repo stringclasses 1 value | instance_id stringlengths 22 24 | problem_statement stringlengths 30 24.1k | patch stringlengths 0 1.9M | test_patch stringclasses 1 value | created_at stringdate 2022-11-25 05:12:07 2025-06-13 10:24:29 | hints_text stringlengths 0 228k | base_commit stringlengths 40 40 | test_instructions stringlengths 0 232k | filenames listlengths 0 300 |
|---|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | juspay__hyperswitch-3818 | Bug: [FEATURE] : [Fiserv] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index e2511dc8d56..b8dd3c9643f 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -62,8 +62,8 @@ pub enum Source {
},
#[allow(dead_code)]
GooglePay {
- data: String,
- signature: String,
+ data: Secret<String>,
+ signature: Secret<String>,
version: String,
},
}
@@ -80,8 +80,8 @@ pub struct CardData {
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayToken {
- signature: String,
- signed_message: String,
+ signature: Secret<String>,
+ signed_message: Secret<String>,
protocol_version: String,
}
@@ -104,7 +104,7 @@ pub struct TransactionDetails {
#[serde(rename_all = "camelCase")]
pub struct MerchantDetails {
merchant_id: Secret<String>,
- terminal_id: Option<String>,
+ terminal_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
@@ -428,7 +428,7 @@ pub struct ReferenceTransactionDetails {
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FiservSessionObject {
- pub terminal_id: String,
+ pub terminal_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject {
| 2024-02-26T09:58:16Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Fiserv.
## Test case
1. Create a card payment with fiserv
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
1.b. Check if all the sensitive data in the `masked_response` and also in `request` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Masked Request
```
request\":\"{\\\"amount\\\":{\\\"total\\\":20.0,\\\"currency\\\":\\\"USD\\\"},\\\"source\\\":{\\\"sourceType\\\":\\\"PaymentCard\\\",\\\"card\\\":{\\\"cardData\\\":\\\"411111**********\\\",\\\"expirationMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"expirationYear\\\":\\\"*** alloc::string::String ***\\\",\\\"securityCode\\\":\\\"*** alloc::string::String ***\\\"}},\\\"transactionDetails\\\":{\\\"captureFlag\\\":true,\\\"reversalReasonCode\\\":null,\\\"merchantTransactionId\\\":\\\"pay_IRGqmgQ7FkrCPXxyCWfa_1\\\"},\\\"merchantDetails\\\":{\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"terminalId\\\":\\\"*** alloc::string::String ***\\\"},\\\"transactionInteraction\\\":{\\\"origin\\\":\\\"ECOM\\\",\\\"eciIndicator\\\":\\\"CHANNEL_ENCRYPTED\\\",\\\"posConditionCode\\\":\\\"CARD_NOT_PRESENT_ECOM\\\"}}
```
Masked Response
```
"masked_response\":\"{\\\"gatewayResponse\\\":{\\\"gatewayTransactionId\\\":null,\\\"transactionState\\\":\\\"CAPTURED\\\",\\\"transactionProcessingDetails\\\":{\\\"orderId\\\":\\\"CHG01a86281900c326c5f580655313a9cc7cb\\\",\\\"transactionId\\\":\\\"4a695b8bd77b448d80ebb13640561fe7\\\"}}}
```
## Impacted Area
> Payment Create flow | 75c633fc7c37341177597041ccbcdfc3cf9e236f | [
"crates/router/src/connector/fiserv/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3816 | Bug: [Analytics] - Add error_reason field in clickhouse column
| diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
deleted file mode 100644
index 92a748ff489..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
+++ /dev/null
@@ -1,142 +0,0 @@
-CREATE TABLE hyperswitch.dispute_queue on cluster '{cluster}' (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
- `created_at` DateTime CODEC(T64, LZ4),
- `modified_at` DateTime CODEC(T64, LZ4),
- `connector` LowCardinality(String),
- `evidence` Nullable(String),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `sign_flag` Int8
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
-kafka_topic_list = 'hyperswitch-dispute-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-
-CREATE MATERIALIZED VIEW hyperswitch.dispute_mv on cluster '{cluster}' TO hyperswitch.dispute (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime64(3)),
- `connector_created_at` Nullable(DateTime64(3)),
- `connector_updated_at` Nullable(DateTime64(3)),
- `created_at` DateTime64(3),
- `modified_at` DateTime64(3),
- `connector` LowCardinality(String),
- `evidence` Nullable(String),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `inserted_at` DateTime64(3),
- `sign_flag` Int8
-) AS
-SELECT
- dispute_id,
- amount,
- currency,
- dispute_stage,
- dispute_status,
- payment_id,
- attempt_id,
- merchant_id,
- connector_status,
- connector_dispute_id,
- connector_reason,
- connector_reason_code,
- challenge_required_by,
- connector_created_at,
- connector_updated_at,
- created_at,
- modified_at,
- connector,
- evidence,
- profile_id,
- merchant_connector_id,
- now() as inserted_at,
- sign_flag
-FROM
- hyperswitch.dispute_queue
-WHERE length(_error) = 0;
-
-
-CREATE TABLE hyperswitch.dispute_clustered on cluster '{cluster}' (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `connector` LowCardinality(String),
- `evidence` String DEFAULT '{}' CODEC(T64, LZ4),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8
- INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
- INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
- INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedCollapsingMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/dispute_clustered',
- '{replica}',
- dispute_status
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, dispute_id)
-TTL created_at + toIntervalMonth(6);
-
-
-CREATE MATERIALIZED VIEW hyperswitch.dispute_parse_errors on cluster '{cluster}'
-(
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-)
-ENGINE = MergeTree
-ORDER BY (topic, partition, offset)
-SETTINGS index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM hyperswitch.dispute_queue
-WHERE length(_error) > 0
-;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/api_events.sql b/crates/analytics/docs/clickhouse/scripts/api_events.sql
index 49a6472eaa4..e466fc56cb6 100644
--- a/crates/analytics/docs/clickhouse/scripts/api_events.sql
+++ b/crates/analytics/docs/clickhouse/scripts/api_events.sql
@@ -58,7 +58,7 @@ CREATE TABLE api_events_dist (
`hs_latency` Nullable(UInt128),
`http_method` LowCardinality(String),
`url_path` String,
- `dispute_id` Nullable(String)
+ `dispute_id` Nullable(String),
INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1,
INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1,
INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
index 276e311e57a..8b7715044c1 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
@@ -29,6 +29,15 @@ CREATE TABLE payment_attempts_queue (
`created_at` DateTime CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`modified_at` DateTime CODEC(T64, LZ4),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-attempt-events',
@@ -67,6 +76,15 @@ CREATE TABLE payment_attempt_dist (
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
@@ -115,6 +133,15 @@ CREATE MATERIALIZED VIEW kafka_parse_pa TO payment_attempt_dist (
`capture_on` Nullable(DateTime64(3)),
`last_synced` Nullable(DateTime64(3)),
`modified_at` DateTime64(3),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`inserted_at` DateTime64(3),
`sign_flag` Int8
) AS
@@ -149,6 +176,15 @@ SELECT
capture_on,
last_synced,
modified_at,
+ payment_method_data,
+ error_reason,
+ multiple_capture_count,
+ amount_capturable,
+ merchant_connector_id,
+ net_amount,
+ unified_code,
+ unified_message,
+ mandate_data,
now() as inserted_at,
sign_flag
FROM
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index ea0721f418e..98f88fb69f5 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -1,4 +1,5 @@
-use data_models::payments::payment_attempt::PaymentAttempt;
+// use diesel_models::enums::MandateDetails;
+use data_models::{mandates::MandateDetails, payments::payment_attempt::PaymentAttempt};
use diesel_models::enums as storage_enums;
use time::OffsetDateTime;
@@ -39,6 +40,15 @@ pub struct KafkaPaymentAttempt<'a> {
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
+ pub payment_method_data: Option<String>,
+ pub error_reason: Option<&'a String>,
+ pub multiple_capture_count: Option<i16>,
+ pub amount_capturable: i64,
+ pub merchant_connector_id: Option<&'a String>,
+ pub net_amount: i64,
+ pub unified_code: Option<&'a String>,
+ pub unified_message: Option<&'a String>,
+ pub mandate_data: Option<&'a MandateDetails>,
}
impl<'a> KafkaPaymentAttempt<'a> {
@@ -74,6 +84,15 @@ impl<'a> KafkaPaymentAttempt<'a> {
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
+ payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
+ error_reason: attempt.error_reason.as_ref(),
+ multiple_capture_count: attempt.multiple_capture_count,
+ amount_capturable: attempt.amount_capturable,
+ merchant_connector_id: attempt.merchant_connector_id.as_ref(),
+ net_amount: attempt.net_amount,
+ unified_code: attempt.unified_code.as_ref(),
+ unified_message: attempt.unified_message.as_ref(),
+ mandate_data: attempt.mandate_data.as_ref(),
}
}
}
| 2024-02-26T07:09:51Z |
## Description
<!-- Adding new fields in Kafka struct for analytics usecase -->
This PR adds more fields which we would want to send to Kafka for various usecases of search and analytics from attempts table in PSQL
Fields which have been added are
```
payment_method_data,
error_reason,
multiple_capture_count,
amount_capturable,
merchant_connector_id,
net_amount,
unified_code,
unified_message,
mandate_data,
```
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | f4d0e2b441a25048186be4b9d0871e2473a6f357 |
Curl
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: key' \
--data-raw '{
"amount": 60,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 60,
"customer_id": "SHIVANSH",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```

Tested it locally , by creating payments and observing what events are being generated for that payment which is being pushed to Kafka
Can test the changes in loki though once deployed
As soon as we deploy this
The fields which we have
We’ll get those fields under `topic="hyperswitch-payment-attempt-events"`
| [
"crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql",
"crates/analytics/docs/clickhouse/scripts/api_events.sql",
"crates/analytics/docs/clickhouse/scripts/payment_attempts.sql",
"crates/router/src/services/kafka/payment_attempt.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3867 | Bug: [Analytics]/[Dispute] Create API's endpoints for disputes analytics
These are the metrics needed
- Number of disputes
- disputes challenged
- disputes won
- disputes lost
- Total amount disputed
- Total dispute lost amount
## Filters
## Group By Dimensions | diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index fed029f2edb..6ebac7c1d92 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -23,7 +23,7 @@ use crate::{
metrics::{latency::LatencyAvg, ApiEventMetricRow},
},
connector_events::events::ConnectorEventsResult,
- disputes::filters::DisputeFilterRow,
+ disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow},
outgoing_webhook_event::events::OutgoingWebhookLogsResult,
sdk_events::events::SdkEventsResult,
types::TableEngine,
@@ -170,6 +170,7 @@ impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
{
}
impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {}
+impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {}
#[derive(Debug, serde::Serialize)]
struct CkhQuery {
@@ -278,6 +279,17 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
))
}
}
+impl TryInto<DisputeMetricRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<DisputeMetricRow, Self::Error> {
+ serde_json::from_value(self)
+ .into_report()
+ .change_context(ParsingError::StructParseFailure(
+ "Failed to parse DisputeMetricRow in clickhouse results",
+ ))
+ }
+}
impl TryInto<DisputeFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
diff --git a/crates/analytics/src/disputes.rs b/crates/analytics/src/disputes.rs
index b6d7e6280c7..8cf1b3db0fd 100644
--- a/crates/analytics/src/disputes.rs
+++ b/crates/analytics/src/disputes.rs
@@ -1,5 +1,9 @@
+pub mod accumulators;
mod core;
-
pub mod filters;
+pub mod metrics;
+pub mod types;
+pub use accumulators::{DisputeMetricAccumulator, DisputeMetricsAccumulator};
-pub use self::core::get_filters;
+pub trait DisputeAnalytics: metrics::DisputeMetricAnalytics {}
+pub use self::core::{get_filters, get_metrics};
diff --git a/crates/analytics/src/disputes/accumulators.rs b/crates/analytics/src/disputes/accumulators.rs
new file mode 100644
index 00000000000..1997d75d323
--- /dev/null
+++ b/crates/analytics/src/disputes/accumulators.rs
@@ -0,0 +1,100 @@
+use api_models::analytics::disputes::DisputeMetricsBucketValue;
+use diesel_models::enums as storage_enums;
+
+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,
+}
+#[derive(Debug, Default)]
+pub struct RateAccumulator {
+ pub won_count: i64,
+ pub challenged_count: i64,
+ pub lost_count: i64,
+ pub total: i64,
+}
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct SumAccumulator {
+ pub total: Option<i64>,
+}
+
+pub trait DisputeMetricAccumulator {
+ type MetricOutput;
+
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow);
+
+ fn collect(self) -> Self::MetricOutput;
+}
+
+impl DisputeMetricAccumulator for SumAccumulator {
+ type MetricOutput = Option<u64>;
+ #[inline]
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
+ self.total = match (
+ self.total,
+ metrics
+ .total
+ .as_ref()
+ .and_then(bigdecimal::ToPrimitive::to_i64),
+ ) {
+ (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())
+ }
+}
+
+impl DisputeMetricAccumulator for RateAccumulator {
+ type MetricOutput = Option<(Option<u64>, Option<u64>, Option<u64>, Option<u64>)>;
+
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
+ if let Some(ref dispute_status) = metrics.dispute_status {
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeChallenged {
+ self.challenged_count += metrics.count.unwrap_or_default();
+ }
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeWon {
+ self.won_count += metrics.count.unwrap_or_default();
+ }
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeLost {
+ self.lost_count += metrics.count.unwrap_or_default();
+ }
+ };
+
+ self.total += metrics.count.unwrap_or_default();
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total <= 0 {
+ Some((None, None, None, None))
+ } else {
+ Some((
+ u64::try_from(self.challenged_count).ok(),
+ u64::try_from(self.won_count).ok(),
+ u64::try_from(self.lost_count).ok(),
+ u64::try_from(self.total).ok(),
+ ))
+ }
+ }
+}
+
+impl DisputeMetricsAccumulator {
+ pub fn collect(self) -> DisputeMetricsBucketValue {
+ let (challenge_rate, won_rate, lost_rate, total_dispute) =
+ self.disputes_status_rate.collect().unwrap_or_default();
+ DisputeMetricsBucketValue {
+ 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(),
+ total_dispute,
+ }
+ }
+}
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs
index 8ccbbdea6d2..ae013aa81d1 100644
--- a/crates/analytics/src/disputes/core.rs
+++ b/crates/analytics/src/disputes/core.rs
@@ -1,15 +1,125 @@
+use std::collections::HashMap;
+
use api_models::analytics::{
- disputes::DisputeDimensions, DisputeFilterValue, DisputeFiltersResponse,
- GetDisputeFilterRequest,
+ disputes::{
+ DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier,
+ DisputeMetricsBucketResponse,
+ },
+ AnalyticsMetadata, DisputeFilterValue, DisputeFiltersResponse, GetDisputeFilterRequest,
+ GetDisputeMetricRequest, MetricsResponse,
+};
+use error_stack::{IntoReport, ResultExt};
+use router_env::{
+ logger,
+ tracing::{self, Instrument},
};
-use error_stack::ResultExt;
-use super::filters::{get_dispute_filter_for_dimension, DisputeFilterRow};
+use super::{
+ filters::{get_dispute_filter_for_dimension, DisputeFilterRow},
+ DisputeMetricsAccumulator,
+};
use crate::{
+ disputes::DisputeMetricAccumulator,
errors::{AnalyticsError, AnalyticsResult},
- AnalyticsProvider,
+ metrics, AnalyticsProvider,
};
+pub async fn get_metrics(
+ pool: &AnalyticsProvider,
+ merchant_id: &String,
+ req: GetDisputeMetricRequest,
+) -> AnalyticsResult<MetricsResponse<DisputeMetricsBucketResponse>> {
+ let mut metrics_accumulator: HashMap<
+ DisputeMetricsBucketIdentifier,
+ DisputeMetricsAccumulator,
+ > = HashMap::new();
+ let mut set = tokio::task::JoinSet::new();
+ for metric_type in req.metrics.iter().cloned() {
+ let req = req.clone();
+ let pool = pool.clone();
+ let task_span = tracing::debug_span!(
+ "analytics_dispute_query",
+ refund_metric = metric_type.as_ref()
+ );
+ // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference
+ // We can optimize away this clone once that is fixed
+ let merchant_id_scoped = merchant_id.to_owned();
+ set.spawn(
+ async move {
+ let data = pool
+ .get_dispute_metrics(
+ &metric_type,
+ &req.group_by_names.clone(),
+ &merchant_id_scoped,
+ &req.filters,
+ &req.time_series.map(|t| t.granularity),
+ &req.time_range,
+ )
+ .await
+ .change_context(AnalyticsError::UnknownError);
+ (metric_type, data)
+ }
+ .instrument(task_span),
+ );
+ }
+
+ while let Some((metric, data)) = set
+ .join_next()
+ .await
+ .transpose()
+ .into_report()
+ .change_context(AnalyticsError::UnknownError)?
+ {
+ let data = data?;
+ let attributes = &[
+ metrics::request::add_attributes("metric_type", metric.to_string()),
+ metrics::request::add_attributes("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);
+ }
+
+ 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 {
+ DisputeMetrics::DisputeStatusMetric => 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
+ .add_metrics_bucket(&value),
+ }
+ }
+
+ logger::debug!(
+ "Analytics Accumulated Results: metric: {}, results: {:#?}",
+ metric,
+ metrics_accumulator
+ );
+ }
+ let query_data: Vec<DisputeMetricsBucketResponse> = metrics_accumulator
+ .into_iter()
+ .map(|(id, val)| DisputeMetricsBucketResponse {
+ values: val.collect(),
+ dimensions: id,
+ })
+ .collect();
+
+ Ok(MetricsResponse {
+ query_data,
+ meta_data: [AnalyticsMetadata {
+ current_time_range: req.time_range,
+ }],
+ })
+}
+
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetDisputeFilterRequest,
@@ -76,9 +186,7 @@ pub async fn get_filters(
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: DisputeFilterRow| match dim {
- DisputeDimensions::DisputeStatus => fil.dispute_status,
DisputeDimensions::DisputeStage => fil.dispute_stage,
- DisputeDimensions::ConnectorStatus => fil.connector_status,
DisputeDimensions::Connector => fil.connector,
})
.collect::<Vec<String>>();
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
new file mode 100644
index 00000000000..4963626d0fa
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -0,0 +1,119 @@
+mod dispute_status_metric;
+mod total_amount_disputed;
+mod total_dispute_lost_amount;
+
+use api_models::{
+ analytics::{
+ disputes::{
+ DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier,
+ },
+ Granularity,
+ },
+ payments::TimeRange,
+};
+use diesel_models::enums as storage_enums;
+use time::PrimitiveDateTime;
+
+use self::{
+ dispute_status_metric::DisputeStatusMetric, total_amount_disputed::TotalAmountDisputed,
+ total_dispute_lost_amount::TotalDisputeLostAmount,
+};
+use crate::{
+ query::{Aggregate, GroupByClause, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
+};
+#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
+pub struct DisputeMetricRow {
+ pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>,
+ pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>,
+ pub connector: Option<String>,
+ pub total: Option<bigdecimal::BigDecimal>,
+ pub count: Option<i64>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub start_bucket: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub end_bucket: Option<PrimitiveDateTime>,
+}
+
+pub trait DisputeMetricAnalytics: LoadRow<DisputeMetricRow> {}
+
+#[async_trait::async_trait]
+pub trait DisputeMetric<T>
+where
+ T: AnalyticsDataSource + 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],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>;
+}
+
+#[async_trait::async_trait]
+impl<T> DisputeMetric<T> for DisputeMetrics
+where
+ T: AnalyticsDataSource + 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],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> {
+ match self {
+ Self::TotalAmountDisputed => {
+ TotalAmountDisputed::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::DisputeStatusMetric => {
+ DisputeStatusMetric::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::TotalDisputeLostAmount => {
+ TotalDisputeLostAmount::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ }
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
new file mode 100644
index 00000000000..5b97021becc
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
@@ -0,0 +1,119 @@
+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::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) 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],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ 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()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .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<
+ Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
new file mode 100644
index 00000000000..cbba553aa85
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
@@ -0,0 +1,116 @@
+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::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) 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],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ 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()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .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<Vec<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
new file mode 100644
index 00000000000..c7be2ab1a98
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
@@ -0,0 +1,117 @@
+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::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) 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],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ 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()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .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<Vec<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/disputes/types.rs b/crates/analytics/src/disputes/types.rs
new file mode 100644
index 00000000000..762e8d27554
--- /dev/null
+++ b/crates/analytics/src/disputes/types.rs
@@ -0,0 +1,29 @@
+use api_models::analytics::disputes::{DisputeDimensions, DisputeFilters};
+use error_stack::ResultExt;
+
+use crate::{
+ query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
+ types::{AnalyticsCollection, AnalyticsDataSource},
+};
+
+impl<T> QueryFilter<T> for DisputeFilters
+where
+ T: AnalyticsDataSource,
+ AnalyticsCollection: ToSql<T>,
+{
+ fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
+ if !self.connector.is_empty() {
+ builder
+ .add_filter_in_range_clause(DisputeDimensions::Connector, &self.connector)
+ .attach_printable("Error adding connector filter")?;
+ }
+
+ if !self.dispute_stage.is_empty() {
+ builder
+ .add_filter_in_range_clause(DisputeDimensions::DisputeStage, &self.dispute_stage)
+ .attach_printable("Error adding dispute stage filter")?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 0fb8d9eea6e..c9752bd27a6 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -15,6 +15,7 @@ pub mod sdk_events;
mod sqlx;
mod types;
use api_event::metrics::{ApiEventMetric, ApiEventMetricRow};
+use disputes::metrics::{DisputeMetric, DisputeMetricRow};
pub use types::AnalyticsDomain;
pub mod lambda_utils;
pub mod utils;
@@ -25,6 +26,7 @@ use api_models::analytics::{
api_event::{
ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier,
},
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier},
refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier},
sdk_events::{
@@ -393,6 +395,106 @@ impl AnalyticsProvider {
.await
}
+ pub async fn get_dispute_metrics(
+ &self,
+ metric: &DisputeMetrics,
+ dimensions: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ ) -> types::MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> {
+ // Metrics to get the fetch time for each refund metric
+ metrics::request::record_operation_time(
+ async {
+ match self {
+ Self::Sqlx(pool) => {
+ metric
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::Clickhouse(pool) => {
+ metric
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::CombinedCkh(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ )
+ );
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics metrics")
+ }
+ _ => {}
+ };
+ ckh_result
+ }
+ Self::CombinedSqlx(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ )
+ );
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics metrics")
+ }
+ _ => {}
+ };
+ sqlx_result
+ }
+ }
+ },
+ &metrics::METRIC_FETCH_TIME,
+ metric,
+ self,
+ )
+ .await
+ }
+
pub async fn get_sdk_event_metrics(
&self,
metric: &SdkEventMetrics,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index bc21ab8f0f4..27e4154a1a9 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -11,7 +11,8 @@ use api_models::{
Granularity,
},
enums::{
- AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType,
+ AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, PaymentMethod,
+ PaymentMethodType,
},
refunds::RefundStatus,
};
@@ -363,8 +364,6 @@ impl_to_sql_for_to_string!(
PaymentDimensions,
&PaymentDistributions,
RefundDimensions,
- &DisputeDimensions,
- DisputeDimensions,
PaymentMethod,
PaymentMethodType,
AuthenticationType,
@@ -386,6 +385,8 @@ impl_to_sql_for_to_string!(&SdkEventDimensions, SdkEventDimensions, SdkEventName
impl_to_sql_for_to_string!(&ApiEventDimensions, ApiEventDimensions);
+impl_to_sql_for_to_string!(&DisputeDimensions, DisputeDimensions, DisputeStage);
+
#[derive(Debug)]
pub enum FilterTypes {
Equal,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 0aeffeafa9e..e88fe519c3c 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -1,6 +1,9 @@
use std::{fmt::Display, str::FromStr};
-use api_models::analytics::refunds::RefundType;
+use api_models::{
+ analytics::refunds::RefundType,
+ enums::{DisputeStage, DisputeStatus},
+};
use common_utils::errors::{CustomResult, ParsingError};
use diesel_models::enums::{
AttemptStatus, AuthenticationType, Currency, PaymentMethod, RefundStatus,
@@ -89,6 +92,8 @@ db_type!(AttemptStatus);
db_type!(PaymentMethod, TEXT);
db_type!(RefundStatus);
db_type!(RefundType);
+db_type!(DisputeStage);
+db_type!(DisputeStatus);
impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type>
where
@@ -145,6 +150,7 @@ impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient
impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}
impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {}
impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {}
+impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {}
#[async_trait::async_trait]
impl AnalyticsDataSource for SqlxClient {
@@ -454,6 +460,48 @@ impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow {
})
}
}
+impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let dispute_stage: Option<DBEnumWrapper<DisputeStage>> =
+ row.try_get("dispute_stage").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let dispute_status: Option<DBEnumWrapper<DisputeStatus>> =
+ row.try_get("dispute_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 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),
+ })?;
+ // 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 {
+ dispute_stage,
+ dispute_status,
+ connector,
+ total,
+ count,
+ start_bucket,
+ end_bucket,
+ })
+ }
+}
impl ToSql<SqlxClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index c12f8e7adfe..1434c357798 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -5,7 +5,7 @@ use masking::Secret;
use self::{
api_event::{ApiEventDimensions, ApiEventMetrics},
- disputes::DisputeDimensions,
+ disputes::{DisputeDimensions, DisputeMetrics},
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
@@ -271,3 +271,17 @@ pub struct DisputeFilterValue {
pub dimension: DisputeDimensions,
pub values: Vec<String>,
}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetDisputeMetricRequest {
+ pub time_series: Option<TimeSeries>,
+ pub time_range: TimeRange,
+ #[serde(default)]
+ pub group_by_names: Vec<DisputeDimensions>,
+ #[serde(default)]
+ pub filters: disputes::DisputeFilters,
+ pub metrics: HashSet<DisputeMetrics>,
+ #[serde(default)]
+ pub delta: bool,
+}
diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs
index 4b4b7ba3830..edb85c129e6 100644
--- a/crates/api_models/src/analytics/disputes.rs
+++ b/crates/api_models/src/analytics/disputes.rs
@@ -1,4 +1,10 @@
-use super::NameDescription;
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+};
+
+use super::{NameDescription, TimeRange};
+use crate::enums::DisputeStage;
#[derive(
Clone,
@@ -15,9 +21,7 @@ use super::NameDescription;
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum DisputeMetrics {
- DisputesChallenged,
- DisputesWon,
- DisputesLost,
+ DisputeStatusMetric,
TotalAmountDisputed,
TotalDisputeLostAmount,
}
@@ -42,8 +46,6 @@ pub enum DisputeDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
- DisputeStatus,
- ConnectorStatus,
DisputeStage,
}
@@ -64,3 +66,70 @@ impl From<DisputeMetrics> for NameDescription {
}
}
}
+
+#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
+pub struct DisputeFilters {
+ #[serde(default)]
+ pub dispute_stage: Vec<DisputeStage>,
+ pub connector: Vec<String>,
+}
+
+#[derive(Debug, serde::Serialize, Eq)]
+pub struct DisputeMetricsBucketIdentifier {
+ pub dispute_stage: Option<DisputeStage>,
+ pub connector: Option<String>,
+ #[serde(rename = "time_range")]
+ pub time_bucket: TimeRange,
+ #[serde(rename = "time_bucket")]
+ #[serde(with = "common_utils::custom_serde::iso8601custom")]
+ pub start_time: time::PrimitiveDateTime,
+}
+
+impl Hash for DisputeMetricsBucketIdentifier {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.dispute_stage.hash(state);
+ self.connector.hash(state);
+ self.time_bucket.hash(state);
+ }
+}
+impl PartialEq for DisputeMetricsBucketIdentifier {
+ fn eq(&self, other: &Self) -> bool {
+ let mut left = DefaultHasher::new();
+ self.hash(&mut left);
+ let mut right = DefaultHasher::new();
+ other.hash(&mut right);
+ left.finish() == right.finish()
+ }
+}
+
+impl DisputeMetricsBucketIdentifier {
+ pub fn new(
+ dispute_stage: Option<DisputeStage>,
+ connector: Option<String>,
+ normalized_time_range: TimeRange,
+ ) -> Self {
+ Self {
+ dispute_stage,
+ connector,
+ time_bucket: normalized_time_range,
+ start_time: normalized_time_range.start_time,
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+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 total_dispute: Option<u64>,
+}
+#[derive(Debug, serde::Serialize)]
+pub struct DisputeMetricsBucketResponse {
+ #[serde(flatten)]
+ pub values: DisputeMetricsBucketValue,
+ #[serde(flatten)]
+ pub dimensions: DisputeMetricsBucketIdentifier,
+}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 59b2d54016a..218881389db 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -97,7 +97,8 @@ impl_misc_api_event_type!(
ConnectorEventsRequest,
OutgoingWebhookLogsRequest,
GetDisputeFilterRequest,
- DisputeFiltersResponse
+ DisputeFiltersResponse,
+ GetDisputeMetricRequest
);
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 51fb6ff822b..f7bee88b8c3 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -9,8 +9,9 @@ pub mod routes {
};
use api_models::analytics::{
GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest,
- GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest,
- GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
+ GetDisputeMetricRequest, GetPaymentFiltersRequest, GetPaymentMetricRequest,
+ GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest,
+ GetSdkEventMetricRequest, ReportRequest,
};
use error_stack::ResultExt;
use router_env::AnalyticsFlow;
@@ -92,6 +93,10 @@ pub mod routes {
web::resource("filters/disputes")
.route(web::post().to(get_dispute_filters)),
)
+ .service(
+ web::resource("metrics/disputes")
+ .route(web::post().to(get_dispute_metrics)),
+ )
}
route
}
@@ -612,4 +617,39 @@ pub mod routes {
))
.await
}
+ /// # Panics
+ ///
+ /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
+ pub async fn get_dispute_metrics(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<[GetDisputeMetricRequest; 1]>,
+ ) -> impl Responder {
+ // safety: This shouldn't panic owing to the data type
+ #[allow(clippy::expect_used)]
+ let payload = json_payload
+ .into_inner()
+ .to_vec()
+ .pop()
+ .expect("Couldn't get GetDisputeMetricRequest");
+ let flow = AnalyticsFlow::GetDisputeMetrics;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req| async move {
+ analytics::disputes::get_metrics(
+ &state.pool,
+ &auth.merchant_account.merchant_id,
+ req,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index 0091de588f1..0f309ce5de0 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -33,6 +33,7 @@ pub enum EventType {
ApiLogs,
ConnectorApiLogs,
OutgoingWebhookLogs,
+ Dispute,
}
#[derive(Debug, Default, Deserialize, Clone)]
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index ef9352e55b4..ab4a8948a6b 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -347,6 +347,7 @@ impl KafkaProducer {
EventType::Refund => &self.refund_analytics_topic,
EventType::ConnectorApiLogs => &self.connector_logs_topic,
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
+ EventType::Dispute => &self.dispute_analytics_topic,
}
}
}
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index 3ccdbe53cb1..2925bb5221d 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -7,7 +7,7 @@ use crate::types::storage::dispute::Dispute;
#[derive(serde::Serialize, Debug)]
pub struct KafkaDispute<'a> {
pub dispute_id: &'a String,
- pub amount: &'a String,
+ pub dispute_amount: i64,
pub currency: &'a String,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
@@ -38,7 +38,7 @@ impl<'a> KafkaDispute<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
Self {
dispute_id: &dispute.dispute_id,
- amount: &dispute.amount,
+ dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(),
currency: &dispute.currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index be6aa257d74..b68cdcc6fcc 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -55,6 +55,7 @@ pub enum AnalyticsFlow {
GetConnectorEvents,
GetOutgoingWebhookEvents,
GetDisputeFilters,
+ GetDisputeMetrics,
}
impl FlowMetric for AnalyticsFlow {}
| 2024-02-25T16:55:50Z |
## Description
adding metric api for dispute analytics
Http Method: ```POST```
URL Path ```/analytics/v1/metric/dispute```
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 8b32dffe324a4cdbfde173cffe3fad2e839a52aa |
Hit the URL given below and should get sample response mentioned in the comment
| [
"crates/analytics/src/clickhouse.rs",
"crates/analytics/src/disputes.rs",
"crates/analytics/src/disputes/accumulators.rs",
"crates/analytics/src/disputes/core.rs",
"crates/analytics/src/disputes/metrics.rs",
"crates/analytics/src/disputes/metrics/dispute_status_metric.rs",
"crates/analytics/src/disputes... | |
juspay/hyperswitch | juspay__hyperswitch-3806 | Bug: [BUG] collections fail to import if variable is not a string
Newman runner i.e., newman-dir does support dynamic values but only string variables and not other variables say integer. Hence, variables like `"{{value}}"` is the only way for you to export the collection json file to its directory structure and having the variables like `{{value}}` will result in the `dir-export` / `dir-import` commands to fail.
This bug affects collections that use dynamic values for amount fields. One such connector is NMI which has a hard limit on transactions i.e., once a payment for a n amount is done, the payment cannot be repeated up until the next 20 mins. If not, the payment is flagged as duplicate. The only work around for this is to use dynamic values. But that is restricted because of this bug with `newman-dir`.
One work around that we can do is to:
- export the collection to its json format
- remove double quotes (`\"`) for integer fields
- run the collection -- json and not dir
- and all this should happen in run time
Example:
```sh
newman dir-import -o /tmp/generated_collection.json
perl -pi -e 's/\\"{{value}}\\"/{{value}}/g' /tmp/generated_collection.json
newman run /tmp/generated_collection.json
```
We can use `sed` / `regex` instead of `perl` as well.
Reference:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9a9eef47fb334cb686b2fff360e09536
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4e5ead4663c85da803b0a2c2030852eb
https://regex101.com/r/G6iapi/1
https://www.regular-expressions.info/named.html
| diff --git a/Cargo.lock b/Cargo.lock
index 2c9293c1701..7823e917ed5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4977,14 +4977,14 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.9.6"
+version = "1.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff"
+checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15"
dependencies = [
"aho-corasick",
"memchr",
- "regex-automata 0.3.9",
- "regex-syntax 0.7.5",
+ "regex-automata 0.4.5",
+ "regex-syntax 0.8.2",
]
[[package]]
@@ -4998,13 +4998,13 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.3.9"
+version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9"
+checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd"
dependencies = [
"aho-corasick",
"memchr",
- "regex-syntax 0.7.5",
+ "regex-syntax 0.8.2",
]
[[package]]
@@ -5031,6 +5031,12 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
+[[package]]
+name = "regex-syntax"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
+
[[package]]
name = "rend"
version = "0.4.1"
@@ -6356,6 +6362,7 @@ dependencies = [
"clap",
"masking",
"rand 0.8.5",
+ "regex",
"reqwest",
"serde",
"serde_json",
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index ceb188b74db..59ff36e6cc5 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -17,6 +17,7 @@ async-trait = "0.1.68"
base64 = "0.21.2"
clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] }
rand = "0.8.5"
+regex = "1.10.3"
reqwest = { version = "0.11.18", features = ["native-tls"] }
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs
index 22c91e063d8..006075895b5 100644
--- a/crates/test_utils/src/main.rs
+++ b/crates/test_utils/src/main.rs
@@ -16,28 +16,20 @@ fn main() {
};
let status = child.wait();
- if runner.file_modified_flag {
- let git_status = Command::new("git")
- .args([
- "restore",
- format!("{}/event.prerequest.js", runner.collection_path).as_str(),
- ])
- .output();
+ // Filter out None values leaving behind Some(Path)
+ let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect();
+ let git_status = Command::new("git").arg("restore").args(&paths).output();
- match git_status {
- Ok(output) => {
- if output.status.success() {
- let stdout_str = String::from_utf8_lossy(&output.stdout);
- println!("Git command executed successfully: {stdout_str}");
- } else {
- let stderr_str = String::from_utf8_lossy(&output.stderr);
- eprintln!("Git command failed with error: {stderr_str}");
- }
- }
- Err(e) => {
- eprintln!("Error running Git: {e}");
+ match git_status {
+ Ok(output) => {
+ if !output.status.success() {
+ let stderr_str = String::from_utf8_lossy(&output.stderr);
+ eprintln!("Git command failed with error: {stderr_str}");
}
}
+ Err(e) => {
+ eprintln!("Error running Git: {e}");
+ }
}
let exit_code = match status {
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index 961853548a2..e70c630cffe 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -1,7 +1,14 @@
-use std::{env, io::Write, path::Path, process::Command};
+use std::{
+ env,
+ fs::{self, OpenOptions},
+ io::{self, Write},
+ path::Path,
+ process::{exit, Command},
+};
use clap::{arg, command, Parser};
use masking::PeekInterface;
+use regex::Regex;
use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap};
#[derive(Parser)]
@@ -33,14 +40,24 @@ struct Args {
pub struct ReturnArgs {
pub newman_command: Command,
- pub file_modified_flag: bool,
+ pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
-// Just by the name of the connector, this function generates the name of the collection dir
+// Generates the name of the collection JSON file for the specified connector.
+// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
+#[inline]
+fn get_collection_path(name: impl AsRef<str>) -> String {
+ format!(
+ "postman/collection-json/{}.postman_collection.json",
+ name.as_ref()
+ )
+}
+
+// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
-fn get_path(name: impl AsRef<str>) -> String {
+fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
@@ -72,22 +89,34 @@ pub fn generate_newman_command() -> ReturnArgs {
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
- let collection_path = get_path(&connector_name);
+ let collection_path = get_collection_path(&connector_name);
+ let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
- // Newman runner
- // Depending on the conditions satisfied, variables are added. Since certificates of stripe have already
- // been added to the postman collection, those conditions are set to true and collections that have
- // variables set up for certificate, will consider those variables and will fail.
+ /*
+ Newman runner
+ Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
+ It can be overridden by explicitly passing certificates as arguments.
+
+ If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
+ then Stripe's certificates will be passed implicitly (for now).
+ If any other connector requires certificates to be passed, that has to be passed explicitly for now.
+ */
let mut newman_command = Command::new("newman");
- newman_command.args(["dir-run", &collection_path]);
+ newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
- if let Some(auth_type) = inner_map.get(&connector_name) {
+ let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
+
+ // validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
+ let (connector_name, modified_collection_file_paths) =
+ check_connector_for_dynamic_amount(&connector_name);
+
+ if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
@@ -187,24 +216,126 @@ pub fn generate_newman_command() -> ReturnArgs {
newman_command.arg("--verbose");
}
- let mut modified = false;
- if let Some(headers) = &args.custom_headers {
+ ReturnArgs {
+ newman_command,
+ modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
+ collection_path,
+ }
+}
+
+pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
+ if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
- if insert_content(&collection_path, &content_to_insert).is_ok() {
- modified = true;
+
+ if let Err(err) = insert_content(path, &content_to_insert) {
+ eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {}", header);
}
}
+
+ return Some(format!("{}/event.prerequest.js", path));
}
+ None
+}
- ReturnArgs {
- newman_command,
- file_modified_flag: modified,
- collection_path,
+// If the connector name exists in dynamic_amount_connectors,
+// the corresponding collection is modified at runtime to remove double quotes
+pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
+ let collection_dir_path = get_dir_path(connector_name);
+
+ let dynamic_amount_connectors = ["nmi", "powertranz"];
+
+ if dynamic_amount_connectors.contains(&connector_name) {
+ return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
+ }
+ /*
+ If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
+ since we're running from collections directly, we'll have to export the collection again and it is much simpler.
+ We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
+ to determine the place of edit.
+ */
+ export_collection(connector_name, collection_dir_path);
+
+ (connector_name, None)
+}
+
+/*
+Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
+double quotes without which it fails to execute.
+For integer values like `amount`, this is a bummer as it flags the value stating it is of type
+string and not integer.
+Refactoring is done in 2 steps:
+- Export the collection to json (although the json will be up-to-date, we export it again for safety)
+- Use regex to replace the values which removes double quotes from integer values
+ Ex: \"{{amount}}\" -> {{amount}}
+*/
+
+pub fn remove_quotes_for_integer_values(
+ connector_name: &str,
+) -> Result<(&str, Option<String>), io::Error> {
+ let collection_path = get_collection_path(connector_name);
+ let collection_dir_path = get_dir_path(connector_name);
+
+ let values_to_replace = [
+ "amount",
+ "another_random_number",
+ "capture_amount",
+ "random_number",
+ "refund_amount",
+ ];
+
+ export_collection(connector_name, collection_dir_path);
+
+ let mut contents = fs::read_to_string(&collection_path)?;
+ for value_to_replace in values_to_replace {
+ if let Ok(re) = Regex::new(&format!(
+ r#"\\"(?P<field>\{{\{{{}\}}\}})\\""#,
+ value_to_replace
+ )) {
+ contents = re.replace_all(&contents, "$field").to_string();
+ } else {
+ eprintln!("Regex validation failed.");
+ }
+
+ let mut file = OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .open(&collection_path)?;
+
+ file.write_all(contents.as_bytes())?;
+ }
+
+ Ok((connector_name, Some(collection_path)))
+}
+
+pub fn export_collection(connector_name: &str, collection_dir_path: String) {
+ let collection_path = get_collection_path(connector_name);
+
+ let mut newman_command = Command::new("newman");
+ newman_command.args([
+ "dir-import".to_owned(),
+ collection_dir_path,
+ "-o".to_owned(),
+ collection_path.clone(),
+ ]);
+
+ match newman_command.spawn().and_then(|mut child| child.wait()) {
+ Ok(exit_status) => {
+ if exit_status.success() {
+ println!("Conversion of collection from directory structure to json successful!");
+ } else {
+ eprintln!("Conversion of collection from directory structure to json failed!");
+ exit(exit_status.code().unwrap_or(1));
+ }
+ }
+ Err(err) => {
+ eprintln!("Failed to execute dir-import: {:?}", err);
+ exit(1);
+ }
}
}
diff --git a/postman/collection-dir/aci/Health check/New Request/request.json b/postman/collection-dir/aci/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/aci/Health check/New Request/request.json
+++ b/postman/collection-dir/aci/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/adyen_uk/Health check/New Request/request.json b/postman/collection-dir/adyen_uk/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/adyen_uk/Health check/New Request/request.json
+++ b/postman/collection-dir/adyen_uk/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/airwallex/Health check/New Request/request.json b/postman/collection-dir/airwallex/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/airwallex/Health check/New Request/request.json
+++ b/postman/collection-dir/airwallex/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
+++ b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bambora/Health check/New Request/request.json b/postman/collection-dir/bambora/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bambora/Health check/New Request/request.json
+++ b/postman/collection-dir/bambora/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
+++ b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bankofamerica/Health check/New Request/request.json b/postman/collection-dir/bankofamerica/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/bankofamerica/Health check/New Request/request.json
+++ b/postman/collection-dir/bankofamerica/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/bluesnap/Health check/New Request/request.json b/postman/collection-dir/bluesnap/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bluesnap/Health check/New Request/request.json
+++ b/postman/collection-dir/bluesnap/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/braintree/Health check/New Request/request.json b/postman/collection-dir/braintree/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/braintree/Health check/New Request/request.json
+++ b/postman/collection-dir/braintree/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/checkout/Health check/New Request/request.json b/postman/collection-dir/checkout/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/checkout/Health check/New Request/request.json
+++ b/postman/collection-dir/checkout/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/forte/Health check/New Request/request.json b/postman/collection-dir/forte/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/forte/Health check/New Request/request.json
+++ b/postman/collection-dir/forte/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/globalpay/Health check/New Request/request.json b/postman/collection-dir/globalpay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/globalpay/Health check/New Request/request.json
+++ b/postman/collection-dir/globalpay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/hyperswitch/Health check/New Request/request.json b/postman/collection-dir/hyperswitch/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/hyperswitch/Health check/New Request/request.json
+++ b/postman/collection-dir/hyperswitch/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/mollie/Health check/New Request/request.json b/postman/collection-dir/mollie/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/mollie/Health check/New Request/request.json
+++ b/postman/collection-dir/mollie/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/multisafepay/Health check/New Request/request.json b/postman/collection-dir/multisafepay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/multisafepay/Health check/New Request/request.json
+++ b/postman/collection-dir/multisafepay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/nexinets/Health check/New Request/request.json b/postman/collection-dir/nexinets/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/nexinets/Health check/New Request/request.json
+++ b/postman/collection-dir/nexinets/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
index 6c99817eb04..7b72495e5c4 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
@@ -79,14 +74,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
index 2d931088d18..bad52859824 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
@@ -18,18 +18,14 @@
}
},
"raw_json_formatted": {
- "amount": "{{another_random_number}}"
+ "amount": "{{another_random_number}}",
+ "amount_to_capture": "{{another_random_number}}"
}
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
index 6c99817eb04..7b72495e5c4 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
@@ -79,14 +74,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
index 2d931088d18..bad52859824 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
@@ -18,18 +18,14 @@
}
},
"raw_json_formatted": {
- "amount": "{{another_random_number}}"
+ "amount": "{{another_random_number}}",
+ "amount_to_capture": "{{another_random_number}}"
}
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Health check/New Request/request.json b/postman/collection-dir/nmi/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/nmi/Health check/New Request/request.json
+++ b/postman/collection-dir/nmi/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/payme/Health check/New Request/request.json b/postman/collection-dir/payme/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/payme/Health check/New Request/request.json
+++ b/postman/collection-dir/payme/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/paypal/Health check/New Request/request.json b/postman/collection-dir/paypal/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/paypal/Health check/New Request/request.json
+++ b/postman/collection-dir/paypal/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/powertranz/Health check/New Request/request.json b/postman/collection-dir/powertranz/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/powertranz/Health check/New Request/request.json
+++ b/postman/collection-dir/powertranz/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/rapyd/Health check/New Request/request.json b/postman/collection-dir/rapyd/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/rapyd/Health check/New Request/request.json
+++ b/postman/collection-dir/rapyd/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/shift4/Health check/New Request/request.json b/postman/collection-dir/shift4/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/shift4/Health check/New Request/request.json
+++ b/postman/collection-dir/shift4/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
index fed600e09cd..dfe421f512f 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
@@ -24,23 +24,12 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
}
],
"url": {
"raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- "payment_methods"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["account", "payment_methods"],
"query": [
{
"key": "client_secret",
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
index fed600e09cd..dfe421f512f 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
@@ -24,23 +24,12 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
}
],
"url": {
"raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- "payment_methods"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["account", "payment_methods"],
"query": [
{
"key": "client_secret",
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
index 5b0c090f2be..5a51941cf64 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-dir/stripe/Health check/New Request/request.json b/postman/collection-dir/stripe/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/stripe/Health check/New Request/request.json
+++ b/postman/collection-dir/stripe/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/trustpay/Health check/New Request/request.json b/postman/collection-dir/trustpay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/trustpay/Health check/New Request/request.json
+++ b/postman/collection-dir/trustpay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/volt/Health check/New Request/request.json b/postman/collection-dir/volt/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/volt/Health check/New Request/request.json
+++ b/postman/collection-dir/volt/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/wise/Health check/Health/request.json b/postman/collection-dir/wise/Health check/Health/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/wise/Health check/Health/request.json
+++ b/postman/collection-dir/wise/Health check/Health/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/worldline/Health check/New Request/request.json b/postman/collection-dir/worldline/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/worldline/Health check/New Request/request.json
+++ b/postman/collection-dir/worldline/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/zen/Health check/New Request/request.json b/postman/collection-dir/zen/Health check/New Request/request.json
index 9b836ff05cb..24ea5a4157a 100644
--- a/postman/collection-dir/zen/Health check/New Request/request.json
+++ b/postman/collection-dir/zen/Health check/New Request/request.json
@@ -3,14 +3,7 @@
"type": "noauth"
},
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
| 2024-02-24T17:47:27Z |
## Description
<!-- Describe your changes in detail -->
This PR refactors test_utils crate's `newman_runner` to support dynamic values through postman variables.
The main issue with `newman-dir` is that in order to export the collection, the variables must be of type string (Example: Variable value must be of type `"{{value}}"` and not `{{value}}`) without which the user cannot import or export the collection in directory format which is a bummer.
With this refactor, we've introduced a validation to look after `connector_name` and if it is `nmi` or `powertranz`, we'll be doing the collection refactor in run time (collection refactor here means that before the collection is run, we'll be updating the json collection file by removing the double quotes in the integer values (`amount`) at least in 40+ places) which is later restored after the collection is run.
With this change, we'll again be using `run` command to run the collections instead of `dir-run` going forward.
This also added some complexity with how we're running tests for `custom_headers` and removed that part of code from all the existing collections.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
In order to run NMI collection which is updated here at #3805, this change is needed.
This PR should also close #3806.
# | 6b078fa339b5404f7c730322bc8597cd1104ec15 |
In #3805, the tests ran without any issues. Adding the screenshot below:
<img width="485" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/7c925fb8-b6b0-4eac-9657-ee3c181c6b70">
Yet another validation: https://github.com/juspay/hyperswitch/actions/runs/8092287211/job/22112758729?pr=3807 (i know why it failed, outdated collection-json file which will be updated on next release after this pr is merged)
| [
"Cargo.lock",
"crates/test_utils/Cargo.toml",
"crates/test_utils/src/main.rs",
"crates/test_utils/src/newman_runner.rs",
"postman/collection-dir/aci/Health check/New Request/request.json",
"postman/collection-dir/adyen_uk/Health check/New Request/request.json",
"postman/collection-dir/airwallex/Health c... | |
juspay/hyperswitch | juspay__hyperswitch-3734 | Bug: [CI] Update NMI postman collection
Existing NMI postman collection is outdated and needs to be updated to the latest one look after regressions | 2024-02-24T17:21:42Z |
## Description
<!-- Describe your changes in detail -->
This PR aims at refactoring NMI collection by bringing it back to life. Added more flows to look after regressions.
Closes #3734
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 check for regressions.
# | 734327a957c216511b182151a2f0b27819e7e3bb |
Ran the collection:
<img width="980" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/9aaad0eb-a4d7-4735-9d8c-303d323fc915">
There is a bug in NMI connector which needs to be addressed.
Created a separate collection to reproduce it.
| [] | ||
juspay/hyperswitch | juspay__hyperswitch-3783 | Bug: [FEATURE] [BOA/Cybersource] Pass commerce indicator using card network for apple pay
### Feature Description
Apple pay transactions via BOA and Cybersource require a specific field `commerce_indicator` which is based on the card network type used during apple pay transactions.
https://docs.cybersource.com/content/dam/documentation/en/apple-pay/fdiglobal/so/applepay-so-fdiglobal.pdf
### Possible Implementation
`commerce_indicator` should be passed using the card network data being shared from SDK during apple pay payments for BOA and Cybersource
### 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/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 235321f1ac6..0be25b078bc 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -330,21 +330,34 @@ impl
From<(
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
)> for ProcessingInformation
{
fn from(
- (item, solution): (
+ (item, solution, network): (
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
),
) -> Self {
+ let commerce_indicator = match network {
+ Some(card_network) => match card_network.to_lowercase().as_str() {
+ "amex" => "aesk",
+ "discover" => "dipb",
+ "mastercard" => "spa",
+ "visa" => "internet",
+ _ => "internet",
+ },
+ None => "internet",
+ }
+ .to_string();
Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
- commerce_indicator: String::from("internet"),
+ commerce_indicator,
}
}
}
@@ -552,7 +565,7 @@ impl
card_type,
},
});
- let processing_information = ProcessingInformation::from((item, None));
+ let processing_information = ProcessingInformation::from((item, None, None));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -574,20 +587,25 @@ impl
TryFrom<(
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, apple_pay_data): (
+ (item, apple_pay_data, apple_pay_wallet_data): (
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
- let processing_information =
- ProcessingInformation::from((item, Some(PaymentSolution::ApplePay)));
+ let processing_information = ProcessingInformation::from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_wallet_data.payment_method.network),
+ ));
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month()?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
@@ -640,7 +658,7 @@ impl
},
});
let processing_information =
- ProcessingInformation::from((item, Some(PaymentSolution::GooglePay)));
+ ProcessingInformation::from((item, Some(PaymentSolution::GooglePay), None));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -672,7 +690,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- Self::try_from((item, decrypt_data))
+ Self::try_from((item, decrypt_data, apple_pay_data))
}
types::PaymentMethodToken::Token(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
@@ -685,6 +703,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
let processing_information = ProcessingInformation::from((
item,
Some(PaymentSolution::ApplePay),
+ Some(apple_pay_data.payment_method.network),
));
let client_reference_information =
ClientReferenceInformation::from(item);
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index f96bd50ffc8..2a20999085d 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -207,7 +207,7 @@ pub struct ApplePayPredecrypt {
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
- eci: Option<Secret<String>>,
+ eci: Option<String>,
cryptogram: Secret<String>,
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 646fe179da6..4bb28439b7f 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -489,13 +489,15 @@ impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, solution): (
+ (item, solution, network): (
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
@@ -539,6 +541,17 @@ impl
} else {
(None, None, None)
};
+ let commerce_indicator = match network {
+ Some(card_network) => match card_network.to_lowercase().as_str() {
+ "amex" => "aesk",
+ "discover" => "dipb",
+ "mastercard" => "spa",
+ "visa" => "internet",
+ _ => "internet",
+ },
+ None => "internet",
+ }
+ .to_string();
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
@@ -549,7 +562,7 @@ impl
action_token_types,
authorization_options,
capture_options: None,
- commerce_indicator: String::from("internet"),
+ commerce_indicator,
})
}
}
@@ -721,7 +734,7 @@ impl
},
});
- let processing_information = ProcessingInformation::try_from((item, None))?;
+ let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -820,20 +833,25 @@ impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, apple_pay_data): (
+ (item, apple_pay_data, apple_pay_wallet_data): (
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
- let processing_information =
- ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay)))?;
+ let processing_information = ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_wallet_data.payment_method.network),
+ ))?;
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month()?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
@@ -887,7 +905,7 @@ impl
},
});
let processing_information =
- ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay)))?;
+ ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -922,7 +940,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- Self::try_from((item, decrypt_data))
+ Self::try_from((item, decrypt_data, apple_pay_data))
}
types::PaymentMethodToken::Token(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
@@ -934,9 +952,12 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
build_bill_to(item.router_data.get_billing()?, email)?;
let order_information =
OrderInformationWithBill::from((item, bill_to));
- let processing_information = ProcessingInformation::try_from(
- (item, Some(PaymentSolution::ApplePay)),
- )?;
+ let processing_information =
+ ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_data.payment_method.network),
+ ))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let payment_information = PaymentInformation::ApplePayToken(
@@ -1048,7 +1069,7 @@ impl
String,
),
) -> Result<Self, Self::Error> {
- let processing_information = ProcessingInformation::try_from((item, None))?;
+ let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = CybersoucrePaymentInstrument {
id: connector_mandate_id,
};
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 8c370317c62..7c7a534f1c0 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -489,7 +489,7 @@ pub struct StripeApplePayPredecrypt {
#[serde(rename = "card[cryptogram]")]
cryptogram: Secret<String>,
#[serde(rename = "card[eci]")]
- eci: Option<Secret<String>>,
+ eci: Option<String>,
#[serde(rename = "card[tokenization_method]")]
tokenization_method: String,
}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 7951246790f..fde9195143e 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -949,7 +949,6 @@ impl ApplePayDecrypt for Box<ApplePayPredecryptData> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date
- .peek()
.get(0..2)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
)))
@@ -958,7 +957,6 @@ impl ApplePayDecrypt for Box<ApplePayPredecryptData> {
fn get_expiry_month(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(
self.application_expiration_date
- .peek()
.get(2..4)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_owned(),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 050b0dd4b7b..e13d54f80d1 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1129,6 +1129,8 @@ where
.parse_value::<router_types::ApplePayPredecryptData>("ApplePayPredecryptData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ logger::debug!(?apple_pay_predecrypt);
+
router_data.payment_method_token = Some(router_types::PaymentMethodToken::ApplePayDecrypt(
Box::new(apple_pay_predecrypt),
));
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index e163de9a5da..07691879d4a 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -334,9 +334,9 @@ pub enum PaymentMethodToken {
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptData {
pub application_primary_account_number: Secret<String>,
- pub application_expiration_date: Secret<String>,
- pub currency_code: Secret<String>,
- pub transaction_amount: Secret<i64>,
+ pub application_expiration_date: String,
+ pub currency_code: String,
+ pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramData,
@@ -346,7 +346,7 @@ pub struct ApplePayPredecryptData {
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramData {
pub online_payment_cryptogram: Secret<String>,
- pub eci_indicator: Option<Secret<String>>,
+ pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone)]
| 2024-02-23T08:05:13Z |
## Description
<!-- Describe your changes in detail -->
Apple pay transactions via BOA and Cybersource require a specific field `commerce_indicator` which is based on the card network type used during apple pay transactions.
https://docs.cybersource.com/content/dam/documentation/en/apple-pay/fdiglobal/so/applepay-so-fdiglobal.pdf
This data is now being passed using the card network data being shared from SDK during apple pay payments.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/3783
# | 21d2b6ee2cacecc6da3a3c8ef07dedfb417752b0 |
Apple pay payments need to be tested using simplified and manual flow for connectors BOA and Cybersource.

| [
"crates/router/src/connector/bankofamerica/transformers.rs",
"crates/router/src/connector/checkout/transformers.rs",
"crates/router/src/connector/cybersource/transformers.rs",
"crates/router/src/connector/stripe/transformers.rs",
"crates/router/src/connector/utils.rs",
"crates/router/src/core/payments.rs"... | |
juspay/hyperswitch | juspay__hyperswitch-3793 | Bug: feat: add blacklist for roles
After a role is updated, the users who are using that role at that time should get new tokens. So, the role should be blacklisted.
| diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 3c3f01dc5f9..72f160990e5 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -70,6 +70,8 @@ pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
pub const USER_BLACKLIST_PREFIX: &str = "BU_";
+pub const ROLE_BLACKLIST_PREFIX: &str = "BR_";
+
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 7ce72779bbb..6edbda85bfd 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -12,7 +12,7 @@ use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::AppState,
services::{
- authentication::UserFromToken,
+ authentication::{blacklist, UserFromToken},
authorization::roles::{self, predefined_roles::PREDEFINED_ROLES},
ApplicationResponse,
},
@@ -219,5 +219,7 @@ pub async fn update_role(
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
+ blacklist::insert_role_in_blacklist(&state, role_id).await?;
+
Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 34153ef6e8f..455dc97d03e 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -13,6 +13,7 @@ use masking::ExposeInterface;
use masking::{PeekInterface, StrongSecret};
use serde::Serialize;
+use self::blacklist::BlackList;
use super::authorization::{self, permissions::Permission};
#[cfg(feature = "olap")]
use super::jwt;
@@ -334,7 +335,7 @@ where
state: &A,
) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -499,7 +500,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -528,7 +529,7 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -566,7 +567,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -609,7 +610,7 @@ where
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -659,7 +660,7 @@ where
state: &A,
) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -710,7 +711,7 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -741,7 +742,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 325ef29bad3..346e563ee32 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,10 +5,11 @@ use common_utils::date_time;
use error_stack::{IntoReport, ResultExt};
use redis_interface::RedisConnectionPool;
+use super::{AuthToken, UserAuthToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
- consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX},
+ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
routes::app::AppStateInfo,
};
@@ -34,6 +35,22 @@ pub async fn insert_user_in_blacklist(state: &AppState, user_id: &str) -> UserRe
.change_context(UserErrors::InternalServerError)
}
+#[cfg(feature = "olap")]
+pub async fn insert_role_in_blacklist(state: &AppState, role_id: &str) -> UserResult<()> {
+ let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let expiry =
+ expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
+ let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
+ redis_conn
+ .set_key_with_expiry(
+ role_blacklist_key.as_str(),
+ date_time::now_unix_timestamp(),
+ expiry,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
pub async fn check_user_in_blacklist<A: AppStateInfo>(
state: &A,
user_id: &str,
@@ -49,6 +66,21 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>(
.map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
+pub async fn check_role_in_blacklist<A: AppStateInfo>(
+ state: &A,
+ role_id: &str,
+ token_expiry: u64,
+) -> RouterResult<bool> {
+ let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
+ let redis_conn = get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<i64>>(token.as_str())
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
+}
+
#[cfg(feature = "email")]
pub async fn insert_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
@@ -90,3 +122,33 @@ fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
.into_report()
.change_context(ApiErrorResponse::InternalServerError)
}
+
+#[async_trait::async_trait]
+pub trait BlackList {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync;
+}
+
+#[async_trait::async_trait]
+impl BlackList for AuthToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync,
+ {
+ Ok(
+ check_user_in_blacklist(state, &self.user_id, self.exp).await?
+ || check_role_in_blacklist(state, &self.role_id, self.exp).await?,
+ )
+ }
+}
+
+#[async_trait::async_trait]
+impl BlackList for UserAuthToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync,
+ {
+ check_user_in_blacklist(state, &self.user_id, self.exp).await
+ }
+}
| 2024-02-23T07:21:31Z |
## Description
<!-- Describe your changes in detail -->
This PR adds ability to blacklist roles to stop JWTs after a role is changed.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #3793
# | 21d2b6ee2cacecc6da3a3c8ef07dedfb417752b0 |
Postman.
To get JWT of admin, you have to singup/create a new account. Or you can use a JWT of org_admin user.
1. Create a role
```
curl --location 'http://localhost:8080/user/role' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data '{
"role_name": "custom_role",
"groups": ["users_view"],
"role_scope": "merchant"
}'
```
Response should be 200 OK
This api will create a new custom role. This role can be assigned to people to restrict them.
2. Get the list of roles
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT of Admin'
```
In the response you will find newly created role
```
[
{
"role_id": "role_of8p9odNmf2puQVhQemT",
"permissions": [
"MerchantAccountRead",
"UsersRead"
],
"role_name": "custom_role",
"role_scope": "merchant"
}
]
```
This api is called to get the details of the role that was perviously created.
3. Update a user in the merchant in that merchant account to this newly created role
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data-raw '{
"email": "email of other user in different merchant account",
"name": "user name",
"role_id": "role_of8p9odNmf2puQVhQemT"
}'
```
Response will be 200 OK.
You can use the details you got from the previous api and invite some other person into your org, this will automatically create a new user if user doesn't exist.
4. Login as the user who got invited
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email of user who got udpated",
"password": "password"
}'
```
```
{
"token": "JWT of user who got updated",
"merchant_id": "merchant_id",
"name": "user name",
"email": "email of user who got updated",
"verification_days_left": null,
"user_role": "role_of8p9odNmf2puQVhQemT"
}
```
Use the credentials of the person who was invited to login and save the JWT.
5. Invite a new user with the role_id that was created previously using admin JWT
```
curl --location --request PUT 'http://localhost:8080/user/role/role_of8p9odNmf2puQVhQemT' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data '{
"groups": ["users_view", "users_manage"]
}'
```
Response will be 200 OK.
This api should be hit with Admin JWT again (not the invited user), this will update the role that we created earlier.
6. Try to use the token of the invited user which we saved earlier and hit this api and it will throw an error.
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of invited user that was saved previously' \
--data-raw '{
"email": "email of other user in different merchant account",
"name": "user name",
"role_id": "role_of8p9odNmf2puQVhQemT"
}'
```
```
{
"error": {
"type": "invalid_request",
"message": "Access forbidden, invalid JWT token was used",
"code": "IR_17"
}
}
```
| [
"crates/router/src/consts.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/services/authentication.rs",
"crates/router/src/services/authentication/blacklist.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3740 | Bug: Customer Payment Method List updates for MIT payments
Since we are deprecating Mandates for unscheduled MIT use cases, the customer payment method list will undergo the following changes:
- List only PMs that are in active state
- Add auth support for Ephemeral Key
- Default PM to be communicated in Customer PM list response | diff --git a/config/development.toml b/config/development.toml
index d69719bd419..59d73a4b8b2 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -71,7 +71,6 @@ mock_locker = true
basilisk_host = ""
locker_enabled = true
-
[forex_api]
call_delay = 21600
local_fetch_retry_count = 5
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index d8c864746a8..eeb10e62286 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -73,6 +73,9 @@ pub struct CustomerResponse {
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
+ /// The identifier for the default payment method.
+ #[schema(max_length = 64, example = "pm_djh2837dwduh890123")]
+ pub default_payment_method_id: Option<String>,
}
#[derive(Default, Clone, Debug, Deserialize, Serialize)]
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 32d3dc30bd8..92f69933900 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};
use crate::{
payment_methods::{
- CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest,
+ CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse,
+ DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest,
PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
@@ -95,6 +96,16 @@ impl ApiEventMetric for PaymentMethodResponse {
impl ApiEventMetric for PaymentMethodUpdate {}
+impl ApiEventMetric for DefaultPaymentMethod {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.payment_method_id.clone(),
+ payment_method: None,
+ payment_method_type: None,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
@@ -121,6 +132,16 @@ impl ApiEventMetric for PaymentMethodListRequest {
impl ApiEventMetric for PaymentMethodListResponse {}
+impl ApiEventMetric for CustomerDefaultPaymentMethodResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(),
+ payment_method: Some(self.payment_method),
+ payment_method_type: self.payment_method_type,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 83e1a2c4887..35193b958f2 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -185,6 +185,10 @@ pub struct PaymentMethodResponse {
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Bank>)]
pub bank_transfer: Option<payouts::Bank>,
+
+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
@@ -550,6 +554,10 @@ pub struct PaymentMethodListRequest {
/// Indicates whether the payment method is eligible for card netwotks
#[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))]
pub card_networks: Option<Vec<api_enums::CardNetwork>>,
+
+ /// Indicates the limit of last used payment methods
+ #[schema(example = 1)]
+ pub limit: Option<i64>,
}
impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
@@ -618,6 +626,9 @@ impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
Some(inner) => inner.push(map.next_value()?),
None => output.card_networks = Some(vec![map.next_value()?]),
},
+ "limit" => {
+ set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?;
+ }
_ => {}
}
}
@@ -731,12 +742,30 @@ pub struct PaymentMethodDeleteResponse {
#[schema(example = true)]
pub deleted: bool,
}
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CustomerDefaultPaymentMethodResponse {
+ /// The unique identifier of the Payment method
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")]
+ pub default_payment_method_id: Option<String>,
+ /// The unique identifier of the customer.
+ #[schema(example = "cus_meowerunwiuwiwqw")]
+ pub customer_id: String,
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+ /// This is a sub-category of payment method.
+ #[schema(value_type = Option<PaymentMethodType>,example = "credit")]
+ pub payment_method_type: Option<api_enums::PaymentMethodType>,
+}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethod {
/// Token for payment method in temporary card locker which gets refreshed often
#[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]
pub payment_token: String,
+ /// The unique identifier of the customer.
+ #[schema(example = "pm_iouuy468iyuowqs")]
+ pub payment_method_id: String,
/// The unique identifier of the customer.
#[schema(example = "cus_meowerunwiuwiwqw")]
@@ -798,6 +827,14 @@ pub struct CustomerPaymentMethod {
/// Whether this payment method requires CVV to be collected
#[schema(example = true)]
pub requires_cvv: bool,
+
+ /// A timestamp (ISO 8601 code) that determines when the payment method was last used
+ #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
+ /// Indicates if the payment method has been set to default or not
+ #[schema(example = true)]
+ pub default_payment_method_set: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -810,6 +847,11 @@ pub struct PaymentMethodId {
pub payment_method_id: String,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+pub struct DefaultPaymentMethod {
+ pub customer_id: String,
+ pub payment_method_id: String,
+}
//------------------------------------------------TokenizeService------------------------------------------------
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizePayloadEncrypted {
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index c0cebba7755..cefb0c240ec 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -37,6 +37,7 @@ pub struct Customer {
pub connector_customer: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -51,4 +52,5 @@ pub struct CustomerUpdateInternal {
pub modified_at: Option<PrimitiveDateTime>,
pub connector_customer: Option<serde_json::Value>,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 09be739581e..6191a768efe 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -34,12 +34,13 @@ pub struct PaymentMethod {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
}
-#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
+#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: String,
@@ -64,6 +65,7 @@ pub struct PaymentMethodNew {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
@@ -96,6 +98,7 @@ impl Default for PaymentMethodNew {
last_modified: now,
metadata: Option::default(),
payment_method_data: Option::default(),
+ last_used_at: now,
connector_mandate_details: Option::default(),
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
@@ -117,6 +120,9 @@ pub enum PaymentMethodUpdate {
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
},
+ LastUsedUpdate {
+ last_used_at: PrimitiveDateTime,
+ },
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -124,6 +130,7 @@ pub enum PaymentMethodUpdate {
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
+ last_used_at: Option<PrimitiveDateTime>,
}
impl PaymentMethodUpdateInternal {
@@ -140,12 +147,19 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
PaymentMethodUpdate::MetadataUpdate { metadata } => Self {
metadata,
payment_method_data: None,
+ last_used_at: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
} => Self {
metadata: None,
payment_method_data,
+ last_used_at: None,
+ },
+ PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: Some(last_used_at),
},
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index aa227962760..e3f2e511378 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -90,20 +90,16 @@ impl PaymentMethod {
conn: &PgPooledConn,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
- generics::generic_filter::<
- <Self as HasTable>::Table,
- _,
- <<Self as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ limit,
None,
- None,
- None,
+ Some(dsl::last_used_at.desc()),
)
.await
}
@@ -114,21 +110,17 @@ impl PaymentMethod {
customer_id: &str,
merchant_id: &str,
status: storage_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
- generics::generic_filter::<
- <Self as HasTable>::Table,
- _,
- <<Self as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
+ limit,
None,
- None,
- None,
+ Some(dsl::last_used_at.desc()),
)
.await
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f3c6f23e086..97ef8b974dc 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -227,6 +227,8 @@ diesel::table! {
modified_at -> Timestamp,
#[max_length = 64]
address_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ default_payment_method_id -> Nullable<Varchar>,
}
}
@@ -831,6 +833,7 @@ diesel::table! {
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
+ last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index ef573093be5..e21797d2eef 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -115,6 +115,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_mandates_list,
+ routes::customers::default_payment_method_set_api,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
@@ -188,6 +189,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
+ api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::CardDetail,
api_models::payment_methods::RequestPaymentMethodTypes,
@@ -374,6 +376,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payment_methods::RequiredFieldInfo,
+ api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs
index 19901cbbeb9..6011621fc13 100644
--- a/crates/openapi/src/routes/customers.rs
+++ b/crates/openapi/src/routes/customers.rs
@@ -116,3 +116,23 @@ pub async fn customers_list() {}
security(("api_key" = []))
)]
pub async fn customers_mandates_list() {}
+
+/// Customers - Set Default Payment Method
+///
+/// Set the Payment Method as Default for the Customer.
+#[utoipa::path(
+ get,
+ path = "/{customer_id}/payment_methods/{payment_method_id}/default",
+ params (
+ ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
+ (status = 400, description = "Payment Method has already been set as default for that customer"),
+ (status = 404, description = "Payment Method not found for the customer")
+ ),
+ tag = "Customer Set Default Payment Method",
+ operation_id = "Set the Payment Method as Default",
+ security(("ephemeral_key" = []))
+)]
+pub async fn default_payment_method_set_api() {}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 521e3a22166..02127efe6de 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -108,6 +108,7 @@ pub async fn create_customer(
address_id: address.clone().map(|addr| addr.address_id),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
+ default_payment_method_id: None,
})
}
.await
@@ -208,6 +209,7 @@ pub async fn delete_customer(
.find_payment_method_by_customer_id_merchant_id_list(
&req.customer_id,
&merchant_account.merchant_id,
+ None,
)
.await
{
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 1347bb8ffd0..c5ddb1ed6bb 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -43,7 +43,11 @@ pub async fn rust_locker_migration(
for customer in domain_customers {
let result = db
- .find_payment_method_by_customer_id_merchant_id_list(&customer.customer_id, merchant_id)
+ .find_payment_method_by_customer_id_merchant_id_list(
+ &customer.customer_id,
+ merchant_id,
+ None,
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|pm| {
call_to_locker(
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index bdbd9b02d9e..df1fb1e358d 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -156,6 +156,10 @@ impl PaymentMethodRetrieve for Oss {
helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -167,6 +171,10 @@ impl PaymentMethodRetrieve for Oss {
helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index a92215936a0..8c00938cadc 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -7,8 +7,9 @@ use api_models::{
admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
- BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails,
- PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
+ BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes,
+ CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes,
+ PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
ResponsePaymentMethodsEnabled,
},
@@ -25,6 +26,7 @@ use diesel_models::{
business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
payment_method,
};
+use domain::CustomerUpdate;
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
@@ -128,11 +130,12 @@ pub fn store_default_payment_method(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, //[#219]
installment_payment_enabled: false, //[#219]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
};
+
(payment_method_response, None)
}
-
#[instrument(skip_all)]
pub async fn get_or_insert_payment_method(
db: &dyn db::StorageInterface,
@@ -2584,6 +2587,8 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
customer_id: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = state.store.as_ref();
+ let limit = req.clone().and_then(|pml_req| pml_req.limit);
+
if let Some(customer_id) = customer_id {
Box::pin(list_customer_payment_method(
&state,
@@ -2591,6 +2596,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
key_store,
None,
customer_id,
+ limit,
))
.await
} else {
@@ -2614,6 +2620,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
key_store,
payment_intent,
&customer_id,
+ limit,
))
.await
}
@@ -2634,6 +2641,7 @@ pub async fn list_customer_payment_method(
key_store: domain::MerchantKeyStore,
payment_intent: Option<storage::PaymentIntent>,
customer_id: &str,
+ limit: Option<i64>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
@@ -2645,13 +2653,14 @@ pub async fn list_customer_payment_method(
}
};
- db.find_customer_by_customer_id_merchant_id(
- customer_id,
- &merchant_account.merchant_id,
- &key_store,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let key = key_store.key.get_inner().peek();
@@ -2671,6 +2680,7 @@ pub async fn list_customer_payment_method(
customer_id,
&merchant_account.merchant_id,
common_enums::PaymentMethodStatus::Active,
+ limit,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -2758,6 +2768,7 @@ pub async fn list_customer_payment_method(
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
+ payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id,
payment_method: pm.payment_method,
payment_method_type: pm.payment_method_type,
@@ -2773,6 +2784,9 @@ pub async fn list_customer_payment_method(
bank: bank_details,
surcharge_details: None,
requires_cvv,
+ last_used_at: Some(pm.last_used_at),
+ default_payment_method_set: customer.default_payment_method_id.is_some()
+ && customer.default_payment_method_id == Some(pm.payment_method_id),
};
customer_pms.push(pma.to_owned());
@@ -3059,7 +3073,96 @@ async fn get_bank_account_connector_details(
None => Ok(None),
}
}
+pub async fn set_default_payment_method(
+ state: routes::AppState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ customer_id: &str,
+ payment_method_id: String,
+) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> {
+ let db = &*state.store;
+ //check for the customer
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ // check for the presence of payment_method
+ let payment_method = db
+ .find_payment_method(&payment_method_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ utils::when(
+ payment_method.customer_id != customer_id
+ && payment_method.merchant_id != merchant_account.merchant_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "The payment_method_id is not valid".to_string(),
+ })
+ .into_report()
+ },
+ )?;
+
+ utils::when(
+ Some(payment_method_id.clone()) == customer.default_payment_method_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Payment Method is already set as default".to_string(),
+ })
+ .into_report()
+ },
+ )?;
+
+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id: Some(payment_method_id.clone()),
+ };
+
+ // update the db with the default payment method id
+ let updated_customer_details = db
+ .update_customer_by_customer_id_merchant_id(
+ customer_id.to_owned(),
+ merchant_account.merchant_id,
+ customer_update,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the default payment method id for the customer")?;
+ let resp = CustomerDefaultPaymentMethodResponse {
+ default_payment_method_id: updated_customer_details.default_payment_method_id,
+ customer_id: customer.customer_id,
+ payment_method_type: payment_method.payment_method_type,
+ payment_method: payment_method.payment_method,
+ };
+
+ Ok(services::ApplicationResponse::Json(resp))
+}
+
+pub async fn update_last_used_at(
+ pm_id: &str,
+ state: &routes::AppState,
+) -> errors::RouterResult<()> {
+ let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate {
+ last_used_at: common_utils::date_time::now(),
+ };
+ let payment_method = state
+ .store
+ .find_payment_method(pm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ state
+ .store
+ .update_payment_method(payment_method, update_last_used)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the last_used_at in db")?;
+
+ Ok(())
+}
#[cfg(feature = "payouts")]
pub async fn get_bank_from_hs_locker(
state: &routes::AppState,
@@ -3243,9 +3346,10 @@ pub async fn retrieve_payment_method(
card,
metadata: pm.metadata,
created: Some(pm.created_at),
- recurring_enabled: false, //[#219]
- installment_payment_enabled: false, //[#219]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219],
+ recurring_enabled: false,
+ installment_payment_enabled: false,
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(pm.last_used_at),
},
))
}
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 19ecf733dfb..35491d747ef 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -327,7 +327,8 @@ pub fn mk_add_bank_response_hs(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, // [#256]
installment_payment_enabled: false, // #[#256]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
}
}
@@ -370,7 +371,8 @@ pub fn mk_add_card_response_hs(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, // [#256]
installment_payment_enabled: false, // #[#256]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()), // [#256]
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index b94b8627ef9..782d1814cc6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1070,7 +1070,6 @@ where
customer,
)
.await?;
-
*payment_data = pd;
// Validating the blocklist guard and generate the fingerprint
@@ -1141,7 +1140,6 @@ where
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
.await?;
-
if let Some(payment_method_token) = pm_token.clone() {
router_data.payment_method_token = Some(router_types::PaymentMethodToken::Token(
payment_method_token,
@@ -1846,7 +1844,7 @@ async fn decide_payment_method_tokenize_action(
}
}
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInRouter,
TokenizeInConnector,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0baba7035ce..e0b8a5f6232 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1131,6 +1131,7 @@ pub(crate) async fn get_payment_method_create_request(
customer_id: Some(customer.customer_id.to_owned()),
card_network: None,
};
+
Ok(payment_method_request)
}
},
@@ -1402,6 +1403,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
modified_at: common_utils::date_time::now(),
connector_customer: None,
address_id: None,
+ default_payment_method_id: None,
})
}
.await
@@ -1545,7 +1547,8 @@ pub async fn retrieve_payment_method_with_temporary_token(
pub async fn retrieve_card_with_permanent_token(
state: &AppState,
- token: &str,
+ locker_id: &str,
+ payment_method_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&CardToken>,
) -> RouterResult<api::PaymentMethodData> {
@@ -1556,11 +1559,11 @@ pub async fn retrieve_card_with_permanent_token(
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
-
- let card = cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, token)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card information from the permanent locker")?;
+ let card =
+ 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 information from the permanent locker")?;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
@@ -1593,7 +1596,7 @@ pub async fn retrieve_card_with_permanent_token(
card_issuing_country: None,
bank_code: None,
};
-
+ cards::update_last_used_at(payment_method_id, state).await?;
Ok(api::PaymentMethodData::Card(api_card))
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index d08f0208500..21fd4cf85e8 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -426,6 +426,7 @@ async fn skip_saving_card_in_locker(
metadata: None,
created: Some(common_utils::date_time::now()),
bank_transfer: None,
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((pm_resp, None))
@@ -445,6 +446,7 @@ async fn skip_saving_card_in_locker(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
bank_transfer: None,
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((payment_method_response, None))
}
@@ -491,6 +493,7 @@ pub async fn save_in_locker(
recurring_enabled: false, //[#219]
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((payment_method_response, None))
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7b5ec096248..75a8483e06c 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -432,6 +432,7 @@ pub async fn get_or_create_customer_details(
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
address_id: None,
+ default_payment_method_id: None,
};
Ok(Some(
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 982ed9cae94..2987370f280 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -297,6 +297,7 @@ async fn store_bank_details_in_payment_methods(
.find_payment_method_by_customer_id_merchant_id_list(
&customer_id,
&merchant_account.merchant_id,
+ None,
)
.await
.change_context(ApiErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 1c1ec00ce79..0c4cf01aa0e 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1267,9 +1267,10 @@ impl PaymentMethodInterface for KafkaStore {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id)
+ .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id, limit)
.await
}
@@ -1278,9 +1279,15 @@ impl PaymentMethodInterface for KafkaStore {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status)
+ .find_payment_method_by_customer_id_merchant_id_status(
+ customer_id,
+ merchant_id,
+ status,
+ limit,
+ )
.await
}
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index f15ceecd1c4..ddd2857cc22 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -24,6 +24,7 @@ pub trait PaymentMethodInterface {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
async fn find_payment_method_by_customer_id_merchant_id_status(
@@ -31,6 +32,7 @@ pub trait PaymentMethodInterface {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
async fn insert_payment_method(
@@ -104,12 +106,18 @@ impl PaymentMethodInterface for Store {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id)
- .await
- .map_err(Into::into)
- .into_report()
+ storage::PaymentMethod::find_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ limit,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
}
async fn find_payment_method_by_customer_id_merchant_id_status(
@@ -117,6 +125,7 @@ impl PaymentMethodInterface for Store {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::PaymentMethod::find_by_customer_id_merchant_id_status(
@@ -124,6 +133,7 @@ impl PaymentMethodInterface for Store {
customer_id,
merchant_id,
status,
+ limit,
)
.await
.map_err(Into::into)
@@ -221,6 +231,7 @@ impl PaymentMethodInterface for MockDb {
payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
metadata: payment_method_new.metadata,
payment_method_data: payment_method_new.payment_method_data,
+ last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
@@ -233,6 +244,7 @@ impl PaymentMethodInterface for MockDb {
&self,
customer_id: &str,
merchant_id: &str,
+ _limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods
@@ -256,6 +268,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ _limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 73558c78d7b..1d82bc7539f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -632,6 +632,10 @@ impl Customers {
web::resource("/{customer_id}/payment_methods")
.route(web::get().to(list_customer_payment_method_api)),
)
+ .service(
+ web::resource("/{customer_id}/payment_methods/{payment_method_id}/default")
+ .route(web::post().to(default_payment_method_set_api)),
+ )
.service(
web::resource("/{customer_id}")
.route(web::get().to(customers_retrieve))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9471289a0c8..edbdee7bf6f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -96,7 +96,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsRetrieve
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
- | Flow::ValidatePaymentMethod => Self::PaymentMethods,
+ | Flow::ValidatePaymentMethod
+ | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 89ca36c8c15..5469f981659 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -102,6 +102,12 @@ pub async fn list_customer_payment_method_api(
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
+
+ let ephemeral_auth =
+ match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
Box::pin(api::server_wrap(
flow,
state,
@@ -116,7 +122,7 @@ pub async fn list_customer_payment_method_api(
Some(&customer_id),
)
},
- &auth::ApiKeyAuth,
+ &*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
@@ -157,6 +163,7 @@ pub async fn list_customer_payment_method_api_client(
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
+
Box::pin(api::server_wrap(
flow,
state,
@@ -252,6 +259,42 @@ pub async fn payment_method_delete_api(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
+pub async fn default_payment_method_set_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<payment_methods::DefaultPaymentMethod>,
+) -> HttpResponse {
+ let flow = Flow::DefaultPaymentMethodsSet;
+ let payload = path.into_inner();
+ let customer_id = payload.clone().customer_id;
+
+ let ephemeral_auth =
+ match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, default_payment_method| {
+ cards::set_default_payment_method(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ &customer_id,
+ default_payment_method.payment_method_id,
+ )
+ },
+ &*ephemeral_auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 894b3d830dd..009033d5341 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -204,7 +204,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
// Normal flow will call the connector and follow the flow specific operations (capture, authorize)
// SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk )
-#[derive(Clone, Eq, PartialEq)]
+#[derive(Clone, Eq, PartialEq, Debug)]
pub enum GetToken {
GpayMetadata,
ApplePayMetadata,
@@ -214,7 +214,7 @@ pub enum GetToken {
/// Routing algorithm will output merchant connector identifier instead of connector name
/// In order to support backwards compatibility for older routing algorithms and merchant accounts
/// the support for connector name is retained
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct ConnectorData {
pub connector: BoxedConnector,
pub connector_name: types::Connector,
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 32430c0918a..6f08a7fd7e4 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -32,6 +32,7 @@ impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResp
created_at: cust.created_at,
metadata: cust.metadata,
address,
+ default_payment_method_id: cust.default_payment_method_id,
}
.into()
}
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index ca852f832ee..642e94ad69e 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -1,10 +1,11 @@
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
- CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest,
- GetTokenizePayloadResponse, PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId,
- PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
- PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
- TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
+ GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate,
+ PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest,
+ PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
+ TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
+ TokenizedWalletValue1, TokenizedWalletValue2,
};
use error_stack::report;
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index fe575851dc4..5437d06a2e6 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -22,6 +22,7 @@ pub struct Customer {
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<serde_json::Value>,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
#[async_trait::async_trait]
@@ -45,6 +46,7 @@ impl super::behaviour::Conversion for Customer {
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
+ default_payment_method_id: self.default_payment_method_id,
})
}
@@ -72,6 +74,7 @@ impl super::behaviour::Conversion for Customer {
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
+ default_payment_method_id: item.default_payment_method_id,
})
}
.await
@@ -114,6 +117,9 @@ pub enum CustomerUpdate {
ConnectorCustomer {
connector_customer: Option<serde_json::Value>,
},
+ UpdateDefaultPaymentMethod {
+ default_payment_method_id: Option<String>,
+ },
}
impl From<CustomerUpdate> for CustomerUpdateInternal {
@@ -138,12 +144,20 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
connector_customer,
modified_at: Some(date_time::now()),
address_id,
+ ..Default::default()
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
modified_at: Some(common_utils::date_time::now()),
..Default::default()
},
+ CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id,
+ } => Self {
+ default_payment_method_id,
+ modified_at: Some(common_utils::date_time::now()),
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 62c09c42455..4790e60acb1 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -123,6 +123,8 @@ pub enum Flow {
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
+ /// Default Payment method flow.
+ DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql
new file mode 100644
index 00000000000..fc9fc6350ed
--- /dev/null
+++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS last_used_at;
\ No newline at end of file
diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql
new file mode 100644
index 00000000000..f1c0aab4def
--- /dev/null
+++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP;
\ No newline at end of file
diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql
new file mode 100644
index 00000000000..948123ce7e2
--- /dev/null
+++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE customers DROP COLUMN IF EXISTS default_payment_method;
diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql
new file mode 100644
index 00000000000..abaeb1df718
--- /dev/null
+++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE customers
+ADD COLUMN IF NOT EXISTS default_payment_method_id VARCHAR(64);
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 30e75c028d5..3fcf6bca79f 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4080,6 +4080,50 @@
}
]
}
+ },
+ "/{customer_id}/payment_methods/{payment_method_id}/default": {
+ "get": {
+ "tags": [
+ "Customer Set Default Payment Method"
+ ],
+ "summary": "Customers - Set Default Payment Method",
+ "description": "Customers - Set Default Payment Method\n\nSet the Payment Method as Default for the Customer.",
+ "operationId": "Set the Payment Method as Default",
+ "parameters": [
+ {
+ "name": "method_id",
+ "in": "path",
+ "description": "Set the Payment Method as Default for the Customer",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method has been set as default",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomerDefaultPaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Payment Method has already been set as default for that customer"
+ },
+ "404": {
+ "description": "Payment Method not found for the customer"
+ }
+ },
+ "security": [
+ {
+ "ephemeral_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -7308,6 +7352,37 @@
}
}
},
+ "CustomerDefaultPaymentMethodResponse": {
+ "type": "object",
+ "required": [
+ "customer_id",
+ "payment_method"
+ ],
+ "properties": {
+ "default_payment_method_id": {
+ "type": "string",
+ "description": "The unique identifier of the Payment method",
+ "example": "card_rGK4Vi5iSW70MY7J2mIy",
+ "nullable": true
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "cus_meowerunwiuwiwqw"
+ },
+ "payment_method": {
+ "$ref": "#/components/schemas/PaymentMethod"
+ },
+ "payment_method_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"CustomerDeleteResponse": {
"type": "object",
"required": [
@@ -7384,11 +7459,13 @@
"type": "object",
"required": [
"payment_token",
+ "payment_method_id",
"customer_id",
"payment_method",
"recurring_enabled",
"installment_payment_enabled",
- "requires_cvv"
+ "requires_cvv",
+ "default_payment_method_set"
],
"properties": {
"payment_token": {
@@ -7396,6 +7473,11 @@
"description": "Token for payment method in temporary card locker which gets refreshed often",
"example": "7ebf443f-a050-4067-84e5-e6f6d4800aef"
},
+ "payment_method_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "pm_iouuy468iyuowqs"
+ },
"customer_id": {
"type": "string",
"description": "The unique identifier of the customer.",
@@ -7495,6 +7577,18 @@
"type": "boolean",
"description": "Whether this payment method requires CVV to be collected",
"example": true
+ },
+ "last_used_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used",
+ "example": "2024-02-24T11:04:09.922Z",
+ "nullable": true
+ },
+ "default_payment_method_set": {
+ "type": "boolean",
+ "description": "Indicates if the payment method has been set to default or not",
+ "example": true
}
}
},
@@ -7644,6 +7738,28 @@
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.",
"nullable": true
+ },
+ "default_payment_method_id": {
+ "type": "string",
+ "description": "The identifier for the default payment method.",
+ "example": "pm_djh2837dwduh890123",
+ "nullable": true,
+ "maxLength": 64
+ }
+ }
+ },
+ "DefaultPaymentMethod": {
+ "type": "object",
+ "required": [
+ "customer_id",
+ "payment_method_id"
+ ],
+ "properties": {
+ "customer_id": {
+ "type": "string"
+ },
+ "payment_method_id": {
+ "type": "string"
}
}
},
@@ -11888,6 +12004,12 @@
}
],
"nullable": true
+ },
+ "last_used_at": {
+ "type": "string",
+ "format": "date-time",
+ "example": "2024-02-24T11:04:09.922Z",
+ "nullable": true
}
}
},
| 2024-02-23T04:00:53Z |
## Description
- Add default payment method column in customers table and last used column in payment_methods table.
- Last used would be updated depending on every payment_method usages.
- And the CustomerPaymentMethodList would be sorted on the basis of last_used at.
- A query param was added , to show the list on the basis of limit, i.e., if limit is 1 we will show only the 1st payment_method while doing a CustomerPaymentMethodList
- CustomerPaymentMethodList Authentication from ApiKey to EphemeralKey
- Made a new Api Route, `/payment_methods/{customer_id}/{payment_method_id}/default` for explicitly setting up the default payment method for a particular customer, which would require , customer_id and payment_method_id to be passed in the path
- In CustomerPaymentMethodList we would show the Default Payment Method was either set or not , based on its entry in the Customer Table
- Also in CustomerPaymentMethodList we would show payment_method_id now
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | f4d0e2b441a25048186be4b9d0871e2473a6f357 | To test `set_default_payment_method`
- Create an MA and and MCA
- Create an ApiKey and EphemeralKey for that particular customer
- Make a payment , using one card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below)
- The following curl can be used to set the particular payment_method as default, the
```
curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \
--header 'Accept: application/json' \
--header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202'
```
- do a ListCustomerPaymentMethods, The `default_payment_method` would be true
To test `last_used_at`
- Create an MA and and MCA
- Create an ApiKey and EphemeralKey for that particular customer
- Make a payment , using one card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The last_used_at field would show the current timestamp
- Make a payment , using another card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The last_used_at field would show the current timestamp
- Do The list customer and then select a payment_token of the last card
- Make a payment using the `payment_token`
- The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at
- The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method
```
curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \
--header 'Accept: application/json' \
--header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW'
```

<img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733">


| [
"config/development.toml",
"crates/api_models/src/customers.rs",
"crates/api_models/src/events/payment.rs",
"crates/api_models/src/payment_methods.rs",
"crates/diesel_models/src/customers.rs",
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/die... | |
juspay/hyperswitch | juspay__hyperswitch-3739 | Bug: Support Default Payment Method for customer
Add support for having a default payment method option for a customer. This can be used to increase conversion rates by using the preferred saved payment method for payments, reducing the friction.
Solution:
- Customers table to have a column for 'default_payment_method'
- API to set and retrieve the default PM for a customer
- If default has not been set, use the `last_used` PM as the default
- Customer Payment Method List to indicate the default PM | diff --git a/config/development.toml b/config/development.toml
index d69719bd419..59d73a4b8b2 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -71,7 +71,6 @@ mock_locker = true
basilisk_host = ""
locker_enabled = true
-
[forex_api]
call_delay = 21600
local_fetch_retry_count = 5
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index d8c864746a8..eeb10e62286 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -73,6 +73,9 @@ pub struct CustomerResponse {
/// object.
#[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
+ /// The identifier for the default payment method.
+ #[schema(max_length = 64, example = "pm_djh2837dwduh890123")]
+ pub default_payment_method_id: Option<String>,
}
#[derive(Default, Clone, Debug, Deserialize, Serialize)]
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 32d3dc30bd8..92f69933900 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};
use crate::{
payment_methods::{
- CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest,
+ CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse,
+ DefaultPaymentMethod, PaymentMethodDeleteResponse, PaymentMethodListRequest,
PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
@@ -95,6 +96,16 @@ impl ApiEventMetric for PaymentMethodResponse {
impl ApiEventMetric for PaymentMethodUpdate {}
+impl ApiEventMetric for DefaultPaymentMethod {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.payment_method_id.clone(),
+ payment_method: None,
+ payment_method_type: None,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
@@ -121,6 +132,16 @@ impl ApiEventMetric for PaymentMethodListRequest {
impl ApiEventMetric for PaymentMethodListResponse {}
+impl ApiEventMetric for CustomerDefaultPaymentMethodResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(),
+ payment_method: Some(self.payment_method),
+ payment_method_type: self.payment_method_type,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 83e1a2c4887..35193b958f2 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -185,6 +185,10 @@ pub struct PaymentMethodResponse {
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Bank>)]
pub bank_transfer: Option<payouts::Bank>,
+
+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
@@ -550,6 +554,10 @@ pub struct PaymentMethodListRequest {
/// Indicates whether the payment method is eligible for card netwotks
#[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))]
pub card_networks: Option<Vec<api_enums::CardNetwork>>,
+
+ /// Indicates the limit of last used payment methods
+ #[schema(example = 1)]
+ pub limit: Option<i64>,
}
impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
@@ -618,6 +626,9 @@ impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest {
Some(inner) => inner.push(map.next_value()?),
None => output.card_networks = Some(vec![map.next_value()?]),
},
+ "limit" => {
+ set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?;
+ }
_ => {}
}
}
@@ -731,12 +742,30 @@ pub struct PaymentMethodDeleteResponse {
#[schema(example = true)]
pub deleted: bool,
}
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CustomerDefaultPaymentMethodResponse {
+ /// The unique identifier of the Payment method
+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIy")]
+ pub default_payment_method_id: Option<String>,
+ /// The unique identifier of the customer.
+ #[schema(example = "cus_meowerunwiuwiwqw")]
+ pub customer_id: String,
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+ /// This is a sub-category of payment method.
+ #[schema(value_type = Option<PaymentMethodType>,example = "credit")]
+ pub payment_method_type: Option<api_enums::PaymentMethodType>,
+}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethod {
/// Token for payment method in temporary card locker which gets refreshed often
#[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]
pub payment_token: String,
+ /// The unique identifier of the customer.
+ #[schema(example = "pm_iouuy468iyuowqs")]
+ pub payment_method_id: String,
/// The unique identifier of the customer.
#[schema(example = "cus_meowerunwiuwiwqw")]
@@ -798,6 +827,14 @@ pub struct CustomerPaymentMethod {
/// Whether this payment method requires CVV to be collected
#[schema(example = true)]
pub requires_cvv: bool,
+
+ /// A timestamp (ISO 8601 code) that determines when the payment method was last used
+ #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
+ /// Indicates if the payment method has been set to default or not
+ #[schema(example = true)]
+ pub default_payment_method_set: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -810,6 +847,11 @@ pub struct PaymentMethodId {
pub payment_method_id: String,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+pub struct DefaultPaymentMethod {
+ pub customer_id: String,
+ pub payment_method_id: String,
+}
//------------------------------------------------TokenizeService------------------------------------------------
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizePayloadEncrypted {
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index c0cebba7755..cefb0c240ec 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -37,6 +37,7 @@ pub struct Customer {
pub connector_customer: Option<serde_json::Value>,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -51,4 +52,5 @@ pub struct CustomerUpdateInternal {
pub modified_at: Option<PrimitiveDateTime>,
pub connector_customer: Option<serde_json::Value>,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 09be739581e..6191a768efe 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -34,12 +34,13 @@ pub struct PaymentMethod {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
}
-#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
+#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: String,
@@ -64,6 +65,7 @@ pub struct PaymentMethodNew {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
@@ -96,6 +98,7 @@ impl Default for PaymentMethodNew {
last_modified: now,
metadata: Option::default(),
payment_method_data: Option::default(),
+ last_used_at: now,
connector_mandate_details: Option::default(),
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
@@ -117,6 +120,9 @@ pub enum PaymentMethodUpdate {
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
},
+ LastUsedUpdate {
+ last_used_at: PrimitiveDateTime,
+ },
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -124,6 +130,7 @@ pub enum PaymentMethodUpdate {
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
+ last_used_at: Option<PrimitiveDateTime>,
}
impl PaymentMethodUpdateInternal {
@@ -140,12 +147,19 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
PaymentMethodUpdate::MetadataUpdate { metadata } => Self {
metadata,
payment_method_data: None,
+ last_used_at: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
} => Self {
metadata: None,
payment_method_data,
+ last_used_at: None,
+ },
+ PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: Some(last_used_at),
},
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index aa227962760..e3f2e511378 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -90,20 +90,16 @@ impl PaymentMethod {
conn: &PgPooledConn,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
- generics::generic_filter::<
- <Self as HasTable>::Table,
- _,
- <<Self as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ limit,
None,
- None,
- None,
+ Some(dsl::last_used_at.desc()),
)
.await
}
@@ -114,21 +110,17 @@ impl PaymentMethod {
customer_id: &str,
merchant_id: &str,
status: storage_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
- generics::generic_filter::<
- <Self as HasTable>::Table,
- _,
- <<Self as HasTable>::Table as Table>::PrimaryKey,
- _,
- >(
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
+ limit,
None,
- None,
- None,
+ Some(dsl::last_used_at.desc()),
)
.await
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f3c6f23e086..97ef8b974dc 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -227,6 +227,8 @@ diesel::table! {
modified_at -> Timestamp,
#[max_length = 64]
address_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ default_payment_method_id -> Nullable<Varchar>,
}
}
@@ -831,6 +833,7 @@ diesel::table! {
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
+ last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index ef573093be5..e21797d2eef 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -115,6 +115,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_mandates_list,
+ routes::customers::default_payment_method_set_api,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
@@ -188,6 +189,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
+ api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::CardDetail,
api_models::payment_methods::RequestPaymentMethodTypes,
@@ -374,6 +376,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payment_methods::RequiredFieldInfo,
+ api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs
index 19901cbbeb9..6011621fc13 100644
--- a/crates/openapi/src/routes/customers.rs
+++ b/crates/openapi/src/routes/customers.rs
@@ -116,3 +116,23 @@ pub async fn customers_list() {}
security(("api_key" = []))
)]
pub async fn customers_mandates_list() {}
+
+/// Customers - Set Default Payment Method
+///
+/// Set the Payment Method as Default for the Customer.
+#[utoipa::path(
+ get,
+ path = "/{customer_id}/payment_methods/{payment_method_id}/default",
+ params (
+ ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
+ (status = 400, description = "Payment Method has already been set as default for that customer"),
+ (status = 404, description = "Payment Method not found for the customer")
+ ),
+ tag = "Customer Set Default Payment Method",
+ operation_id = "Set the Payment Method as Default",
+ security(("ephemeral_key" = []))
+)]
+pub async fn default_payment_method_set_api() {}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 521e3a22166..02127efe6de 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -108,6 +108,7 @@ pub async fn create_customer(
address_id: address.clone().map(|addr| addr.address_id),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
+ default_payment_method_id: None,
})
}
.await
@@ -208,6 +209,7 @@ pub async fn delete_customer(
.find_payment_method_by_customer_id_merchant_id_list(
&req.customer_id,
&merchant_account.merchant_id,
+ None,
)
.await
{
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 1347bb8ffd0..c5ddb1ed6bb 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -43,7 +43,11 @@ pub async fn rust_locker_migration(
for customer in domain_customers {
let result = db
- .find_payment_method_by_customer_id_merchant_id_list(&customer.customer_id, merchant_id)
+ .find_payment_method_by_customer_id_merchant_id_list(
+ &customer.customer_id,
+ merchant_id,
+ None,
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|pm| {
call_to_locker(
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index bdbd9b02d9e..df1fb1e358d 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -156,6 +156,10 @@ impl PaymentMethodRetrieve for Oss {
helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -167,6 +171,10 @@ impl PaymentMethodRetrieve for Oss {
helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
+ card_token
+ .payment_method_id
+ .as_ref()
+ .unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index a92215936a0..8c00938cadc 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -7,8 +7,9 @@ use api_models::{
admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
- BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails,
- PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
+ BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes,
+ CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes,
+ PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
ResponsePaymentMethodsEnabled,
},
@@ -25,6 +26,7 @@ use diesel_models::{
business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
payment_method,
};
+use domain::CustomerUpdate;
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
@@ -128,11 +130,12 @@ pub fn store_default_payment_method(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, //[#219]
installment_payment_enabled: false, //[#219]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
};
+
(payment_method_response, None)
}
-
#[instrument(skip_all)]
pub async fn get_or_insert_payment_method(
db: &dyn db::StorageInterface,
@@ -2584,6 +2587,8 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
customer_id: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = state.store.as_ref();
+ let limit = req.clone().and_then(|pml_req| pml_req.limit);
+
if let Some(customer_id) = customer_id {
Box::pin(list_customer_payment_method(
&state,
@@ -2591,6 +2596,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
key_store,
None,
customer_id,
+ limit,
))
.await
} else {
@@ -2614,6 +2620,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
key_store,
payment_intent,
&customer_id,
+ limit,
))
.await
}
@@ -2634,6 +2641,7 @@ pub async fn list_customer_payment_method(
key_store: domain::MerchantKeyStore,
payment_intent: Option<storage::PaymentIntent>,
customer_id: &str,
+ limit: Option<i64>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
@@ -2645,13 +2653,14 @@ pub async fn list_customer_payment_method(
}
};
- db.find_customer_by_customer_id_merchant_id(
- customer_id,
- &merchant_account.merchant_id,
- &key_store,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let key = key_store.key.get_inner().peek();
@@ -2671,6 +2680,7 @@ pub async fn list_customer_payment_method(
customer_id,
&merchant_account.merchant_id,
common_enums::PaymentMethodStatus::Active,
+ limit,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
@@ -2758,6 +2768,7 @@ pub async fn list_customer_payment_method(
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
+ payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id,
payment_method: pm.payment_method,
payment_method_type: pm.payment_method_type,
@@ -2773,6 +2784,9 @@ pub async fn list_customer_payment_method(
bank: bank_details,
surcharge_details: None,
requires_cvv,
+ last_used_at: Some(pm.last_used_at),
+ default_payment_method_set: customer.default_payment_method_id.is_some()
+ && customer.default_payment_method_id == Some(pm.payment_method_id),
};
customer_pms.push(pma.to_owned());
@@ -3059,7 +3073,96 @@ async fn get_bank_account_connector_details(
None => Ok(None),
}
}
+pub async fn set_default_payment_method(
+ state: routes::AppState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ customer_id: &str,
+ payment_method_id: String,
+) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> {
+ let db = &*state.store;
+ //check for the customer
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ // check for the presence of payment_method
+ let payment_method = db
+ .find_payment_method(&payment_method_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ utils::when(
+ payment_method.customer_id != customer_id
+ && payment_method.merchant_id != merchant_account.merchant_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "The payment_method_id is not valid".to_string(),
+ })
+ .into_report()
+ },
+ )?;
+
+ utils::when(
+ Some(payment_method_id.clone()) == customer.default_payment_method_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Payment Method is already set as default".to_string(),
+ })
+ .into_report()
+ },
+ )?;
+
+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id: Some(payment_method_id.clone()),
+ };
+
+ // update the db with the default payment method id
+ let updated_customer_details = db
+ .update_customer_by_customer_id_merchant_id(
+ customer_id.to_owned(),
+ merchant_account.merchant_id,
+ customer_update,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the default payment method id for the customer")?;
+ let resp = CustomerDefaultPaymentMethodResponse {
+ default_payment_method_id: updated_customer_details.default_payment_method_id,
+ customer_id: customer.customer_id,
+ payment_method_type: payment_method.payment_method_type,
+ payment_method: payment_method.payment_method,
+ };
+
+ Ok(services::ApplicationResponse::Json(resp))
+}
+
+pub async fn update_last_used_at(
+ pm_id: &str,
+ state: &routes::AppState,
+) -> errors::RouterResult<()> {
+ let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate {
+ last_used_at: common_utils::date_time::now(),
+ };
+ let payment_method = state
+ .store
+ .find_payment_method(pm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ state
+ .store
+ .update_payment_method(payment_method, update_last_used)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the last_used_at in db")?;
+
+ Ok(())
+}
#[cfg(feature = "payouts")]
pub async fn get_bank_from_hs_locker(
state: &routes::AppState,
@@ -3243,9 +3346,10 @@ pub async fn retrieve_payment_method(
card,
metadata: pm.metadata,
created: Some(pm.created_at),
- recurring_enabled: false, //[#219]
- installment_payment_enabled: false, //[#219]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219],
+ recurring_enabled: false,
+ installment_payment_enabled: false,
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(pm.last_used_at),
},
))
}
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 19ecf733dfb..35491d747ef 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -327,7 +327,8 @@ pub fn mk_add_bank_response_hs(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, // [#256]
installment_payment_enabled: false, // #[#256]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()),
}
}
@@ -370,7 +371,8 @@ pub fn mk_add_card_response_hs(
created: Some(common_utils::date_time::now()),
recurring_enabled: false, // [#256]
installment_payment_enabled: false, // #[#256]
- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256]
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ last_used_at: Some(common_utils::date_time::now()), // [#256]
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index b94b8627ef9..782d1814cc6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1070,7 +1070,6 @@ where
customer,
)
.await?;
-
*payment_data = pd;
// Validating the blocklist guard and generate the fingerprint
@@ -1141,7 +1140,6 @@ where
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
.await?;
-
if let Some(payment_method_token) = pm_token.clone() {
router_data.payment_method_token = Some(router_types::PaymentMethodToken::Token(
payment_method_token,
@@ -1846,7 +1844,7 @@ async fn decide_payment_method_tokenize_action(
}
}
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInRouter,
TokenizeInConnector,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0baba7035ce..e0b8a5f6232 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1131,6 +1131,7 @@ pub(crate) async fn get_payment_method_create_request(
customer_id: Some(customer.customer_id.to_owned()),
card_network: None,
};
+
Ok(payment_method_request)
}
},
@@ -1402,6 +1403,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
modified_at: common_utils::date_time::now(),
connector_customer: None,
address_id: None,
+ default_payment_method_id: None,
})
}
.await
@@ -1545,7 +1547,8 @@ pub async fn retrieve_payment_method_with_temporary_token(
pub async fn retrieve_card_with_permanent_token(
state: &AppState,
- token: &str,
+ locker_id: &str,
+ payment_method_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&CardToken>,
) -> RouterResult<api::PaymentMethodData> {
@@ -1556,11 +1559,11 @@ pub async fn retrieve_card_with_permanent_token(
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
-
- let card = cards::get_card_from_locker(state, customer_id, &payment_intent.merchant_id, token)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card information from the permanent locker")?;
+ let card =
+ 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 information from the permanent locker")?;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
@@ -1593,7 +1596,7 @@ pub async fn retrieve_card_with_permanent_token(
card_issuing_country: None,
bank_code: None,
};
-
+ cards::update_last_used_at(payment_method_id, state).await?;
Ok(api::PaymentMethodData::Card(api_card))
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index d08f0208500..21fd4cf85e8 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -426,6 +426,7 @@ async fn skip_saving_card_in_locker(
metadata: None,
created: Some(common_utils::date_time::now()),
bank_transfer: None,
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((pm_resp, None))
@@ -445,6 +446,7 @@ async fn skip_saving_card_in_locker(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
bank_transfer: None,
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((payment_method_response, None))
}
@@ -491,6 +493,7 @@ pub async fn save_in_locker(
recurring_enabled: false, //[#219]
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
+ last_used_at: Some(common_utils::date_time::now()),
};
Ok((payment_method_response, None))
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7b5ec096248..75a8483e06c 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -432,6 +432,7 @@ pub async fn get_or_create_customer_details(
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
address_id: None,
+ default_payment_method_id: None,
};
Ok(Some(
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 982ed9cae94..2987370f280 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -297,6 +297,7 @@ async fn store_bank_details_in_payment_methods(
.find_payment_method_by_customer_id_merchant_id_list(
&customer_id,
&merchant_account.merchant_id,
+ None,
)
.await
.change_context(ApiErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 1c1ec00ce79..0c4cf01aa0e 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1267,9 +1267,10 @@ impl PaymentMethodInterface for KafkaStore {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id)
+ .find_payment_method_by_customer_id_merchant_id_list(customer_id, merchant_id, limit)
.await
}
@@ -1278,9 +1279,15 @@ impl PaymentMethodInterface for KafkaStore {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
self.diesel_store
- .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status)
+ .find_payment_method_by_customer_id_merchant_id_status(
+ customer_id,
+ merchant_id,
+ status,
+ limit,
+ )
.await
}
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index f15ceecd1c4..ddd2857cc22 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -24,6 +24,7 @@ pub trait PaymentMethodInterface {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
async fn find_payment_method_by_customer_id_merchant_id_status(
@@ -31,6 +32,7 @@ pub trait PaymentMethodInterface {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
async fn insert_payment_method(
@@ -104,12 +106,18 @@ impl PaymentMethodInterface for Store {
&self,
customer_id: &str,
merchant_id: &str,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id)
- .await
- .map_err(Into::into)
- .into_report()
+ storage::PaymentMethod::find_by_customer_id_merchant_id(
+ &conn,
+ customer_id,
+ merchant_id,
+ limit,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
}
async fn find_payment_method_by_customer_id_merchant_id_status(
@@ -117,6 +125,7 @@ impl PaymentMethodInterface for Store {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::PaymentMethod::find_by_customer_id_merchant_id_status(
@@ -124,6 +133,7 @@ impl PaymentMethodInterface for Store {
customer_id,
merchant_id,
status,
+ limit,
)
.await
.map_err(Into::into)
@@ -221,6 +231,7 @@ impl PaymentMethodInterface for MockDb {
payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
metadata: payment_method_new.metadata,
payment_method_data: payment_method_new.payment_method_data,
+ last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
@@ -233,6 +244,7 @@ impl PaymentMethodInterface for MockDb {
&self,
customer_id: &str,
merchant_id: &str,
+ _limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods
@@ -256,6 +268,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: &str,
merchant_id: &str,
status: common_enums::PaymentMethodStatus,
+ _limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 73558c78d7b..1d82bc7539f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -632,6 +632,10 @@ impl Customers {
web::resource("/{customer_id}/payment_methods")
.route(web::get().to(list_customer_payment_method_api)),
)
+ .service(
+ web::resource("/{customer_id}/payment_methods/{payment_method_id}/default")
+ .route(web::post().to(default_payment_method_set_api)),
+ )
.service(
web::resource("/{customer_id}")
.route(web::get().to(customers_retrieve))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9471289a0c8..edbdee7bf6f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -96,7 +96,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsRetrieve
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
- | Flow::ValidatePaymentMethod => Self::PaymentMethods,
+ | Flow::ValidatePaymentMethod
+ | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 89ca36c8c15..5469f981659 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -102,6 +102,12 @@ pub async fn list_customer_payment_method_api(
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
+
+ let ephemeral_auth =
+ match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
Box::pin(api::server_wrap(
flow,
state,
@@ -116,7 +122,7 @@ pub async fn list_customer_payment_method_api(
Some(&customer_id),
)
},
- &auth::ApiKeyAuth,
+ &*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
@@ -157,6 +163,7 @@ pub async fn list_customer_payment_method_api_client(
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
+
Box::pin(api::server_wrap(
flow,
state,
@@ -252,6 +259,42 @@ pub async fn payment_method_delete_api(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
+pub async fn default_payment_method_set_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<payment_methods::DefaultPaymentMethod>,
+) -> HttpResponse {
+ let flow = Flow::DefaultPaymentMethodsSet;
+ let payload = path.into_inner();
+ let customer_id = payload.clone().customer_id;
+
+ let ephemeral_auth =
+ match auth::is_ephemeral_auth(req.headers(), &*state.store, &customer_id).await {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, default_payment_method| {
+ cards::set_default_payment_method(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ &customer_id,
+ default_payment_method.payment_method_id,
+ )
+ },
+ &*ephemeral_auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 894b3d830dd..009033d5341 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -204,7 +204,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
// Normal flow will call the connector and follow the flow specific operations (capture, authorize)
// SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk )
-#[derive(Clone, Eq, PartialEq)]
+#[derive(Clone, Eq, PartialEq, Debug)]
pub enum GetToken {
GpayMetadata,
ApplePayMetadata,
@@ -214,7 +214,7 @@ pub enum GetToken {
/// Routing algorithm will output merchant connector identifier instead of connector name
/// In order to support backwards compatibility for older routing algorithms and merchant accounts
/// the support for connector name is retained
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct ConnectorData {
pub connector: BoxedConnector,
pub connector_name: types::Connector,
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 32430c0918a..6f08a7fd7e4 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -32,6 +32,7 @@ impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResp
created_at: cust.created_at,
metadata: cust.metadata,
address,
+ default_payment_method_id: cust.default_payment_method_id,
}
.into()
}
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index ca852f832ee..642e94ad69e 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -1,10 +1,11 @@
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
- CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest,
- GetTokenizePayloadResponse, PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId,
- PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
- PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
- TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
+ GetTokenizePayloadRequest, GetTokenizePayloadResponse, PaymentMethodCreate,
+ PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, PaymentMethodListRequest,
+ PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
+ TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
+ TokenizedWalletValue1, TokenizedWalletValue2,
};
use error_stack::report;
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index fe575851dc4..5437d06a2e6 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -22,6 +22,7 @@ pub struct Customer {
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<serde_json::Value>,
pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
}
#[async_trait::async_trait]
@@ -45,6 +46,7 @@ impl super::behaviour::Conversion for Customer {
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
+ default_payment_method_id: self.default_payment_method_id,
})
}
@@ -72,6 +74,7 @@ impl super::behaviour::Conversion for Customer {
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
+ default_payment_method_id: item.default_payment_method_id,
})
}
.await
@@ -114,6 +117,9 @@ pub enum CustomerUpdate {
ConnectorCustomer {
connector_customer: Option<serde_json::Value>,
},
+ UpdateDefaultPaymentMethod {
+ default_payment_method_id: Option<String>,
+ },
}
impl From<CustomerUpdate> for CustomerUpdateInternal {
@@ -138,12 +144,20 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
connector_customer,
modified_at: Some(date_time::now()),
address_id,
+ ..Default::default()
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
modified_at: Some(common_utils::date_time::now()),
..Default::default()
},
+ CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id,
+ } => Self {
+ default_payment_method_id,
+ modified_at: Some(common_utils::date_time::now()),
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 62c09c42455..4790e60acb1 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -123,6 +123,8 @@ pub enum Flow {
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
+ /// Default Payment method flow.
+ DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql
new file mode 100644
index 00000000000..fc9fc6350ed
--- /dev/null
+++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS last_used_at;
\ No newline at end of file
diff --git a/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql
new file mode 100644
index 00000000000..f1c0aab4def
--- /dev/null
+++ b/migrations/2024-02-21-120100_add_last_used_at_in_payment_methods/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP;
\ No newline at end of file
diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql
new file mode 100644
index 00000000000..948123ce7e2
--- /dev/null
+++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE customers DROP COLUMN IF EXISTS default_payment_method;
diff --git a/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql
new file mode 100644
index 00000000000..abaeb1df718
--- /dev/null
+++ b/migrations/2024-02-21-143530_add_default_payment_method_in_customers/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE customers
+ADD COLUMN IF NOT EXISTS default_payment_method_id VARCHAR(64);
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 30e75c028d5..3fcf6bca79f 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4080,6 +4080,50 @@
}
]
}
+ },
+ "/{customer_id}/payment_methods/{payment_method_id}/default": {
+ "get": {
+ "tags": [
+ "Customer Set Default Payment Method"
+ ],
+ "summary": "Customers - Set Default Payment Method",
+ "description": "Customers - Set Default Payment Method\n\nSet the Payment Method as Default for the Customer.",
+ "operationId": "Set the Payment Method as Default",
+ "parameters": [
+ {
+ "name": "method_id",
+ "in": "path",
+ "description": "Set the Payment Method as Default for the Customer",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method has been set as default",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomerDefaultPaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Payment Method has already been set as default for that customer"
+ },
+ "404": {
+ "description": "Payment Method not found for the customer"
+ }
+ },
+ "security": [
+ {
+ "ephemeral_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -7308,6 +7352,37 @@
}
}
},
+ "CustomerDefaultPaymentMethodResponse": {
+ "type": "object",
+ "required": [
+ "customer_id",
+ "payment_method"
+ ],
+ "properties": {
+ "default_payment_method_id": {
+ "type": "string",
+ "description": "The unique identifier of the Payment method",
+ "example": "card_rGK4Vi5iSW70MY7J2mIy",
+ "nullable": true
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "cus_meowerunwiuwiwqw"
+ },
+ "payment_method": {
+ "$ref": "#/components/schemas/PaymentMethod"
+ },
+ "payment_method_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"CustomerDeleteResponse": {
"type": "object",
"required": [
@@ -7384,11 +7459,13 @@
"type": "object",
"required": [
"payment_token",
+ "payment_method_id",
"customer_id",
"payment_method",
"recurring_enabled",
"installment_payment_enabled",
- "requires_cvv"
+ "requires_cvv",
+ "default_payment_method_set"
],
"properties": {
"payment_token": {
@@ -7396,6 +7473,11 @@
"description": "Token for payment method in temporary card locker which gets refreshed often",
"example": "7ebf443f-a050-4067-84e5-e6f6d4800aef"
},
+ "payment_method_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "pm_iouuy468iyuowqs"
+ },
"customer_id": {
"type": "string",
"description": "The unique identifier of the customer.",
@@ -7495,6 +7577,18 @@
"type": "boolean",
"description": "Whether this payment method requires CVV to be collected",
"example": true
+ },
+ "last_used_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used",
+ "example": "2024-02-24T11:04:09.922Z",
+ "nullable": true
+ },
+ "default_payment_method_set": {
+ "type": "boolean",
+ "description": "Indicates if the payment method has been set to default or not",
+ "example": true
}
}
},
@@ -7644,6 +7738,28 @@
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject.",
"nullable": true
+ },
+ "default_payment_method_id": {
+ "type": "string",
+ "description": "The identifier for the default payment method.",
+ "example": "pm_djh2837dwduh890123",
+ "nullable": true,
+ "maxLength": 64
+ }
+ }
+ },
+ "DefaultPaymentMethod": {
+ "type": "object",
+ "required": [
+ "customer_id",
+ "payment_method_id"
+ ],
+ "properties": {
+ "customer_id": {
+ "type": "string"
+ },
+ "payment_method_id": {
+ "type": "string"
}
}
},
@@ -11888,6 +12004,12 @@
}
],
"nullable": true
+ },
+ "last_used_at": {
+ "type": "string",
+ "format": "date-time",
+ "example": "2024-02-24T11:04:09.922Z",
+ "nullable": true
}
}
},
| 2024-02-23T04:00:53Z |
## Description
- Add default payment method column in customers table and last used column in payment_methods table.
- Last used would be updated depending on every payment_method usages.
- And the CustomerPaymentMethodList would be sorted on the basis of last_used at.
- A query param was added , to show the list on the basis of limit, i.e., if limit is 1 we will show only the 1st payment_method while doing a CustomerPaymentMethodList
- CustomerPaymentMethodList Authentication from ApiKey to EphemeralKey
- Made a new Api Route, `/payment_methods/{customer_id}/{payment_method_id}/default` for explicitly setting up the default payment method for a particular customer, which would require , customer_id and payment_method_id to be passed in the path
- In CustomerPaymentMethodList we would show the Default Payment Method was either set or not , based on its entry in the Customer Table
- Also in CustomerPaymentMethodList we would show payment_method_id now
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | f4d0e2b441a25048186be4b9d0871e2473a6f357 | To test `set_default_payment_method`
- Create an MA and and MCA
- Create an ApiKey and EphemeralKey for that particular customer
- Make a payment , using one card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The `default_payment_method` would be false , there also will be `payment_method_id` field (refer the screenshots below)
- The following curl can be used to set the particular payment_method as default, the
```
curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \
--header 'Accept: application/json' \
--header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202'
```
- do a ListCustomerPaymentMethods, The `default_payment_method` would be true
To test `last_used_at`
- Create an MA and and MCA
- Create an ApiKey and EphemeralKey for that particular customer
- Make a payment , using one card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The last_used_at field would show the current timestamp
- Make a payment , using another card and then do a ListCustomerPaymentMethods
- > Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data-raw ' {"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "7cc",
"email": "something@gmail.com",
"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"
}
},
"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"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"business_country": "US",
"business_label": "default",
"setup_future_usage": "on_session"
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_nIQnyrfS15jQja2OocCX/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_RHgvB0yPOTVA4xK4zTjXzxrnSVmnXlJz80hnEHIocTKplSc6sYqwRu2yHD8iJyuA' \
--data '{
"confirm": true,
"payment_type": "normal",
"setup_future_usage":"on_session",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
- The last_used_at field would show the current timestamp
- Do The list customer and then select a payment_token of the last card
- Make a payment using the `payment_token`
- The last_used_at field would show the current timestamp, and would be sorted in the order that PaymentMethod was used at
- The following curl can be used to list the customer payment methods with a limit , the limit if set as 1 would show the last used payment method
```
curl --location 'http://localhost:8080/customers/{customer_id}/payment_methods?limit=1' \
--header 'Accept: application/json' \
--header 'api-key: dev_OS3aZUsCeqV3eTW2Nlaba7yThKEUAZGXlEysuL15ZIoPP0McJ4YB9zRr9mWc9NFW'
```

<img width="1728" alt="Screenshot 2024-02-26 at 4 42 43 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/64231527-bce6-4483-9997-b0cfb0669733">


| [
"config/development.toml",
"crates/api_models/src/customers.rs",
"crates/api_models/src/events/payment.rs",
"crates/api_models/src/payment_methods.rs",
"crates/diesel_models/src/customers.rs",
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/die... | |
juspay/hyperswitch | juspay__hyperswitch-3785 | Bug: [FEATURE] : [Cybersource] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 4bb28439b7f..14f8b2a7f99 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -2,7 +2,7 @@ use api_models::payments;
use base64::Engine;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -259,9 +259,9 @@ pub struct ProcessingInformation {
pub struct CybersourceConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -385,7 +385,7 @@ pub enum PaymentInformation {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CybersoucrePaymentInstrument {
- id: String,
+ id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -1071,7 +1071,7 @@ impl
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = CybersoucrePaymentInstrument {
- id: connector_mandate_id,
+ id: connector_mandate_id.into(),
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
@@ -1491,7 +1491,7 @@ pub struct ClientRiskInformation {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
- name: String,
+ name: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -1592,7 +1592,7 @@ fn get_payment_response(
.token_information
.clone()
.map(|token_info| types::MandateReference {
- connector_mandate_id: Some(token_info.payment_instrument.id),
+ connector_mandate_id: Some(token_info.payment_instrument.id.expose()),
payment_method_id: None,
});
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -1941,10 +1941,10 @@ pub enum CybersourceAuthEnrollmentStatus {
pub struct CybersourceConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
@@ -1956,7 +1956,7 @@ pub struct CybersourceThreeDSMetadata {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
- access_token: Option<String>,
+ access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
@@ -2044,9 +2044,9 @@ impl<F>
.consumer_authentication_information
.step_up_url,
) {
- (Some(access_token), Some(step_up_url)) => {
+ (Some(token), Some(step_up_url)) => {
Some(services::RedirectForm::CybersourceConsumerAuth {
- access_token,
+ access_token: token.expose(),
step_up_url,
})
}
@@ -2241,7 +2241,7 @@ impl<F, T>
CybersourceSetupMandatesResponse::ClientReferenceInformation(info_response) => {
let mandate_reference = info_response.token_information.clone().map(|token_info| {
types::MandateReference {
- connector_mandate_id: Some(token_info.payment_instrument.id),
+ connector_mandate_id: Some(token_info.payment_instrument.id.expose()),
payment_method_id: None,
}
});
@@ -2655,7 +2655,7 @@ impl
client_risk_information.rules.map(|rules| {
rules
.iter()
- .map(|risk_info| format!(" , {}", risk_info.name))
+ .map(|risk_info| format!(" , {}", risk_info.name.clone().expose()))
.collect::<Vec<String>>()
.join("")
})
| 2024-02-22T12:14:42Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Cybersource.
## Test Case
1.a. Create a 3DS payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sJlLjo5AQkfrDpPH0IEmB0gKzEgOLRr4CnI0PeHyePVJmCEoww6B9bkUjcVFyIFF' \
--data-raw '{
"amount": 0,
"currency": "PLN",
"confirm": true,
"business_country": "US",
"business_label": "default",
"capture_method": "automatic",
"customer_id": "abc",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"email": "arjun.karthik@juspay.in",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4622943127013705",
"card_exp_month": "12",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "CA",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "New York",
"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"
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 3200,
"account_name": "transaction_processing"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
, "mandate_type": {
"multi_use": {
"amount": 700,
"currency": "USD"
}
}
}
}'
```
1.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
masked_response should be
```
{\\\"id\\\":\\\"7089429038836063404953\\\",\\\"status\\\":\\\"AUTHORIZED\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_BxnKPq7bjemAWr97xyk3_1\\\"},\\\"processorInformation\\\":{\\\"avs\\\":{\\\"code\\\":\\\"Y\\\",\\\"codeRaw\\\":\\\"Y\\\"}},\\\"riskInformation\\\":{\\\"rules\\\":null},\\\"tokenInformation\\\":{\\\"paymentInstrument\\\":{\\\"id\\\":\\\"*** alloc::string::String ***\\\"}}
```
2.a. Check if sensitive data is masked - MIT
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api-key}}' \
--data '{
"amount": 700,
"currency": "USD",
"off_session": true,
"confirm": true,
"capture_method": "automatic",
"description": "Initiated by merchant",
"mandate_id": "{{mandate_id}}",
"customer_id": "abc",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
}
}'
```
2.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response should be
```
"masked_response\":\"{\\\"id\\\":\\\"7089431984486510104951\\\",\\\"status\\\":\\\"AUTHORIZED\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_TL8q8JuBwqoQ94bQBYY5_1\\\"},\\\"processorInformation\\\":{\\\"avs\\\":{\\\"code\\\":\\\"Y\\\",\\\"codeRaw\\\":\\\"Y\\\"}}
```
Impact Area
> Cybersource 3ds mandate payment flow
> Cybersource MIT flow | 75c633fc7c37341177597041ccbcdfc3cf9e236f | [
"crates/router/src/connector/cybersource/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3972 | Bug: [FIX] add doc for merchant KV flip
| diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index dc38181a683..cb41c8eb05c 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -90,6 +90,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
+ routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::payment_connector_create,
@@ -413,6 +414,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
+ api_models::admin::ToggleKVRequest,
+ api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs
index 967e28225c2..6301844bf3c 100644
--- a/crates/openapi/src/routes/merchant_account.rs
+++ b/crates/openapi/src/routes/merchant_account.rs
@@ -123,3 +123,35 @@ pub async fn update_merchant_account() {}
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
+
+/// Merchant Account - KV Status
+///
+/// Toggle KV mode for the Merchant Account
+#[utoipa::path(
+ post,
+ path = "/accounts/{account_id}/kv",
+ request_body (
+ content = ToggleKVRequest,
+ examples (
+ ("Enable KV for Merchant" = (
+ value = json!({
+ "kv_enabled": "true"
+ })
+ )),
+ ("Disable KV for Merchant" = (
+ value = json!({
+ "kv_enabled": "false"
+ })
+ )))
+ ),
+ params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
+ responses(
+ (status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
+ (status = 400, description = "Invalid data"),
+ (status = 404, description = "Merchant account not found")
+ ),
+ tag = "Merchant Account",
+ operation_id = "Enable/Disable KV for a Merchant Account",
+ security(("admin_api_key" = []))
+)]
+pub async fn merchant_account_kv_status() {}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 9e64f3e9d03..dfc95f9235c 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -913,6 +913,72 @@
]
}
},
+ "/accounts/{account_id}/kv": {
+ "post": {
+ "tags": [
+ "Merchant Account"
+ ],
+ "summary": "Merchant Account - KV Status",
+ "description": "Merchant Account - KV Status\n\nToggle KV mode for the Merchant Account",
+ "operationId": "Enable/Disable KV for a Merchant Account",
+ "parameters": [
+ {
+ "name": "account_id",
+ "in": "path",
+ "description": "The unique identifier for the merchant account",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleKVRequest"
+ },
+ "examples": {
+ "Disable KV for Merchant": {
+ "value": {
+ "kv_enabled": "false"
+ }
+ },
+ "Enable KV for Merchant": {
+ "value": {
+ "kv_enabled": "true"
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "KV mode is enabled/disabled for Merchant Account",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleKVResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ },
+ "404": {
+ "description": "Merchant account not found"
+ }
+ },
+ "security": [
+ {
+ "admin_api_key": []
+ }
+ ]
+ }
+ },
"/api_keys/{merchant_id)": {
"post": {
"tags": [
@@ -16228,6 +16294,39 @@
}
}
},
+ "ToggleKVRequest": {
+ "type": "object",
+ "required": [
+ "kv_enabled"
+ ],
+ "properties": {
+ "kv_enabled": {
+ "type": "boolean",
+ "description": "Status of KV for the specific merchant",
+ "example": true
+ }
+ }
+ },
+ "ToggleKVResponse": {
+ "type": "object",
+ "required": [
+ "merchant_id",
+ "kv_enabled"
+ ],
+ "properties": {
+ "merchant_id": {
+ "type": "string",
+ "description": "The identifier for the Merchant Account",
+ "example": "y3oqhf46pyzuxjbcn2giaqnb44",
+ "maxLength": 255
+ },
+ "kv_enabled": {
+ "type": "boolean",
+ "description": "Status of KV for the specific merchant",
+ "example": true
+ }
+ }
+ },
"TouchNGoRedirection": {
"type": "object"
},
| 2024-02-22T11:57:57Z |
## Description
<!-- Describe your changes in detail -->
Added API reference for enabling/disabling KV for a merchant
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Added doc for KV toggle APi
# | bbb3d3d1e26f303964a495606dece7958f6c40fc |
NA
| [
"crates/openapi/src/openapi.rs",
"crates/openapi/src/routes/merchant_account.rs",
"openapi/openapi_spec.json"
] | |
juspay/hyperswitch | juspay__hyperswitch-3772 | Bug: [FEATURE] : [Checkout] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index f96bd50ffc8..591e1aa31c7 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -188,7 +188,7 @@ pub struct CardSource {
pub struct WalletSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
- pub token: String,
+ pub token: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -301,7 +301,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token,
+ types::PaymentMethodToken::Token(token) => token.into(),
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
}
@@ -314,7 +314,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
types::PaymentMethodToken::Token(apple_pay_payment_token) => {
Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
- token: apple_pay_payment_token,
+ token: apple_pay_payment_token.into(),
}))
}
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
| 2024-02-22T10:22:34Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Checkout.
## Test cases
1. Create a payment with Apple pay
2. Create a payment with Google pay
Generate Google pay token from: https://jsfiddle.net/1agu74ve/
`'gateway': 'checkoutltd'`,
`'gatewayMerchantId': 'public_key'`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 7000,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_data": {
"wallet": {
"google_pay": {
"description": "Visa •••• 1111",
"tokenization_data": {
"type": "PAYMENT_GATEWAY",
"token": "{token_generated_from_above_step}"
},
"type": "CARD",
"info": {
"card_network": "VISA",
"card_details": "1111"
}
}
}
}
}'
```
4. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response for Googlepay
```
"masked_response\":\"{\\\"token\\\":\\\"*** alloc::string::String ***\\\"}
```
## Impact Area
> Create payment: Applepay and Googlepay | d000847b938952de6ff9c2e01bdd06b4ede60e69 | [
"crates/router/src/connector/checkout/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3754 | Bug: DB Updates for Payment Methods Table
| diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index c3976321f0a..29c416e9a85 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1177,6 +1177,32 @@ pub enum PaymentMethodIssuerCode {
JpBacs,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Hash,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentMethodStatus {
+ /// Indicates that the payment method is active and can be used for payments.
+ Active,
+ /// Indicates that the payment method is not active and hence cannot be used for payments.
+ Inactive,
+ /// Indicates that the payment method is awaiting some data or action before it can be marked
+ /// as 'active'.
+ Processing,
+}
+
/// To indicate the type of payment experience that the customer would go through
#[derive(
Eq,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index f9767e2939b..09be739581e 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -34,6 +34,9 @@ pub struct PaymentMethod {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub connector_mandate_details: Option<serde_json::Value>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
@@ -61,6 +64,9 @@ pub struct PaymentMethodNew {
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
+ pub connector_mandate_details: Option<serde_json::Value>,
+ pub customer_acceptance: Option<pii::SecretSerdeValue>,
+ pub status: storage_enums::PaymentMethodStatus,
}
impl Default for PaymentMethodNew {
@@ -90,6 +96,9 @@ impl Default for PaymentMethodNew {
last_modified: now,
metadata: Option::default(),
payment_method_data: Option::default(),
+ connector_mandate_details: Option::default(),
+ customer_acceptance: Option::default(),
+ status: storage_enums::PaymentMethodStatus::Active,
}
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 298db2a234b..aa227962760 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -3,7 +3,7 @@ use router_env::{instrument, tracing};
use super::generics;
use crate::{
- errors,
+ enums as storage_enums, errors,
payment_method::{self, PaymentMethod, PaymentMethodNew},
schema::payment_methods::dsl,
PgPooledConn, StorageResult,
@@ -108,6 +108,31 @@ impl PaymentMethod {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_customer_id_merchant_id_status(
+ conn: &PgPooledConn,
+ customer_id: &str,
+ merchant_id: &str,
+ status: storage_enums::PaymentMethodStatus,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<
+ <Self as HasTable>::Table,
+ _,
+ <<Self as HasTable>::Table as Table>::PrimaryKey,
+ _,
+ >(
+ conn,
+ dsl::customer_id
+ .eq(customer_id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::status.eq(status)),
+ None,
+ None,
+ None,
+ )
+ .await
+ }
+
pub async fn update_with_payment_method_id(
self,
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 4ac75f5e7de..f3c6f23e086 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -831,6 +831,10 @@ diesel::table! {
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
+ connector_mandate_details -> Nullable<Jsonb>,
+ customer_acceptance -> Nullable<Jsonb>,
+ #[max_length = 64]
+ status -> Varchar,
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 0a1cc023ece..a92215936a0 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2667,9 +2667,10 @@ pub async fn list_customer_payment_method(
let requires_cvv = is_requires_cvv.config != "false";
let resp = db
- .find_payment_method_by_customer_id_merchant_id_list(
+ .find_payment_method_by_customer_id_merchant_id_status(
customer_id,
&merchant_account.merchant_id,
+ common_enums::PaymentMethodStatus::Active,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index acc703d5c1b..1c1ec00ce79 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1273,6 +1273,17 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn find_payment_method_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_customer_id_merchant_id_status(customer_id, merchant_id, status)
+ .await
+ }
+
async fn find_payment_method_by_locker_id(
&self,
locker_id: &str,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 4f4087f552e..f15ceecd1c4 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -26,6 +26,13 @@ pub trait PaymentMethodInterface {
merchant_id: &str,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
+ async fn find_payment_method_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -105,6 +112,24 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ async fn find_payment_method_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::find_by_customer_id_merchant_id_status(
+ &conn,
+ customer_id,
+ merchant_id,
+ status,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
merchant_id: &str,
@@ -196,6 +221,9 @@ impl PaymentMethodInterface for MockDb {
payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
metadata: payment_method_new.metadata,
payment_method_data: payment_method_new.payment_method_data,
+ connector_mandate_details: payment_method_new.connector_mandate_details,
+ customer_acceptance: payment_method_new.customer_acceptance,
+ status: payment_method_new.status,
};
payment_methods.push(payment_method.clone());
Ok(payment_method)
@@ -223,6 +251,33 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn find_payment_method_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_methods_found: Vec<storage::PaymentMethod> = payment_methods
+ .iter()
+ .filter(|pm| {
+ pm.customer_id == customer_id
+ && pm.merchant_id == merchant_id
+ && pm.status == status
+ })
+ .cloned()
+ .collect();
+
+ if payment_methods_found.is_empty() {
+ Err(errors::StorageError::ValueNotFound(
+ "cannot find payment methods".to_string(),
+ ))
+ .into_report()
+ } else {
+ Ok(payment_methods_found)
+ }
+ }
+
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
merchant_id: &str,
diff --git a/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql
new file mode 100644
index 00000000000..65367b5cd54
--- /dev/null
+++ b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/down.sql
@@ -0,0 +1,10 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods
+DROP COLUMN status;
+
+ALTER TABLE payment_methods
+DROP COLUMN customer_acceptance;
+
+ALTER TABLE payment_methods
+DROP COLUMN connector_mandate_details;
diff --git a/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql
new file mode 100644
index 00000000000..c43c347da38
--- /dev/null
+++ b/migrations/2024-02-22-060352_add_mit_columns_to_payment_methods/up.sql
@@ -0,0 +1,13 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods
+ADD COLUMN connector_mandate_details JSONB
+DEFAULT NULL;
+
+ALTER TABLE payment_methods
+ADD COLUMN customer_acceptance JSONB
+DEFAULT NULL;
+
+ALTER TABLE payment_methods
+ADD COLUMN status VARCHAR(64)
+NOT NULL DEFAULT 'active';
| 2024-02-22T07:25:32Z |
## Description
<!-- Describe your changes in detail -->
This PR adds 3 columns to the `payment_methods` table, with the purpose of enabling MIT Transaction Orchestration in the near future.
- `connector_mandate_details`: Intended to store Connector MIT details such as the mandate ID
- `customer_acceptance`: Intended to store customer consent and acceptance details
- `status`: The status of the payment method (Can be `processing` initially for connector MITs that rely on asynchronous flows and/or time-based factors for setup)
#### Flows Affected
- **List Payment Methods for Customer**: This was updated such that only payment methods with status `active` are listed for the customer. To make this backwards compatible, the default status for new saved cards is set to `active`.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This change is important for setting up MIT orchestration in the future.
# | 385622678f764b2bdb67423be0e5c8f055dd0b7c |
Local testing, postman tests. The saved card payments flow needs to work as usual which is covered by Postman tests.
When saving a card, the values of the added columns are set to default for now. This is NULL for `connector_mandate_details` and `customer_acceptance`, and `active` for `status`.
<img width="420" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/0bf2473c-90bb-4d9c-b3d2-b83905b5101c">
Since the default for the status column is set to `active`, the `List Payment Methods for Customer` flow works as intended for saved payment methods.
<img width="502" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6c7cbbea-4c99-4391-97db-81012d11e448">
| [
"crates/common_enums/src/enums.rs",
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/diesel_models/src/schema.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/payment_method.rs",
... | |
juspay/hyperswitch | juspay__hyperswitch-3781 | Bug: create api for custom roles
Create apis for
- create custom role
- update custom role | diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 2b8d0221497..f19ff95f9ed 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -1,8 +1,11 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
- AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest,
- ListRolesResponse, RoleInfoResponse, TransferOrgOwnershipRequest, UpdateUserRoleRequest,
+ role::{
+ CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, UpdateRoleRequest,
+ },
+ AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
+ TransferOrgOwnershipRequest, UpdateUserRoleRequest,
};
common_utils::impl_misc_api_event_type!(
@@ -13,5 +16,7 @@ common_utils::impl_misc_api_event_type!(
UpdateUserRoleRequest,
AcceptInvitationRequest,
DeleteUserRoleRequest,
- TransferOrgOwnershipRequest
+ TransferOrgOwnershipRequest,
+ CreateRoleRequest,
+ UpdateRoleRequest
);
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 1c4c28aa993..ed0838adc24 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,23 +1,8 @@
-use common_enums::RoleScope;
use common_utils::pii;
use crate::user::DashboardEntryResponse;
-#[derive(Debug, serde::Serialize)]
-pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
-
-#[derive(Debug, serde::Serialize)]
-pub struct RoleInfoResponse {
- pub role_id: String,
- pub permissions: Vec<Permission>,
- pub role_name: String,
- pub role_scope: RoleScope,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct GetRoleRequest {
- pub role_id: String,
-}
+pub mod role;
#[derive(Debug, serde::Serialize)]
pub enum Permission {
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
new file mode 100644
index 00000000000..4a767cfa723
--- /dev/null
+++ b/crates/api_models/src/user_role/role.rs
@@ -0,0 +1,30 @@
+use common_enums::{PermissionGroup, RoleScope};
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct CreateRoleRequest {
+ pub role_name: String,
+ pub groups: Vec<PermissionGroup>,
+ pub role_scope: RoleScope,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct UpdateRoleRequest {
+ pub groups: Option<Vec<PermissionGroup>>,
+ pub role_name: Option<String>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
+
+#[derive(Debug, serde::Serialize)]
+pub struct RoleInfoResponse {
+ pub role_id: String,
+ pub permissions: Vec<super::Permission>,
+ pub role_name: String,
+ pub role_scope: RoleScope,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct GetRoleRequest {
+ pub role_id: String,
+}
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index 6b21b1461cd..075d0602554 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -46,35 +46,25 @@ pub struct RoleUpdateInternal {
}
pub enum RoleUpdate {
- UpdateGroup {
- groups: Vec<enums::PermissionGroup>,
- last_modified_by: String,
- },
- UpdateRoleName {
- role_name: String,
+ UpdateDetails {
+ groups: Option<Vec<enums::PermissionGroup>>,
+ role_name: Option<String>,
+ last_modified_at: PrimitiveDateTime,
last_modified_by: String,
},
}
impl From<RoleUpdate> for RoleUpdateInternal {
fn from(value: RoleUpdate) -> Self {
- let last_modified_at = common_utils::date_time::now();
match value {
- RoleUpdate::UpdateGroup {
+ RoleUpdate::UpdateDetails {
groups,
- last_modified_by,
- } => Self {
- groups: Some(groups),
- role_name: None,
- last_modified_at,
- last_modified_by,
- },
- RoleUpdate::UpdateRoleName {
role_name,
last_modified_by,
+ last_modified_at,
} => Self {
- groups: None,
- role_name: Some(role_name),
+ groups,
+ role_name,
last_modified_at,
last_modified_by,
},
diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs
index ae1436bcd67..0a5d6556a11 100644
--- a/crates/router/src/consts/user_role.rs
+++ b/crates/router/src/consts/user_role.rs
@@ -9,3 +9,4 @@ pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer";
pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator";
pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support";
pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000";
+pub const MAX_ROLE_NAME_LENGTH: usize = 64;
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index c837fd7c20f..8a7d77cdbc9 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -62,6 +62,10 @@ pub enum UserErrors {
RoleNotFound,
#[error("InvalidRoleOperationWithMessage")]
InvalidRoleOperationWithMessage(String),
+ #[error("RoleNameParsingError")]
+ RoleNameParsingError,
+ #[error("RoleNameAlreadyExists")]
+ RoleNameAlreadyExists,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -159,6 +163,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::InvalidRoleOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None))
}
+ Self::RoleNameParsingError => {
+ AER::BadRequest(ApiError::new(sub_code, 34, self.get_error_message(), None))
+ }
+ Self::RoleNameAlreadyExists => {
+ AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
+ }
}
}
}
@@ -193,6 +203,8 @@ impl UserErrors {
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",
}
}
}
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index c2dfd34322c..b954e0df6c6 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -17,6 +17,8 @@ use crate::{
utils,
};
+pub mod role;
+
pub async fn get_authorization_info(
_state: AppState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
@@ -30,98 +32,6 @@ pub async fn get_authorization_info(
))
}
-pub async fn list_invitable_roles(
- state: AppState,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<user_role_api::ListRolesResponse> {
- let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| user_role_api::RoleInfoResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- });
-
- let custom_roles_map = state
- .store
- .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .map(roles::RoleInfo::from)
- .filter(|role_info| role_info.is_invitable())
- .map(|role_info| user_role_api::RoleInfoResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- });
-
- Ok(ApplicationResponse::Json(user_role_api::ListRolesResponse(
- predefined_roles_map.chain(custom_roles_map).collect(),
- )))
-}
-
-pub async fn get_role(
- state: AppState,
- user_from_token: auth::UserFromToken,
- role: user_role_api::GetRoleRequest,
-) -> UserResponse<user_role_api::RoleInfoResponse> {
- let role_info = roles::get_role_info_from_role_id(
- &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 permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(user_role_api::RoleInfoResponse {
- permissions,
- role_id: role.role_id,
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- }))
-}
-
-pub async fn get_role_from_token(
- state: AppState,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<Vec<user_role_api::Permission>> {
- let role_info = user_from_token
- .get_role_info_from_db(&state)
- .await
- .attach_printable("Invalid role_id in JWT")?;
-
- let permissions = role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect();
-
- Ok(ApplicationResponse::Json(permissions))
-}
-
pub async fn update_user_role(
state: AppState,
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
new file mode 100644
index 00000000000..7ce72779bbb
--- /dev/null
+++ b/crates/router/src/core/user_role/role.rs
@@ -0,0 +1,223 @@
+use api_models::user_role::{
+ role::{self as role_api},
+ Permission,
+};
+use common_enums::RoleScope;
+use common_utils::generate_id_with_default_len;
+use diesel_models::role::{RoleNew, RoleUpdate};
+use error_stack::ResultExt;
+
+use crate::{
+ consts,
+ core::errors::{StorageErrorExt, UserErrors, UserResponse},
+ routes::AppState,
+ services::{
+ authentication::UserFromToken,
+ authorization::roles::{self, predefined_roles::PREDEFINED_ROLES},
+ ApplicationResponse,
+ },
+ types::domain::user::RoleName,
+ utils,
+};
+
+pub async fn get_role_from_token(
+ state: AppState,
+ user_from_token: UserFromToken,
+) -> UserResponse<Vec<Permission>> {
+ let role_info = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?;
+
+ let permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(permissions))
+}
+
+pub async fn create_role(
+ state: AppState,
+ user_from_token: UserFromToken,
+ req: role_api::CreateRoleRequest,
+) -> UserResponse<()> {
+ let now = common_utils::date_time::now();
+ let role_name = RoleName::new(req.role_name)?.get_role_name();
+
+ if req.groups.is_empty() {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Role groups cannot be empty");
+ }
+
+ if matches!(req.role_scope, RoleScope::Organization)
+ && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
+ {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Non org admin user creating org level role");
+ }
+
+ utils::user_role::is_role_name_already_present_for_merchant(
+ &state,
+ &role_name,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await?;
+
+ state
+ .store
+ .insert_role(RoleNew {
+ role_id: generate_id_with_default_len("role"),
+ role_name,
+ merchant_id: user_from_token.merchant_id,
+ org_id: user_from_token.org_id,
+ groups: req.groups,
+ scope: req.role_scope,
+ created_by: user_from_token.user_id.clone(),
+ last_modified_by: user_from_token.user_id,
+ created_at: now,
+ last_modified_at: now,
+ })
+ .await
+ .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+pub async fn list_invitable_roles(
+ state: AppState,
+ user_from_token: UserFromToken,
+) -> UserResponse<role_api::ListRolesResponse> {
+ let predefined_roles_map = PREDEFINED_ROLES
+ .iter()
+ .filter(|(_, role_info)| role_info.is_invitable())
+ .map(|(role_id, role_info)| role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_id.to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
+ let custom_roles_map = state
+ .store
+ .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(roles::RoleInfo::from)
+ .filter(|role_info| role_info.is_invitable())
+ .map(|role_info| role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
+ Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
+ predefined_roles_map.chain(custom_roles_map).collect(),
+ )))
+}
+
+pub async fn get_role(
+ state: AppState,
+ user_from_token: UserFromToken,
+ role: role_api::GetRoleRequest,
+) -> UserResponse<role_api::RoleInfoResponse> {
+ let role_info = roles::get_role_info_from_role_id(
+ &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 permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(role_api::RoleInfoResponse {
+ permissions,
+ role_id: role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }))
+}
+
+pub async fn update_role(
+ state: AppState,
+ user_from_token: UserFromToken,
+ req: role_api::UpdateRoleRequest,
+ role_id: &str,
+) -> UserResponse<()> {
+ let role_name = req
+ .role_name
+ .map(RoleName::new)
+ .transpose()?
+ .map(RoleName::get_role_name);
+
+ if let Some(ref role_name) = role_name {
+ utils::user_role::is_role_name_already_present_for_merchant(
+ &state,
+ role_name,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await?;
+ }
+
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)?;
+
+ if matches!(role_info.get_scope(), RoleScope::Organization)
+ && user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
+ {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Non org admin user creating org level role");
+ }
+
+ if let Some(ref groups) = req.groups {
+ if groups.is_empty() {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("role groups cannot be empty");
+ }
+ }
+
+ state
+ .store
+ .update_role_by_role_id(
+ role_id,
+ RoleUpdate::UpdateDetails {
+ groups: req.groups,
+ role_name,
+ last_modified_at: common_utils::date_time::now(),
+ last_modified_by: user_from_token.user_id,
+ },
+ )
+ .await
+ .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 90e1e97e377..111b531e2f4 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -200,29 +200,21 @@ impl RoleInterface for MockDb {
role_update: storage::RoleUpdate,
) -> CustomResult<storage::Role, errors::StorageError> {
let mut roles = self.roles.lock().await;
- let last_modified_at = common_utils::date_time::now();
-
roles
.iter_mut()
.find(|role| role.role_id == role_id)
.map(|role| {
*role = match role_update {
- storage::RoleUpdate::UpdateGroup {
- groups,
- last_modified_by,
- } => storage::Role {
+ storage::RoleUpdate::UpdateDetails {
groups,
- last_modified_by,
- last_modified_at,
- ..role.to_owned()
- },
- storage::RoleUpdate::UpdateRoleName {
role_name,
+ last_modified_at,
last_modified_by,
} => storage::Role {
- role_name,
- last_modified_at,
+ groups: groups.unwrap_or(role.groups.to_owned()),
+ role_name: role_name.unwrap_or(role.role_name.to_owned()),
last_modified_by,
+ last_modified_at,
..role.to_owned()
},
};
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 26f5b528072..a11265fde80 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1052,9 +1052,17 @@ impl User {
// Role information
route = route.service(
web::scope("/role")
- .service(web::resource("").route(web::get().to(get_role_from_token)))
+ .service(
+ web::resource("")
+ .route(web::get().to(get_role_from_token))
+ .route(web::post().to(create_role)),
+ )
.service(web::resource("/list").route(web::get().to(list_all_roles)))
- .service(web::resource("/{role_id}").route(web::get().to(get_role))),
+ .service(
+ web::resource("/{role_id}")
+ .route(web::get().to(get_role))
+ .route(web::put().to(update_role)),
+ ),
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index e3b04bd3f73..0214d3b5e3d 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -29,6 +29,7 @@ pub enum ApiIdentifier {
Forex,
RustLockerMigration,
Gsm,
+ Role,
User,
UserRole,
ConnectorOnboarding,
@@ -200,7 +201,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::GetAuthorizationInfo
| Flow::AcceptInvitation
| Flow::DeleteUserRole
- | Flow::TransferOrgOwnership => Self::UserRole,
+ | Flow::TransferOrgOwnership
+ | Flow::CreateRole
+ | Flow::UpdateRole => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 63e2ce37269..52e739c36e1 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -7,7 +7,7 @@ use crate::{
core::{api_locking, user_role as user_role_core},
services::{
api,
- authentication::{self as auth, UserFromToken},
+ authentication::{self as auth},
authorization::permissions::Permission,
},
};
@@ -29,6 +29,38 @@ pub async fn get_authorization_info(
.await
}
+pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::GetRoleFromToken;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _| user_role_core::role::get_role_from_token(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn create_role(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_role_api::role::CreateRoleRequest>,
+) -> HttpResponse {
+ let flow = Flow::CreateRole;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ user_role_core::role::create_role,
+ &auth::JWTAuth(Permission::UsersWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::ListRoles;
Box::pin(api::server_wrap(
@@ -36,7 +68,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt
state.clone(),
&req,
(),
- |state, user, _| user_role_core::list_invitable_roles(state, user),
+ |state, user, _| user_role_core::role::list_invitable_roles(state, user),
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -49,7 +81,7 @@ pub async fn get_role(
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetRole;
- let request_payload = user_role_api::GetRoleRequest {
+ let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
Box::pin(api::server_wrap(
@@ -57,22 +89,29 @@ pub async fn get_role(
state.clone(),
&req,
request_payload,
- user_role_core::get_role,
+ user_role_core::role::get_role,
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
.await
}
-pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::GetRoleFromToken;
+pub async fn update_role(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_role_api::role::UpdateRoleRequest>,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::UpdateRole;
+ let role_id = path.into_inner();
+
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
- (),
- |state, user: UserFromToken, _| user_role_core::get_role_from_token(state, user),
- &auth::DashboardNoPermissionAuth,
+ json_payload.into_inner(),
+ |state, user, req| user_role_core::role::update_role(state, user, req, &role_id),
+ &auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 263b0e52b8a..a759bf00806 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -926,3 +926,23 @@ impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
}
}
}
+
+#[derive(Clone)]
+pub struct RoleName(String);
+
+impl RoleName {
+ pub fn new(name: String) -> UserResult<Self> {
+ let is_empty_or_whitespace = name.trim().is_empty();
+ let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH;
+
+ if is_empty_or_whitespace || is_too_long || name.contains(' ') {
+ Err(UserErrors::RoleNameParsingError.into())
+ } else {
+ Ok(Self(name.to_lowercase()))
+ }
+ }
+
+ pub fn get_role_name(self) -> String {
+ self.0
+ }
+}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index ef69219b4c9..8ae65ce86e0 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,6 +1,11 @@
use api_models::user_role as user_role_api;
+use error_stack::ResultExt;
-use crate::services::authorization::permissions::Permission;
+use crate::{
+ core::errors::{UserErrors, UserResult},
+ routes::AppState,
+ services::authorization::permissions::Permission,
+};
impl From<Permission> for user_role_api::Permission {
fn from(value: Permission) -> Self {
@@ -34,3 +39,24 @@ impl From<Permission> for user_role_api::Permission {
}
}
}
+
+pub async fn is_role_name_already_present_for_merchant(
+ state: &AppState,
+ role_name: &str,
+ merchant_id: &str,
+ org_id: &str,
+) -> UserResult<()> {
+ let role_name_list: Vec<String> = state
+ .store
+ .list_all_roles(merchant_id, org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .iter()
+ .map(|role| role.role_name.to_owned())
+ .collect();
+
+ if role_name_list.contains(&role_name.to_string()) {
+ return Err(UserErrors::RoleNameAlreadyExists.into());
+ }
+ Ok(())
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b2e665059e7..4af81ae49ca 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -363,6 +363,10 @@ pub enum Flow {
UpdateUserAccountDetails,
/// Accept user invitation
AcceptInvitation,
+ /// Create Role
+ CreateRole,
+ /// Update Role
+ UpdateRole,
}
///
diff --git a/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql b/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql
new file mode 100644
index 00000000000..3fcac875de6
--- /dev/null
+++ b/migrations/2024-02-22-100718_role_name_org_id_constraint/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+DROP INDEX role_name_org_id_org_scope_index;
+DROP INDEX role_name_merchant_id_merchant_scope_index;
diff --git a/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql b/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql
new file mode 100644
index 00000000000..9780e01b772
--- /dev/null
+++ b/migrations/2024-02-22-100718_role_name_org_id_constraint/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+CREATE UNIQUE INDEX role_name_org_id_org_scope_index ON roles(org_id, role_name) WHERE scope='organization';
+CREATE UNIQUE INDEX role_name_merchant_id_merchant_scope_index ON roles(merchant_id, role_name) WHERE scope='merchant';
| 2024-02-21T21:19:02Z |
## Description
Add functionality for
- create role api
- update role api
## Motivation and Context
User should be allowed to create/update custom roles.
# | bbb3d3d1e26f303964a495606dece7958f6c40fc | Create role
```
curl --location --request PUT 'http://localhost:8080/user/role' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \
--header 'Content-Type: application/json' \
--data '{
"role_name": "test_x",
"groups": ["operations_view"],
"role_scope": "organization"
}'
```
Update
```
curl --location --request PUT 'http://localhost:8080/user/role/role_cau2w3YVoakCr30XWeJi' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOGJiZGM4YWUtZDlhYS00NGUxLWFkYzYtYjEyMjZiYjkxZDliIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA4NjAxMTE3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwODc3MzkxNywib3JnX2lkIjoib3JnX1dFN1Z3emNITWRaS01hTzYzeW9pIn0.l5tcWpOqgTVxGKw6zQvx-4iBBmOietj1-drGgzqFYBg' \
--header 'Content-Type: application/json' \
--data '{
"role_name": "test",
"groups": ["workflows_manage"]
}'
```
Response will be 200 Ok.
| [
"crates/api_models/src/events/user_role.rs",
"crates/api_models/src/user_role.rs",
"crates/api_models/src/user_role/role.rs",
"crates/diesel_models/src/role.rs",
"crates/router/src/consts/user_role.rs",
"crates/router/src/core/errors/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/... | |
juspay/hyperswitch | juspay__hyperswitch-3761 | Bug: [BUG] Internal Server Error thrown when updating or deleting non-existent API key
### Bug Description
When a user tries to update or delete a non-existent API key, an internal server error is thrown. The expected behavior is that the server returns a 404 status code, informing that the API key does not exist.
### Expected Behavior
Server should return 404 status code.
### Actual Behavior
Server returns internal server error (500 status code) with the following response:
```json
{
"error": {
"type": "api",
"message": "Something went wrong",
"code": "HE_00"
}
}
```
### Steps To Reproduce
The following steps assume that the admin API key for the deployed server is known to the user.
1. Create a merchant account using the create merchant account API and admin API key.
2. Try to use the update API key endpoint or the delete API key endpoint with a non-existent API key ID.
For example, the delete API key request could look like so:
```shell
curl --location --request DELETE 'http://localhost:8080/api_keys/<merchant_id>/a-non-existent-key-id' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: <ADMIN_API_KEY>'
```
Server returns the aforementioned response.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 14d1eb2db63..9e3ef903f5c 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -139,6 +139,7 @@ impl StorageError {
pub fn is_db_not_found(&self) -> bool {
match self {
Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound),
+ Self::ValueNotFound(_) => true,
_ => false,
}
}
| 2024-02-21T20:35:44Z |
## Description
<!-- Describe your changes in detail -->
This PR fixes a bug with the update API key and delete API key endpoints throwing an internal server error when a non-existent API key was provided.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #3761.
# | ef5e886ab1abdf50254343be8c6c48100ec2ec2d |
Locally. Trying to either update a non-existent API key returns a 404 status code, with an error message stating that the API key does not exist.
1. Update API key (request body may contain data or could just be an empty object):
```shell
curl --location 'http://localhost:8080/api_keys/<merchant_id>/invalid-api-key-id' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: <ADMIN_API_KEY>' \
--data '{}'
```
2. Delete API key:
```shell
curl --location --request DELETE 'http://localhost:8080/<merchant_id>/merchant_1708546282/invalid-api-key-id' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:<ADMIN_API_KEY>'
```
In both cases, the response returned should be the same, with a 404 status code:
```json
{
"error": {
"type": "invalid_request",
"message": "API Key does not exist in our records",
"code": "HE_02"
}
}
```
| [
"crates/storage_impl/src/errors.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3813 | Bug: Update Hyperswitch Token construction to include MIT details
- To begin with we will store Payment Method ID along with the Locker ID in the token instead | diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index d8b46c1932e..f9767e2939b 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -33,6 +33,7 @@ pub struct PaymentMethod {
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
@@ -59,6 +60,7 @@ pub struct PaymentMethodNew {
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -69,6 +71,7 @@ impl Default for PaymentMethodNew {
customer_id: String::default(),
merchant_id: String::default(),
payment_method_id: String::default(),
+ locker_id: Option::default(),
payment_method: storage_enums::PaymentMethod::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index b1ea3ee388a..298db2a234b 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -44,6 +44,15 @@ impl PaymentMethod {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::locker_id.eq(locker_id.to_owned()),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 5093f0df7d0..3364e560277 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -828,6 +828,8 @@ diesel::table! {
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
+ #[max_length = 64]
+ locker_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 9442bf2ff34..be306112873 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -218,7 +218,7 @@ pub async fn delete_customer(
&state,
&req.customer_id,
&merchant_account.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 2ebec569b38..1347bb8ffd0 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -83,9 +83,13 @@ pub async fn call_to_locker(
.into_iter()
.filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
{
- let card =
- cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id)
- .await;
+ let card = cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await;
let card = match card {
Ok(card) => card,
@@ -127,7 +131,7 @@ pub async fn call_to_locker(
customer_id.to_string(),
merchant_account,
api_enums::LockerChoice::HyperswitchCardVault,
- Some(&pm.payment_method_id),
+ Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index c1617fa77c9..bdbd9b02d9e 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::Permanent(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::PermanentCard(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index dbd8efcd1cf..7bf956be9ff 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -76,6 +76,7 @@ pub async fn create_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &str,
payment_method_id: &str,
+ locker_id: Option<String>,
merchant_id: &str,
pm_metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -90,6 +91,7 @@ pub async fn create_payment_method(
customer_id: customer_id.to_string(),
merchant_id: merchant_id.to_string(),
payment_method_id: payment_method_id.to_string(),
+ locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
@@ -131,6 +133,65 @@ pub fn store_default_payment_method(
(payment_method_response, None)
}
+#[instrument(skip_all)]
+pub async fn get_or_insert_payment_method(
+ db: &dyn db::StorageInterface,
+ req: api::PaymentMethodCreate,
+ resp: &mut api::PaymentMethodResponse,
+ merchant_account: &domain::MerchantAccount,
+ customer_id: &str,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+ let payment_method = {
+ let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => payment_method_id = pm.payment_method_id.clone(),
+ Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+ resp.payment_method_id = payment_method_id.to_owned();
+
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ insert_payment_method(
+ db,
+ resp,
+ req,
+ key_store,
+ &merchant_account.merchant_id,
+ customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -182,40 +243,41 @@ pub async fn add_payment_method(
)),
};
- let (resp, duplication_check) = response?;
+ let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
-
- if let Err(err) = existing_pm {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?
- };
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
}
-
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
+ let existing_pm = get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
+
delete_card_from_locker(
&state,
&customer_id,
merchant_id,
- &resp.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
@@ -226,7 +288,12 @@ pub async fn add_payment_method(
customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&resp.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -243,69 +310,46 @@ pub async fn add_payment_method(
.attach_printable("Failed while updating card metadata changes"))?
};
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
- card.clone(),
- ))
- });
- let pm_data_encrypted =
- create_encrypted_payment_method_data(key_store, updated_pmd).await;
-
- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
-
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method in db")?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?;
- }
- }
+ let updated_card = Some(api::CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
+ });
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
+
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
+ let locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
&resp,
@@ -314,14 +358,16 @@ pub async fn add_payment_method(
merchant_id,
&customer_id,
pm_metadata.cloned(),
+ locker_id,
)
.await?;
}
- };
+ }
Ok(services::ApplicationResponse::Json(resp))
}
+#[allow(clippy::too_many_arguments)]
pub async fn insert_payment_method(
db: &dyn db::StorageInterface,
resp: &api::PaymentMethodResponse,
@@ -330,7 +376,8 @@ pub async fn insert_payment_method(
merchant_id: &str,
customer_id: &str,
pm_metadata: Option<serde_json::Value>,
-) -> errors::RouterResult<()> {
+ locker_id: Option<String>,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
let pm_card_details = resp
.card
.as_ref()
@@ -341,14 +388,13 @@ pub async fn insert_payment_method(
&req,
customer_id,
&resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
key_store,
)
- .await?;
-
- Ok(())
+ .await
}
#[instrument(skip_all)]
@@ -372,7 +418,7 @@ pub async fn update_customer_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
};
@@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>(
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
@@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>(
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
})
@@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>(
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
@@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method(
(
card_details,
None,
- PaymentTokenData::permanent_card(pm.payment_method_id.clone()),
+ PaymentTokenData::permanent_card(
+ Some(pm.payment_method_id.clone()),
+ pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
+ pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
+ ),
)
} else {
continue;
@@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method(
&token,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?,
),
@@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3217,11 +3267,11 @@ pub async fn delete_payment_method(
&state,
&key.customer_id,
&key.merchant_id,
- pm_id.payment_method_id.as_str(),
+ key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
- if response.status == "SUCCESS" {
+ if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 57e46bc9769..6bad41630b5 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs(
}
}
-pub fn mk_add_card_response(
- card: api::CardDetail,
- response: AddCardResponse,
- req: api::PaymentMethodCreate,
- merchant_id: &str,
-) -> api::PaymentMethodResponse {
- let mut card_number = card.card_number.peek().to_owned();
- let card = api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card_number.split_off(card_number.len() - 4)),
- issuer_country: None, // [#256] bin mapping
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: Some(response.external_id.into()), // [#256]
- card_fingerprint: Some(response.card_fingerprint),
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_isin: None,
- card_issuer: None,
- card_network: None,
- card_type: None,
- saved_to_locker: true,
- };
- api::PaymentMethodResponse {
- merchant_id: merchant_id.to_owned(),
- customer_id: req.customer_id,
- payment_method_id: response.card_id,
- payment_method: req.payment_method,
- payment_method_type: req.payment_method_type,
- bank_transfer: None,
- card: Some(card),
- metadata: req.metadata,
- created: Some(common_utils::date_time::now()),
- recurring_enabled: false, // [#256]
- installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker
- payment_experience: None, // [#256]
- }
-}
-
pub fn mk_add_card_request(
locker: &settings::Locker,
card: &api::CardDetail,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2d7a09bdae1..d08f0208500 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -6,6 +6,7 @@ use router_env::{instrument, tracing};
use super::helpers;
use crate::{
+ consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate, payment_methods, payments,
@@ -19,7 +20,7 @@ use crate::{
domain,
storage::{self, enums as storage_enums},
},
- utils::OptionExt,
+ utils::{generate_id, OptionExt},
};
#[instrument(skip_all)]
@@ -85,7 +86,7 @@ where
.await?;
let merchant_id = &merchant_account.merchant_id;
- let locker_response = if !state.conf.locker.locker_enabled {
+ let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
payment_method_create_request.to_owned(),
@@ -100,9 +101,7 @@ where
.await?
};
- let duplication_check = locker_response.1;
-
- let pm_card_details = locker_response.0.card.as_ref().map(|card| {
+ let pm_card_details = resp.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
card.clone(),
))
@@ -115,13 +114,44 @@ where
)
.await;
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
- .await;
- match existing_pm {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
@@ -146,7 +176,8 @@ where
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -165,22 +196,87 @@ where
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(
+ &payment_method_id,
+ )
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ let existing_pm =
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }?;
+
payment_methods::cards::delete_card_from_locker(
state,
&customer.customer_id,
merchant_id,
- &locker_response.0.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = payment_methods::cards::add_card_hs(
state,
- payment_method_create_request.clone(),
+ payment_method_create_request,
&card,
customer.customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&locker_response.0.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -188,7 +284,7 @@ where
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
merchant_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
)
.await
.to_not_found_response(
@@ -201,90 +297,59 @@ where
))?
};
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
+ let updated_card = Some(CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
+ card.clone(),
+ ))
+ });
+ let pm_data_encrypted =
+ payment_methods::cards::create_encrypted_payment_method_data(
+ key_store,
+ updated_pmd,
+ )
.await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(
- card.card_number.clone().get_last4(),
- ),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card.clone()),
- )
- });
- let pm_data_encrypted =
- payment_methods::cards::create_encrypted_payment_method_data(
- key_store,
- updated_pmd,
- )
- .await;
- let pm_update =
- storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
+ let pm_update =
+ storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Failed to add payment method in db",
- )?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &locker_response.0,
- payment_method_create_request,
- key_store,
- merchant_id,
- &customer.customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Error while finding payment method",
- )
- }?;
- }
- }
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
+
+ locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -294,7 +359,7 @@ where
}
}
- Some(locker_response.0.payment_method_id)
+ Some(resp.payment_method_id)
} else {
None
};
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7fb6fa3bde6..de57f8549db 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>(
.attach_printable("failed to deserialize hyperswitch token data")?;
let payment_token = match payment_token_data {
- storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => {
- Some(token)
- }
+ storage::PaymentTokenData::PermanentCard(storage::CardTokenData {
+ locker_id,
+ token,
+ ..
+ }) => locker_id.or(Some(token)),
storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData {
token,
}) => Some(token),
@@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker(
card_network: None,
};
+ let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
cards::create_payment_method(
db,
&payment_method,
&payout_attempt.customer_id,
- &stored_resp.card_reference,
+ &payment_method_id,
+ Some(stored_resp.card_reference),
&merchant_account.merchant_id,
None,
card_details_encrypted,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 78b95544ca1..9dbecd82485 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_locker_id(locker_id)
+ .await
+ }
+
async fn insert_payment_method(
&self,
m: storage::PaymentMethodNew,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index b109d1fe5bd..4f4087f552e 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -15,6 +15,11 @@ pub trait PaymentMethodInterface {
payment_method_id: &str,
) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &str,
@@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::find_by_locker_id(&conn, locker_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.locker_id == Some(locker_id.to_string()))
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: payment_method_new.customer_id,
merchant_id: payment_method_new.merchant_id,
payment_method_id: payment_method_new.payment_method_id,
+ locker_id: payment_method_new.locker_id,
accepted_currency: payment_method_new.accepted_currency,
scheme: payment_method_new.scheme,
token: payment_method_new.token,
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 051547dfa92..10c56973dd3 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse {
state,
&payment_method.customer_id,
&payment_method.merchant_id,
- &payment_method.payment_method_id,
+ payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(&payment_method.payment_method_id),
)
.await?;
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 096303446dc..a787a4d932c 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -13,6 +13,8 @@ pub enum PaymentTokenKind {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
+ pub payment_method_id: Option<String>,
+ pub locker_id: Option<String>,
pub token: String,
}
@@ -34,8 +36,16 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
- pub fn permanent_card(token: String) -> Self {
- Self::PermanentCard(CardTokenData { token })
+ pub fn permanent_card(
+ payment_method_id: Option<String>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
}
pub fn temporary_generic(token: String) -> Self {
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
new file mode 100644
index 00000000000..90eaebaf4da
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id;
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
new file mode 100644
index 00000000000..516dc8a8818
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
| 2024-02-21T17:18:08Z |
## Description
<!-- Describe your changes in detail -->
Currently we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 75c633fc7c37341177597041ccbcdfc3cf9e236f |
Sandbox testing -
* Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146
* Test it for both old card already saved before this PR went in along with new card
* Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine
Test cases (`payment_methods` table) -
(Card 1): Db entry before this code changes :- `locker_id` should be null

(Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

(Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id

(Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

Redis entry (Local testing) -
Old card (both locker_id and payment_method_id will be same):

New card (payment_method_id will be nano_id and locker_id will be the id returned from locker):

| [
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/diesel_models/src/schema.rs",
"crates/router/src/core/customers.rs",
"crates/router/src/core/locker_migration.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payment_method... | |
juspay/hyperswitch | juspay__hyperswitch-3742 | Bug: Locker ID as a soft link for Payment Methods
Decoupling the Payment Method ID and Locker ID to allow more flexibility in PM ID usage for other features/components
- Add Card operation to save the Locker ID in the `locker_id` column of the PM table and generate and add a separate PM ID
- During retrieve, locker fetch to happen based on Locker ID with Payment Method ID as fallback (for ensuring continuity) | diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index d8b46c1932e..f9767e2939b 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -33,6 +33,7 @@ pub struct PaymentMethod {
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
@@ -59,6 +60,7 @@ pub struct PaymentMethodNew {
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -69,6 +71,7 @@ impl Default for PaymentMethodNew {
customer_id: String::default(),
merchant_id: String::default(),
payment_method_id: String::default(),
+ locker_id: Option::default(),
payment_method: storage_enums::PaymentMethod::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index b1ea3ee388a..298db2a234b 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -44,6 +44,15 @@ impl PaymentMethod {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::locker_id.eq(locker_id.to_owned()),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 5093f0df7d0..3364e560277 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -828,6 +828,8 @@ diesel::table! {
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
+ #[max_length = 64]
+ locker_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 9442bf2ff34..be306112873 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -218,7 +218,7 @@ pub async fn delete_customer(
&state,
&req.customer_id,
&merchant_account.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 2ebec569b38..1347bb8ffd0 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -83,9 +83,13 @@ pub async fn call_to_locker(
.into_iter()
.filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
{
- let card =
- cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id)
- .await;
+ let card = cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await;
let card = match card {
Ok(card) => card,
@@ -127,7 +131,7 @@ pub async fn call_to_locker(
customer_id.to_string(),
merchant_account,
api_enums::LockerChoice::HyperswitchCardVault,
- Some(&pm.payment_method_id),
+ Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index c1617fa77c9..bdbd9b02d9e 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::Permanent(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::PermanentCard(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index dbd8efcd1cf..7bf956be9ff 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -76,6 +76,7 @@ pub async fn create_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &str,
payment_method_id: &str,
+ locker_id: Option<String>,
merchant_id: &str,
pm_metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -90,6 +91,7 @@ pub async fn create_payment_method(
customer_id: customer_id.to_string(),
merchant_id: merchant_id.to_string(),
payment_method_id: payment_method_id.to_string(),
+ locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
@@ -131,6 +133,65 @@ pub fn store_default_payment_method(
(payment_method_response, None)
}
+#[instrument(skip_all)]
+pub async fn get_or_insert_payment_method(
+ db: &dyn db::StorageInterface,
+ req: api::PaymentMethodCreate,
+ resp: &mut api::PaymentMethodResponse,
+ merchant_account: &domain::MerchantAccount,
+ customer_id: &str,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+ let payment_method = {
+ let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => payment_method_id = pm.payment_method_id.clone(),
+ Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+ resp.payment_method_id = payment_method_id.to_owned();
+
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ insert_payment_method(
+ db,
+ resp,
+ req,
+ key_store,
+ &merchant_account.merchant_id,
+ customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -182,40 +243,41 @@ pub async fn add_payment_method(
)),
};
- let (resp, duplication_check) = response?;
+ let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
-
- if let Err(err) = existing_pm {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?
- };
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
}
-
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
+ let existing_pm = get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
+
delete_card_from_locker(
&state,
&customer_id,
merchant_id,
- &resp.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
@@ -226,7 +288,12 @@ pub async fn add_payment_method(
customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&resp.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -243,69 +310,46 @@ pub async fn add_payment_method(
.attach_printable("Failed while updating card metadata changes"))?
};
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
- card.clone(),
- ))
- });
- let pm_data_encrypted =
- create_encrypted_payment_method_data(key_store, updated_pmd).await;
-
- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
-
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method in db")?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?;
- }
- }
+ let updated_card = Some(api::CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
+ });
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
+
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
+ let locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
&resp,
@@ -314,14 +358,16 @@ pub async fn add_payment_method(
merchant_id,
&customer_id,
pm_metadata.cloned(),
+ locker_id,
)
.await?;
}
- };
+ }
Ok(services::ApplicationResponse::Json(resp))
}
+#[allow(clippy::too_many_arguments)]
pub async fn insert_payment_method(
db: &dyn db::StorageInterface,
resp: &api::PaymentMethodResponse,
@@ -330,7 +376,8 @@ pub async fn insert_payment_method(
merchant_id: &str,
customer_id: &str,
pm_metadata: Option<serde_json::Value>,
-) -> errors::RouterResult<()> {
+ locker_id: Option<String>,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
let pm_card_details = resp
.card
.as_ref()
@@ -341,14 +388,13 @@ pub async fn insert_payment_method(
&req,
customer_id,
&resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
key_store,
)
- .await?;
-
- Ok(())
+ .await
}
#[instrument(skip_all)]
@@ -372,7 +418,7 @@ pub async fn update_customer_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
};
@@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>(
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
@@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>(
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
})
@@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>(
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
@@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method(
(
card_details,
None,
- PaymentTokenData::permanent_card(pm.payment_method_id.clone()),
+ PaymentTokenData::permanent_card(
+ Some(pm.payment_method_id.clone()),
+ pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
+ pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
+ ),
)
} else {
continue;
@@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method(
&token,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?,
),
@@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3217,11 +3267,11 @@ pub async fn delete_payment_method(
&state,
&key.customer_id,
&key.merchant_id,
- pm_id.payment_method_id.as_str(),
+ key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
- if response.status == "SUCCESS" {
+ if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 57e46bc9769..6bad41630b5 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs(
}
}
-pub fn mk_add_card_response(
- card: api::CardDetail,
- response: AddCardResponse,
- req: api::PaymentMethodCreate,
- merchant_id: &str,
-) -> api::PaymentMethodResponse {
- let mut card_number = card.card_number.peek().to_owned();
- let card = api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card_number.split_off(card_number.len() - 4)),
- issuer_country: None, // [#256] bin mapping
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: Some(response.external_id.into()), // [#256]
- card_fingerprint: Some(response.card_fingerprint),
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_isin: None,
- card_issuer: None,
- card_network: None,
- card_type: None,
- saved_to_locker: true,
- };
- api::PaymentMethodResponse {
- merchant_id: merchant_id.to_owned(),
- customer_id: req.customer_id,
- payment_method_id: response.card_id,
- payment_method: req.payment_method,
- payment_method_type: req.payment_method_type,
- bank_transfer: None,
- card: Some(card),
- metadata: req.metadata,
- created: Some(common_utils::date_time::now()),
- recurring_enabled: false, // [#256]
- installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker
- payment_experience: None, // [#256]
- }
-}
-
pub fn mk_add_card_request(
locker: &settings::Locker,
card: &api::CardDetail,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2d7a09bdae1..d08f0208500 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -6,6 +6,7 @@ use router_env::{instrument, tracing};
use super::helpers;
use crate::{
+ consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate, payment_methods, payments,
@@ -19,7 +20,7 @@ use crate::{
domain,
storage::{self, enums as storage_enums},
},
- utils::OptionExt,
+ utils::{generate_id, OptionExt},
};
#[instrument(skip_all)]
@@ -85,7 +86,7 @@ where
.await?;
let merchant_id = &merchant_account.merchant_id;
- let locker_response = if !state.conf.locker.locker_enabled {
+ let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
payment_method_create_request.to_owned(),
@@ -100,9 +101,7 @@ where
.await?
};
- let duplication_check = locker_response.1;
-
- let pm_card_details = locker_response.0.card.as_ref().map(|card| {
+ let pm_card_details = resp.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
card.clone(),
))
@@ -115,13 +114,44 @@ where
)
.await;
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
- .await;
- match existing_pm {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
@@ -146,7 +176,8 @@ where
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -165,22 +196,87 @@ where
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(
+ &payment_method_id,
+ )
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ let existing_pm =
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }?;
+
payment_methods::cards::delete_card_from_locker(
state,
&customer.customer_id,
merchant_id,
- &locker_response.0.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = payment_methods::cards::add_card_hs(
state,
- payment_method_create_request.clone(),
+ payment_method_create_request,
&card,
customer.customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&locker_response.0.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -188,7 +284,7 @@ where
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
merchant_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
)
.await
.to_not_found_response(
@@ -201,90 +297,59 @@ where
))?
};
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
+ let updated_card = Some(CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
+ card.clone(),
+ ))
+ });
+ let pm_data_encrypted =
+ payment_methods::cards::create_encrypted_payment_method_data(
+ key_store,
+ updated_pmd,
+ )
.await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(
- card.card_number.clone().get_last4(),
- ),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card.clone()),
- )
- });
- let pm_data_encrypted =
- payment_methods::cards::create_encrypted_payment_method_data(
- key_store,
- updated_pmd,
- )
- .await;
- let pm_update =
- storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
+ let pm_update =
+ storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Failed to add payment method in db",
- )?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &locker_response.0,
- payment_method_create_request,
- key_store,
- merchant_id,
- &customer.customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Error while finding payment method",
- )
- }?;
- }
- }
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
+
+ locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -294,7 +359,7 @@ where
}
}
- Some(locker_response.0.payment_method_id)
+ Some(resp.payment_method_id)
} else {
None
};
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7fb6fa3bde6..de57f8549db 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>(
.attach_printable("failed to deserialize hyperswitch token data")?;
let payment_token = match payment_token_data {
- storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => {
- Some(token)
- }
+ storage::PaymentTokenData::PermanentCard(storage::CardTokenData {
+ locker_id,
+ token,
+ ..
+ }) => locker_id.or(Some(token)),
storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData {
token,
}) => Some(token),
@@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker(
card_network: None,
};
+ let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
cards::create_payment_method(
db,
&payment_method,
&payout_attempt.customer_id,
- &stored_resp.card_reference,
+ &payment_method_id,
+ Some(stored_resp.card_reference),
&merchant_account.merchant_id,
None,
card_details_encrypted,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 78b95544ca1..9dbecd82485 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_locker_id(locker_id)
+ .await
+ }
+
async fn insert_payment_method(
&self,
m: storage::PaymentMethodNew,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index b109d1fe5bd..4f4087f552e 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -15,6 +15,11 @@ pub trait PaymentMethodInterface {
payment_method_id: &str,
) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &str,
@@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::find_by_locker_id(&conn, locker_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.locker_id == Some(locker_id.to_string()))
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: payment_method_new.customer_id,
merchant_id: payment_method_new.merchant_id,
payment_method_id: payment_method_new.payment_method_id,
+ locker_id: payment_method_new.locker_id,
accepted_currency: payment_method_new.accepted_currency,
scheme: payment_method_new.scheme,
token: payment_method_new.token,
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 051547dfa92..10c56973dd3 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse {
state,
&payment_method.customer_id,
&payment_method.merchant_id,
- &payment_method.payment_method_id,
+ payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(&payment_method.payment_method_id),
)
.await?;
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 096303446dc..a787a4d932c 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -13,6 +13,8 @@ pub enum PaymentTokenKind {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
+ pub payment_method_id: Option<String>,
+ pub locker_id: Option<String>,
pub token: String,
}
@@ -34,8 +36,16 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
- pub fn permanent_card(token: String) -> Self {
- Self::PermanentCard(CardTokenData { token })
+ pub fn permanent_card(
+ payment_method_id: Option<String>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
}
pub fn temporary_generic(token: String) -> Self {
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
new file mode 100644
index 00000000000..90eaebaf4da
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id;
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
new file mode 100644
index 00000000000..516dc8a8818
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
| 2024-02-21T17:18:08Z |
## Description
<!-- Describe your changes in detail -->
Currently we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 75c633fc7c37341177597041ccbcdfc3cf9e236f |
Sandbox testing -
* Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146
* Test it for both old card already saved before this PR went in along with new card
* Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine
Test cases (`payment_methods` table) -
(Card 1): Db entry before this code changes :- `locker_id` should be null

(Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

(Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id

(Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

Redis entry (Local testing) -
Old card (both locker_id and payment_method_id will be same):

New card (payment_method_id will be nano_id and locker_id will be the id returned from locker):

| [
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/diesel_models/src/schema.rs",
"crates/router/src/core/customers.rs",
"crates/router/src/core/locker_migration.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payment_method... | |
juspay/hyperswitch | juspay__hyperswitch-3731 | Bug: [REFACTOR] introduce `locker_id` column in payment_methods table
Currently we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
| diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index d8b46c1932e..f9767e2939b 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -33,6 +33,7 @@ pub struct PaymentMethod {
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
@@ -59,6 +60,7 @@ pub struct PaymentMethodNew {
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -69,6 +71,7 @@ impl Default for PaymentMethodNew {
customer_id: String::default(),
merchant_id: String::default(),
payment_method_id: String::default(),
+ locker_id: Option::default(),
payment_method: storage_enums::PaymentMethod::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index b1ea3ee388a..298db2a234b 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -44,6 +44,15 @@ impl PaymentMethod {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::locker_id.eq(locker_id.to_owned()),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 5093f0df7d0..3364e560277 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -828,6 +828,8 @@ diesel::table! {
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
+ #[max_length = 64]
+ locker_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 9442bf2ff34..be306112873 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -218,7 +218,7 @@ pub async fn delete_customer(
&state,
&req.customer_id,
&merchant_account.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 2ebec569b38..1347bb8ffd0 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -83,9 +83,13 @@ pub async fn call_to_locker(
.into_iter()
.filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
{
- let card =
- cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id)
- .await;
+ let card = cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await;
let card = match card {
Ok(card) => card,
@@ -127,7 +131,7 @@ pub async fn call_to_locker(
customer_id.to_string(),
merchant_account,
api_enums::LockerChoice::HyperswitchCardVault,
- Some(&pm.payment_method_id),
+ Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index c1617fa77c9..bdbd9b02d9e 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::Permanent(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::PermanentCard(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index dbd8efcd1cf..7bf956be9ff 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -76,6 +76,7 @@ pub async fn create_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &str,
payment_method_id: &str,
+ locker_id: Option<String>,
merchant_id: &str,
pm_metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -90,6 +91,7 @@ pub async fn create_payment_method(
customer_id: customer_id.to_string(),
merchant_id: merchant_id.to_string(),
payment_method_id: payment_method_id.to_string(),
+ locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
@@ -131,6 +133,65 @@ pub fn store_default_payment_method(
(payment_method_response, None)
}
+#[instrument(skip_all)]
+pub async fn get_or_insert_payment_method(
+ db: &dyn db::StorageInterface,
+ req: api::PaymentMethodCreate,
+ resp: &mut api::PaymentMethodResponse,
+ merchant_account: &domain::MerchantAccount,
+ customer_id: &str,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+ let payment_method = {
+ let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => payment_method_id = pm.payment_method_id.clone(),
+ Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+ resp.payment_method_id = payment_method_id.to_owned();
+
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ insert_payment_method(
+ db,
+ resp,
+ req,
+ key_store,
+ &merchant_account.merchant_id,
+ customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -182,40 +243,41 @@ pub async fn add_payment_method(
)),
};
- let (resp, duplication_check) = response?;
+ let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
-
- if let Err(err) = existing_pm {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?
- };
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
}
-
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
+ let existing_pm = get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
+
delete_card_from_locker(
&state,
&customer_id,
merchant_id,
- &resp.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
@@ -226,7 +288,12 @@ pub async fn add_payment_method(
customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&resp.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -243,69 +310,46 @@ pub async fn add_payment_method(
.attach_printable("Failed while updating card metadata changes"))?
};
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
- card.clone(),
- ))
- });
- let pm_data_encrypted =
- create_encrypted_payment_method_data(key_store, updated_pmd).await;
-
- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
-
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method in db")?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?;
- }
- }
+ let updated_card = Some(api::CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
+ });
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
+
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
+ let locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
&resp,
@@ -314,14 +358,16 @@ pub async fn add_payment_method(
merchant_id,
&customer_id,
pm_metadata.cloned(),
+ locker_id,
)
.await?;
}
- };
+ }
Ok(services::ApplicationResponse::Json(resp))
}
+#[allow(clippy::too_many_arguments)]
pub async fn insert_payment_method(
db: &dyn db::StorageInterface,
resp: &api::PaymentMethodResponse,
@@ -330,7 +376,8 @@ pub async fn insert_payment_method(
merchant_id: &str,
customer_id: &str,
pm_metadata: Option<serde_json::Value>,
-) -> errors::RouterResult<()> {
+ locker_id: Option<String>,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
let pm_card_details = resp
.card
.as_ref()
@@ -341,14 +388,13 @@ pub async fn insert_payment_method(
&req,
customer_id,
&resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
key_store,
)
- .await?;
-
- Ok(())
+ .await
}
#[instrument(skip_all)]
@@ -372,7 +418,7 @@ pub async fn update_customer_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
};
@@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>(
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
@@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>(
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
})
@@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>(
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
@@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method(
(
card_details,
None,
- PaymentTokenData::permanent_card(pm.payment_method_id.clone()),
+ PaymentTokenData::permanent_card(
+ Some(pm.payment_method_id.clone()),
+ pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
+ pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
+ ),
)
} else {
continue;
@@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method(
&token,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?,
),
@@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3217,11 +3267,11 @@ pub async fn delete_payment_method(
&state,
&key.customer_id,
&key.merchant_id,
- pm_id.payment_method_id.as_str(),
+ key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
- if response.status == "SUCCESS" {
+ if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 57e46bc9769..6bad41630b5 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs(
}
}
-pub fn mk_add_card_response(
- card: api::CardDetail,
- response: AddCardResponse,
- req: api::PaymentMethodCreate,
- merchant_id: &str,
-) -> api::PaymentMethodResponse {
- let mut card_number = card.card_number.peek().to_owned();
- let card = api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card_number.split_off(card_number.len() - 4)),
- issuer_country: None, // [#256] bin mapping
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: Some(response.external_id.into()), // [#256]
- card_fingerprint: Some(response.card_fingerprint),
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_isin: None,
- card_issuer: None,
- card_network: None,
- card_type: None,
- saved_to_locker: true,
- };
- api::PaymentMethodResponse {
- merchant_id: merchant_id.to_owned(),
- customer_id: req.customer_id,
- payment_method_id: response.card_id,
- payment_method: req.payment_method,
- payment_method_type: req.payment_method_type,
- bank_transfer: None,
- card: Some(card),
- metadata: req.metadata,
- created: Some(common_utils::date_time::now()),
- recurring_enabled: false, // [#256]
- installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker
- payment_experience: None, // [#256]
- }
-}
-
pub fn mk_add_card_request(
locker: &settings::Locker,
card: &api::CardDetail,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2d7a09bdae1..d08f0208500 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -6,6 +6,7 @@ use router_env::{instrument, tracing};
use super::helpers;
use crate::{
+ consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate, payment_methods, payments,
@@ -19,7 +20,7 @@ use crate::{
domain,
storage::{self, enums as storage_enums},
},
- utils::OptionExt,
+ utils::{generate_id, OptionExt},
};
#[instrument(skip_all)]
@@ -85,7 +86,7 @@ where
.await?;
let merchant_id = &merchant_account.merchant_id;
- let locker_response = if !state.conf.locker.locker_enabled {
+ let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
payment_method_create_request.to_owned(),
@@ -100,9 +101,7 @@ where
.await?
};
- let duplication_check = locker_response.1;
-
- let pm_card_details = locker_response.0.card.as_ref().map(|card| {
+ let pm_card_details = resp.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
card.clone(),
))
@@ -115,13 +114,44 @@ where
)
.await;
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
- .await;
- match existing_pm {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
@@ -146,7 +176,8 @@ where
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -165,22 +196,87 @@ where
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(
+ &payment_method_id,
+ )
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ let existing_pm =
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }?;
+
payment_methods::cards::delete_card_from_locker(
state,
&customer.customer_id,
merchant_id,
- &locker_response.0.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = payment_methods::cards::add_card_hs(
state,
- payment_method_create_request.clone(),
+ payment_method_create_request,
&card,
customer.customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&locker_response.0.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -188,7 +284,7 @@ where
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
merchant_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
)
.await
.to_not_found_response(
@@ -201,90 +297,59 @@ where
))?
};
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
+ let updated_card = Some(CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
+ card.clone(),
+ ))
+ });
+ let pm_data_encrypted =
+ payment_methods::cards::create_encrypted_payment_method_data(
+ key_store,
+ updated_pmd,
+ )
.await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(
- card.card_number.clone().get_last4(),
- ),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card.clone()),
- )
- });
- let pm_data_encrypted =
- payment_methods::cards::create_encrypted_payment_method_data(
- key_store,
- updated_pmd,
- )
- .await;
- let pm_update =
- storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
+ let pm_update =
+ storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Failed to add payment method in db",
- )?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &locker_response.0,
- payment_method_create_request,
- key_store,
- merchant_id,
- &customer.customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Error while finding payment method",
- )
- }?;
- }
- }
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
+
+ locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -294,7 +359,7 @@ where
}
}
- Some(locker_response.0.payment_method_id)
+ Some(resp.payment_method_id)
} else {
None
};
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7fb6fa3bde6..de57f8549db 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>(
.attach_printable("failed to deserialize hyperswitch token data")?;
let payment_token = match payment_token_data {
- storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => {
- Some(token)
- }
+ storage::PaymentTokenData::PermanentCard(storage::CardTokenData {
+ locker_id,
+ token,
+ ..
+ }) => locker_id.or(Some(token)),
storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData {
token,
}) => Some(token),
@@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker(
card_network: None,
};
+ let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
cards::create_payment_method(
db,
&payment_method,
&payout_attempt.customer_id,
- &stored_resp.card_reference,
+ &payment_method_id,
+ Some(stored_resp.card_reference),
&merchant_account.merchant_id,
None,
card_details_encrypted,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 78b95544ca1..9dbecd82485 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_locker_id(locker_id)
+ .await
+ }
+
async fn insert_payment_method(
&self,
m: storage::PaymentMethodNew,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index b109d1fe5bd..4f4087f552e 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -15,6 +15,11 @@ pub trait PaymentMethodInterface {
payment_method_id: &str,
) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &str,
@@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::find_by_locker_id(&conn, locker_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.locker_id == Some(locker_id.to_string()))
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: payment_method_new.customer_id,
merchant_id: payment_method_new.merchant_id,
payment_method_id: payment_method_new.payment_method_id,
+ locker_id: payment_method_new.locker_id,
accepted_currency: payment_method_new.accepted_currency,
scheme: payment_method_new.scheme,
token: payment_method_new.token,
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 051547dfa92..10c56973dd3 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse {
state,
&payment_method.customer_id,
&payment_method.merchant_id,
- &payment_method.payment_method_id,
+ payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(&payment_method.payment_method_id),
)
.await?;
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 096303446dc..a787a4d932c 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -13,6 +13,8 @@ pub enum PaymentTokenKind {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
+ pub payment_method_id: Option<String>,
+ pub locker_id: Option<String>,
pub token: String,
}
@@ -34,8 +36,16 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
- pub fn permanent_card(token: String) -> Self {
- Self::PermanentCard(CardTokenData { token })
+ pub fn permanent_card(
+ payment_method_id: Option<String>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
}
pub fn temporary_generic(token: String) -> Self {
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
new file mode 100644
index 00000000000..90eaebaf4da
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id;
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
new file mode 100644
index 00000000000..516dc8a8818
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
| 2024-02-21T17:18:08Z |
## Description
<!-- Describe your changes in detail -->
Currently we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 75c633fc7c37341177597041ccbcdfc3cf9e236f |
Sandbox testing -
* Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146
* Test it for both old card already saved before this PR went in along with new card
* Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine
Test cases (`payment_methods` table) -
(Card 1): Db entry before this code changes :- `locker_id` should be null

(Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

(Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id

(Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

Redis entry (Local testing) -
Old card (both locker_id and payment_method_id will be same):

New card (payment_method_id will be nano_id and locker_id will be the id returned from locker):

| [
"crates/diesel_models/src/payment_method.rs",
"crates/diesel_models/src/query/payment_method.rs",
"crates/diesel_models/src/schema.rs",
"crates/router/src/core/customers.rs",
"crates/router/src/core/locker_migration.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payment_method... | |
juspay/hyperswitch | juspay__hyperswitch-3778 | Bug: [FEATURE] : [Braintree] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index 436cd8dfa36..190cd276572 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -54,7 +54,7 @@ impl<T>
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInput {
- payment_method_id: String,
+ payment_method_id: Secret<String>,
transaction: TransactionBody,
}
@@ -899,7 +899,7 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct TokenizePaymentMethodData {
- id: String,
+ id: Secret<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -969,6 +969,7 @@ impl<F, T>
.tokenize_credit_card
.payment_method
.id
+ .expose()
.clone(),
})
}
@@ -1277,7 +1278,7 @@ impl<F, T>
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeThreeDsResponse {
- pub nonce: String,
+ pub nonce: Secret<String>,
pub liability_shifted: bool,
pub liability_shift_possible: bool,
}
@@ -1332,7 +1333,7 @@ impl
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token,
+ types::PaymentMethodToken::Token(token) => token.into(),
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 8846753117c..9201bc9e4cc 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -1,6 +1,6 @@
use api_models::payments;
use base64::Engine;
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
@@ -77,7 +77,7 @@ pub enum PaymentMethodType {
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct Nonce {
- payment_method_nonce: String,
+ payment_method_nonce: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -130,7 +130,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest {
Ok(wallet_data.token.to_owned())
}
_ => Err(errors::ConnectorError::InvalidWallet),
- }?,
+ }?
+ .into(),
}))
}
_ => Err(errors::ConnectorError::NotImplemented(format!(
@@ -263,7 +264,7 @@ impl<F, T>
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: types::api::SessionToken::Paypal(Box::new(
payments::PaypalSessionTokenResponse {
- session_token: item.response.client_token.value,
+ session_token: item.response.client_token.value.expose(),
},
)),
}),
@@ -281,7 +282,7 @@ pub struct BraintreePaymentsResponse {
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientToken {
- pub value: String,
+ pub value: Secret<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
| 2024-02-21T15:12:03Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Braintree.
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for Braintree
Test for both graphQL and the normal version
Sanity test
1. Payment create - 3ds card
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
response
```
ClientTokenResponse(ClientTokenResponse { data: ClientTokenData { create_client_token: ClientToken { client_token: *** alloc::string::String *** } } })
```
```
router::connector::braintree: connector_response: TokenResponse(TokenResponse { data: TokenizeCreditCard { tokenize_credit_card: TokenizeCreditCardData { payment_method: TokenizePaymentMethodData { id: *** alloc::string::String *** } } } })
```
In logs check for
`topic = "hyperswitch-outgoing-connector-events" ` | ef5e886ab1abdf50254343be8c6c48100ec2ec2d | [
"crates/router/src/connector/braintree/braintree_graphql_transformers.rs",
"crates/router/src/connector/braintree/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3610 | Bug: [FEATURE] Update Payment Connector Create to incorporate recipient creation
### Feature Description
In Open banking payments, some connector offer a recipient creation flow, where a `recipient_id` can be created against merchant's bank account data. The `recipient_id` can be stored in the DB.
Alternatively, for the connectors that don't offer this flow, we can offer to store the data in locker.
### Possible Implementation
A recipient creation API call would have to be incorporated in the payment connector create flow, some type changes would be required a as well.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/config.example.toml b/config/config.example.toml
index 9b855b1e956..5b4c1bbd762 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -698,3 +698,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p
[user_auth_methods]
encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table
+
+[locker_based_open_banking_connectors]
+connector_list = ""
\ No newline at end of file
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index b8945db5f24..060756cf910 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -347,3 +347,6 @@ keys = "user-agent"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
+
+[locker_based_open_banking_connectors]
+connector_list = ""
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index acc28a32c5f..ce7e6df9897 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -366,3 +366,6 @@ keys = "user-agent"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
+
+[locker_based_open_banking_connectors]
+connector_list = ""
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index d776483ebcc..4920ca8589e 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -370,3 +370,6 @@ keys = "user-agent"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
+
+[locker_based_open_banking_connectors]
+connector_list = ""
diff --git a/config/development.toml b/config/development.toml
index c35de87e808..2b7cc68e8b5 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -695,3 +695,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p
[user_auth_methods]
encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F"
+
+[locker_based_open_banking_connectors]
+connector_list = ""
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index c26055f436a..18a3189e4fd 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -351,7 +351,7 @@ sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" }
open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" }
[pm_filters.razorpay]
-upi_collect = {country = "IN", currency = "INR"}
+upi_collect = { country = "IN", currency = "INR" }
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -442,7 +442,7 @@ delay_between_retries_in_milliseconds = 500
[events.kafka]
brokers = ["localhost:9092"]
-fraud_check_analytics_topic= "hyperswitch-fraud-check-events"
+fraud_check_analytics_topic = "hyperswitch-fraud-check-events"
intent_analytics_topic = "hyperswitch-payment-intent-events"
attempt_analytics_topic = "hyperswitch-payment-attempt-events"
refund_analytics_topic = "hyperswitch-refund-events"
@@ -519,7 +519,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 = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
[user_auth_methods]
encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F"
@@ -548,7 +548,10 @@ merchant_name = "HyperSwitch"
card = "credit,debit"
[payout_method_filters.adyenplatform]
-sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOR,PLN,SEK,GBP,CHF" }
+sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH", currency = "EUR,CZK,DKK,HUF,NOR,PLN,SEK,GBP,CHF" }
[payout_method_filters.stripe]
ach = { country = "US", currency = "USD" }
+
+[locker_based_open_banking_connectors]
+connector_list = ""
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index ec9172b7fdf..20129e4b239 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -652,6 +652,49 @@ pub struct MerchantConnectorCreate {
#[schema(value_type = Option<ConnectorStatus>, example = "inactive")]
pub status: Option<api_enums::ConnectorStatus>,
+
+ /// In case the merchant needs to store any additional sensitive data
+ #[schema(value_type = Option<AdditionalMerchantData>)]
+ pub additional_merchant_data: Option<AdditionalMerchantData>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum AdditionalMerchantData {
+ OpenBankingRecipientData(MerchantRecipientData),
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantAccountData {
+ Iban {
+ #[schema(value_type= String)]
+ iban: Secret<String>,
+ name: String,
+ #[schema(value_type= Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+ Bacs {
+ #[schema(value_type= String)]
+ account_number: Secret<String>,
+ #[schema(value_type= String)]
+ sort_code: Secret<String>,
+ name: String,
+ #[schema(value_type= Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantRecipientData {
+ #[schema(value_type= Option<String>)]
+ ConnectorRecipientId(Secret<String>),
+ #[schema(value_type= Option<String>)]
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
}
// Different patterns of authentication.
@@ -805,6 +848,9 @@ pub struct MerchantConnectorResponse {
#[schema(value_type = ConnectorStatus, example = "inactive")]
pub status: api_enums::ConnectorStatus,
+
+ #[schema(value_type = Option<AdditionalMerchantData>)]
+ pub additional_merchant_data: Option<AdditionalMerchantData>,
}
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 87d4f5e775a..ca37332cb76 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -176,6 +176,7 @@ pub enum RoutableConnectors {
Worldline,
Worldpay,
Zen,
+ Plaid,
Zsl,
}
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index 680e3dacc85..e01c465d1b4 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -43,6 +43,7 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
}
@@ -73,6 +74,7 @@ pub struct MerchantConnectorAccountNew {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8d51e378fd9..d9f5b299862 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -707,6 +707,7 @@ diesel::table! {
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
+ additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
}
}
diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs
index 820e3da42d8..a137a6fd54d 100644
--- a/crates/kgraph_utils/benches/evaluation.rs
+++ b/crates/kgraph_utils/benches/evaluation.rs
@@ -71,6 +71,7 @@ fn build_test_data(
applepay_verified_domains: None,
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
+ additional_merchant_data: None,
};
let config = CountryCurrencyFilter {
connector_configs: HashMap::new(),
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index 74cc096e730..0cbf171495b 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -759,6 +759,7 @@ mod tests {
applepay_verified_domains: None,
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
+ additional_merchant_data: None,
};
let config_map = kgraph_types::CountryCurrencyFilter {
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 82bde980a1f..d2e669175eb 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -256,6 +256,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::AuthorizationStatus,
api_models::enums::PaymentMethodStatus,
api_models::admin::MerchantConnectorCreate,
+ api_models::admin::AdditionalMerchantData,
+ api_models::admin::MerchantRecipientData,
+ api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs
index dfcfbb7eddc..6f91b2cb1a2 100644
--- a/crates/pm_auth/src/connector/plaid.rs
+++ b/crates/pm_auth/src/connector/plaid.rs
@@ -15,7 +15,9 @@ use crate::{
types::{
self as auth_types,
api::{
- auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken},
+ auth_service::{
+ self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
+ },
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
@@ -89,6 +91,8 @@ impl ConnectorCommon for Plaid {
}
impl auth_service::AuthService for Plaid {}
+impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
+impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
@@ -338,3 +342,91 @@ impl
self.build_error_response(res)
}
}
+
+impl
+ ConnectorIntegration<
+ RecipientCreate,
+ auth_types::RecipientCreateRequest,
+ auth_types::RecipientCreateResponse,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::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_url(
+ &self,
+ _req: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "/payment_initiation/recipient/create"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ ) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
+ let req_obj = plaid::PlaidRecipientCreateRequest::from(req);
+ Ok(RequestContent::Json(Box::new(req_obj)))
+ }
+
+ fn build_request(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(
+ auth_types::PaymentInitiationRecipientCreateType::get_headers(
+ self, req, connectors,
+ )?,
+ )
+ .set_body(
+ auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
+ )
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &auth_types::RecipientCreateRouterData,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidRecipientCreateResponse = res
+ .response
+ .parse_struct("PlaidRecipientCreateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ Ok(<auth_types::RecipientCreateRouterData>::from(
+ auth_types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ ))
+ }
+ fn get_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
index 8ce5aca7b83..571f27f5b20 100644
--- a/crates/pm_auth/src/connector/plaid/transformers.rs
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -113,6 +113,103 @@ impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
}
}
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateRequest {
+ pub name: String,
+ #[serde(flatten)]
+ pub account_data: PlaidRecipientAccountData,
+ pub address: Option<PlaidRecipientCreateAddress>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateResponse {
+ pub recipient_id: String,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum PlaidRecipientAccountData {
+ Iban(Secret<String>),
+ Bacs {
+ sort_code: Secret<String>,
+ account: Secret<String>,
+ },
+}
+
+impl From<&types::RecipientAccountData> for PlaidRecipientAccountData {
+ fn from(item: &types::RecipientAccountData) -> Self {
+ match item {
+ types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()),
+ types::RecipientAccountData::Bacs {
+ sort_code,
+ account_number,
+ } => Self::Bacs {
+ sort_code: sort_code.clone(),
+ account: account_number.clone(),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateAddress {
+ pub street: String,
+ pub city: String,
+ pub postal_code: String,
+ pub country: String,
+}
+
+impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
+ fn from(item: &types::RecipientCreateAddress) -> Self {
+ Self {
+ street: item.street.clone(),
+ city: item.city.clone(),
+ postal_code: item.postal_code.clone(),
+ country: common_enums::CountryAlpha2::to_string(&item.country),
+ }
+ }
+}
+
+impl From<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
+ fn from(item: &types::RecipientCreateRouterData) -> Self {
+ Self {
+ name: item.request.name.clone(),
+ account_data: PlaidRecipientAccountData::from(&item.request.account_data),
+ address: item
+ .request
+ .address
+ .as_ref()
+ .map(PlaidRecipientCreateAddress::from),
+ }
+ }
+}
+
+impl<F, T>
+ From<
+ types::ResponseRouterData<
+ F,
+ PlaidRecipientCreateResponse,
+ T,
+ types::RecipientCreateResponse,
+ >,
+ > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse>
+{
+ fn from(
+ item: types::ResponseRouterData<
+ F,
+ PlaidRecipientCreateResponse,
+ T,
+ types::RecipientCreateResponse,
+ >,
+ ) -> Self {
+ Self {
+ response: Ok(types::RecipientCreateResponse {
+ recipient_id: item.response.recipient_id,
+ }),
+ ..item.data
+ }
+ }
+}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidBankAccountCredentialsRequest {
@@ -351,6 +448,7 @@ impl<F, T>
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
+ pub merchant_data: Option<types::MerchantRecipientData>,
}
impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
@@ -360,6 +458,16 @@ impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
client_id: client_id.to_owned(),
secret: secret.to_owned(),
+ merchant_data: None,
+ }),
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Ok(Self {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ merchant_data: Some(merchant_data.clone()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index 2537cdc6a36..7450251f157 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -2,10 +2,11 @@ pub mod api;
use std::marker::PhantomData;
-use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken};
-use common_enums::{PaymentMethod, PaymentMethodType};
+use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate};
+use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types};
use masking::Secret;
+
#[derive(Debug, Clone)]
pub struct PaymentAuthRouterData<F, Request, Response> {
pub flow: PhantomData<F>,
@@ -111,6 +112,38 @@ pub type BankDetailsRouterData = PaymentAuthRouterData<
BankAccountCredentialsResponse,
>;
+#[derive(Debug, Clone)]
+pub struct RecipientCreateRequest {
+ pub name: String,
+ pub account_data: RecipientAccountData,
+ pub address: Option<RecipientCreateAddress>,
+}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreateResponse {
+ pub recipient_id: String,
+}
+
+#[derive(Debug, Clone)]
+pub enum RecipientAccountData {
+ Iban(Secret<String>),
+ Bacs {
+ sort_code: Secret<String>,
+ account_number: Secret<String>,
+ },
+}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreateAddress {
+ pub street: String,
+ pub city: String,
+ pub postal_code: String,
+ pub country: CountryAlpha2,
+}
+
+pub type RecipientCreateRouterData =
+ PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
+
pub type PaymentAuthLinkTokenType =
dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
@@ -123,6 +156,9 @@ pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration<
BankAccountCredentialsResponse,
>;
+pub type PaymentInitiationRecipientCreateType =
+ dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
+
#[derive(Clone, Debug, strum::EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodAuthConnectors {
@@ -155,12 +191,38 @@ impl ErrorResponse {
}
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub enum MerchantAccountData {
+ Iban {
+ iban: Secret<String>,
+ name: String,
+ },
+ Bacs {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ },
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantRecipientData {
+ ConnectorRecipientId(Secret<String>),
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
+}
+
#[derive(Default, Debug, Clone, serde::Deserialize)]
pub enum ConnectorAuthType {
BodyKey {
client_id: Secret<String>,
secret: Secret<String>,
},
+ OpenBankingAuth {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ merchant_data: MerchantRecipientData,
+ },
#[default]
NoKey,
}
diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs
index 3684e34ec05..d4edf160985 100644
--- a/crates/pm_auth/src/types/api.rs
+++ b/crates/pm_auth/src/types/api.rs
@@ -10,7 +10,10 @@ use masking::Maskable;
use crate::{
core::errors::ConnectorError,
- types::{self as auth_types, api::auth_service::AuthService},
+ types::{
+ self as auth_types,
+ api::auth_service::{AuthService, PaymentInitiation},
+ },
};
#[async_trait::async_trait]
@@ -125,9 +128,9 @@ where
}
}
-pub trait AuthServiceConnector: AuthService + Send + Debug {}
+pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {}
-impl<T: Send + Debug + AuthService> AuthServiceConnector for T {}
+impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {}
pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>;
diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs
index 35d44970d51..498b6bec40e 100644
--- a/crates/pm_auth/src/types/api/auth_service.rs
+++ b/crates/pm_auth/src/types/api/auth_service.rs
@@ -1,6 +1,7 @@
use crate::types::{
BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
- ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse,
+ ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest,
+ RecipientCreateResponse,
};
pub trait AuthService:
@@ -11,6 +12,8 @@ pub trait AuthService:
{
}
+pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {}
+
#[derive(Debug, Clone)]
pub struct LinkToken;
@@ -38,3 +41,11 @@ pub trait AuthServiceBankAccountCredentials:
>
{
}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreate;
+
+pub trait PaymentInitiationRecipientCreate:
+ super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>
+{
+}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 9f6c797cde8..de53f9c189e 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -434,5 +434,6 @@ pub(crate) async fn fetch_raw_secrets(
multitenancy: conf.multitenancy,
user_auth_methods,
decision: conf.decision,
+ locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index b96784eb714..26685d63583 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 saved_payment_methods: EligiblePaymentMethods,
pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>,
pub decision: Option<DecisionConfig>,
+ pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -690,6 +691,13 @@ pub struct ApplePayDecryptConifg {
pub apple_pay_merchant_cert_key: Secret<String>,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct LockerBasedRecipientConnectorList {
+ #[serde(deserialize_with = "deserialize_hashset")]
+ pub connector_list: HashSet<String>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorRequestReferenceIdConfig {
pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 67b3a05adb7..88f11fdfce8 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -7,7 +7,7 @@ use api_models::{
use common_utils::{
date_time,
ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt},
- pii,
+ id_type, pii,
};
#[cfg(all(feature = "keymanager_create", feature = "olap"))]
use common_utils::{keymanager, types::keymanager as km_types};
@@ -15,24 +15,25 @@ use diesel_models::configs;
use error_stack::{report, FutureExt, ResultExt};
use futures::future::try_join_all;
use masking::{PeekInterface, Secret};
-use pm_auth::connector::plaid::transformers::PlaidAuthType;
+use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types};
+use regex::Regex;
use router_env::metrics::add_attributes;
use uuid::Uuid;
-#[cfg(all(not(feature = "v2"), feature = "olap"))]
-use crate::types::transformers::ForeignFrom;
use crate::{
consts,
core::{
encryption::transfer_encryption_key,
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
+ payment_methods::{cards, transformers},
payments::helpers,
+ pm_auth::helpers::PaymentAuthConnectorDataExt,
routing::helpers as routing_helpers,
utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
- services::{self, api as service_api, authentication},
+ services::{self, api as service_api, authentication, pm_auth as payment_initiation_service},
types::{
self, api,
domain::{
@@ -40,11 +41,15 @@ use crate::{
types::{self as domain_types, AsyncLift},
},
storage::{self, enums::MerchantStorageScheme},
- transformers::ForeignTryFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
+const IBAN_MAX_LENGTH: usize = 34;
+const BACS_SORT_CODE_LENGTH: usize = 6;
+const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
+
#[inline]
pub fn create_merchant_publishable_key() -> String {
format!(
@@ -1107,7 +1112,9 @@ pub async fn create_payment_connector(
api_enums::convert_authentication_connector(req.connector_name.to_string().as_str());
if pm_auth_connector.is_some() {
- if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
+ if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth
+ && req.connector_type != api_enums::ConnectorType::PaymentProcessor
+ {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
@@ -1172,6 +1179,30 @@ pub async fn create_payment_connector(
expected_format: "auth_type and api_key".to_string(),
})?;
+ let merchant_recipient_data = if let Some(data) = &req.additional_merchant_data {
+ Some(
+ process_open_banking_connectors(
+ &state,
+ merchant_id.as_str(),
+ &auth,
+ &req.connector_type,
+ &req.connector_name,
+ types::AdditionalMerchantData::foreign_from(data.clone()),
+ )
+ .await?,
+ )
+ } else {
+ None
+ }
+ .map(|data| {
+ serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
+ data,
+ ))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get MerchantRecipientData")?;
+
validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata)?;
let frm_configs = get_frm_config_as_secret(req.frm_configs);
@@ -1192,7 +1223,7 @@ pub async fn create_payment_connector(
let (connector_status, disabled) = validate_status_and_disabled(
req.status,
req.disabled,
- auth,
+ auth.clone(),
// The validate_status_and_disabled function will use this value only
// when the status can be active. So we are passing this as fallback.
api_enums::ConnectorStatus::Active,
@@ -1212,17 +1243,18 @@ pub async fn create_payment_connector(
}
}
+ let connector_auth = serde_json::to_value(auth)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encoding ConnectorAuthType to serde_json::Value")?;
+ let conn_auth = Secret::new(connector_auth);
+
let merchant_connector_account = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_string(),
connector_type: req.connector_type,
connector_name: req.connector_name.to_string(),
merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"),
connector_account_details: domain_types::encrypt(
- req.connector_account_details.ok_or(
- errors::ApiErrorResponse::MissingRequiredField {
- field_name: "connector_account_details",
- },
- )?,
+ conn_auth,
key_store.key.peek(),
)
.await
@@ -1256,6 +1288,17 @@ pub async fn create_payment_connector(
pm_auth_config: req.pm_auth_config.clone(),
status: connector_status,
connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?,
+ additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
+ Some(domain_types::encrypt(
+ Secret::new(mcd),
+ key_store.key.peek(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt additional_merchant_data")?)
+ } else {
+ None
+ },
};
let transaction_type = match req.connector_type {
@@ -2577,3 +2620,285 @@ pub fn validate_status_and_disabled(
Ok((connector_status, disabled))
}
+
+async fn process_open_banking_connectors(
+ state: &SessionState,
+ merchant_id: &str,
+ auth: &types::ConnectorAuthType,
+ connector_type: &api_enums::ConnectorType,
+ connector: &api_enums::Connector,
+ additional_merchant_data: types::AdditionalMerchantData,
+) -> RouterResult<types::MerchantRecipientData> {
+ let new_merchant_data = match additional_merchant_data {
+ types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => {
+ if connector_type != &api_enums::ConnectorType::PaymentProcessor {
+ return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
+ config:
+ "OpenBanking connector for Payment Initiation should be a payment processor"
+ .to_string(),
+ }
+ .into());
+ }
+ match &merchant_data {
+ types::MerchantRecipientData::AccountData(acc_data) => {
+ validate_bank_account_data(acc_data)?;
+
+ let connector_name = api_enums::Connector::to_string(connector);
+
+ let recipient_creation_not_supported = state
+ .conf
+ .locker_based_open_banking_connectors
+ .connector_list
+ .contains(connector_name.as_str());
+
+ let recipient_id = if recipient_creation_not_supported {
+ locker_recipient_create_call(state, merchant_id, acc_data).await
+ } else {
+ connector_recipient_create_call(
+ state,
+ merchant_id,
+ connector_name,
+ auth,
+ acc_data,
+ )
+ .await
+ }
+ .attach_printable("failed to get recipient_id")?;
+
+ let conn_recipient_id = if recipient_creation_not_supported {
+ Some(types::RecipientIdType::LockerId(Secret::new(recipient_id)))
+ } else {
+ Some(types::RecipientIdType::ConnectorId(Secret::new(
+ recipient_id,
+ )))
+ };
+
+ let account_data = match &acc_data {
+ types::MerchantAccountData::Iban { iban, name, .. } => {
+ types::MerchantAccountData::Iban {
+ iban: iban.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ }
+ }
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => types::MerchantAccountData::Bacs {
+ account_number: account_number.clone(),
+ sort_code: sort_code.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ },
+ };
+
+ types::MerchantRecipientData::AccountData(account_data)
+ }
+ _ => merchant_data.clone(),
+ }
+ }
+ };
+
+ Ok(new_merchant_data)
+}
+
+fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
+ match data {
+ types::MerchantAccountData::Iban { iban, .. } => {
+ // IBAN check algorithm
+ if iban.peek().len() > IBAN_MAX_LENGTH {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN length must be up to 34 characters".to_string(),
+ }
+ .into());
+ }
+ let pattern = Regex::new(r"^[A-Z0-9]*$")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to create regex pattern")?;
+
+ let mut iban = iban.peek().to_string();
+
+ if !pattern.is_match(iban.as_str()) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN data must be alphanumeric".to_string(),
+ }
+ .into());
+ }
+
+ // MOD check
+ let first_4 = iban.chars().take(4).collect::<String>();
+ iban.push_str(first_4.as_str());
+ let len = iban.len();
+
+ let rearranged_iban = iban
+ .chars()
+ .rev()
+ .take(len - 4)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>();
+
+ let mut result = String::new();
+
+ rearranged_iban.chars().for_each(|c| {
+ if c.is_ascii_uppercase() {
+ let digit = (u32::from(c) - u32::from('A')) + 10;
+ result.push_str(&format!("{:02}", digit));
+ } else {
+ result.push(c);
+ }
+ });
+
+ let num = result
+ .parse::<u128>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to validate IBAN")?;
+
+ if num % 97 != 1 {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid IBAN".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+ }
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ ..
+ } => {
+ if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH
+ || sort_code.peek().len() != BACS_SORT_CODE_LENGTH
+ {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid BACS numbers".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+ }
+ }
+}
+
+async fn connector_recipient_create_call(
+ state: &SessionState,
+ merchant_id: &str,
+ connector_name: String,
+ auth: &types::ConnectorAuthType,
+ data: &types::MerchantAccountData,
+) -> RouterResult<String> {
+ let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
+ connector_name.as_str(),
+ )?;
+
+ let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while converting ConnectorAuthType")?;
+
+ let connector_integration: pm_auth_types::api::BoxedConnectorIntegration<
+ '_,
+ pm_auth_types::api::auth_service::RecipientCreate,
+ pm_auth_types::RecipientCreateRequest,
+ pm_auth_types::RecipientCreateResponse,
+ > = connector.connector.get_connector_integration();
+
+ let req = match data {
+ types::MerchantAccountData::Iban { iban, name, .. } => {
+ pm_auth_types::RecipientCreateRequest {
+ name: name.clone(),
+ account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()),
+ address: None,
+ }
+ }
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => pm_auth_types::RecipientCreateRequest {
+ name: name.clone(),
+ account_data: pm_auth_types::RecipientAccountData::Bacs {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ },
+ address: None,
+ },
+ };
+
+ let router_data = pm_auth_types::RecipientCreateRouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: Some(merchant_id.to_owned()),
+ connector: Some(connector_name),
+ request: req,
+ response: Err(pm_auth_types::ErrorResponse {
+ status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
+ reason: None,
+ }),
+ connector_http_status_code: None,
+ connector_auth_type: auth,
+ };
+
+ let resp = payment_initiation_service::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ &connector.connector_name,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling recipient create connector api")?;
+
+ let recipient_create_resp =
+ resp.response
+ .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: connector.connector_name.to_string(),
+ status_code: err.status_code,
+ reason: err.reason,
+ })?;
+
+ let recipient_id = recipient_create_resp.recipient_id;
+
+ Ok(recipient_id)
+}
+
+async fn locker_recipient_create_call(
+ state: &SessionState,
+ merchant_id: &str,
+ data: &types::MerchantAccountData,
+) -> RouterResult<String> {
+ let enc_data = serde_json::to_string(data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert to MerchantAccountData json to String")?;
+
+ let cust_id = id_type::CustomerId::from(merchant_id.to_string().into())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert to CustomerId")?;
+
+ let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq {
+ merchant_id,
+ merchant_customer_id: cust_id.clone(),
+ enc_data,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ });
+
+ let store_resp = cards::call_to_locker_hs(
+ state,
+ &payload,
+ &cust_id,
+ api_enums::LockerChoice::HyperswitchCardVault,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt merchant bank account data")?;
+
+ Ok(store_resp.card_reference)
+}
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index d3393b5b1f7..6eea962b9e5 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -209,6 +209,7 @@ impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType {
Ok::<Self, errors::ConnectorError>(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
+ merchant_data: None,
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs
index 8a1369c2e02..d516cab62fe 100644
--- a/crates/router/src/core/pm_auth/transformers.rs
+++ b/crates/router/src/core/pm_auth/transformers.rs
@@ -2,6 +2,36 @@ use pm_auth::types::{self as pm_auth_types};
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
+impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData {
+ fn from(from: types::MerchantAccountData) -> Self {
+ match from {
+ types::MerchantAccountData::Iban { iban, name, .. } => Self::Iban { iban, name },
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ },
+ }
+ }
+}
+
+impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData {
+ fn from(value: types::MerchantRecipientData) -> Self {
+ match value {
+ types::MerchantRecipientData::ConnectorRecipientId(id) => {
+ Self::ConnectorRecipientId(id)
+ }
+ types::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()),
+ }
+ }
+}
+
impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType {
type Error = errors::ConnectorError;
fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> {
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index a176db26549..567d16ee269 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -440,7 +440,7 @@ impl MerchantConnectorAccountInterface for Store {
#[cfg(feature = "accounts_cache")]
// Redact all caches as any of might be used because of backwards compatibility
- cache::publish_and_redact_multiple(
+ Box::pin(cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
@@ -454,7 +454,7 @@ impl MerchantConnectorAccountInterface for Store {
),
],
|| update,
- )
+ ))
.await
.map_err(|error| {
// Returning `DatabaseConnectionError` after logging the actual error because
@@ -784,6 +784,7 @@ impl MerchantConnectorAccountInterface for MockDb {
pm_auth_config: t.pm_auth_config,
status: t.status,
connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
};
accounts.push(account.clone());
account
@@ -991,6 +992,7 @@ mod merchant_connector_account_cache_tests {
.await
.unwrap(),
),
+ additional_merchant_data: None,
};
db.insert_merchant_connector_account(mca.clone(), &merchant_key)
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index c457ca59df8..cc735612ac3 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -12,7 +12,7 @@ pub mod domain;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod pm_auth;
-
+use masking::Secret;
pub mod storage;
pub mod transformers;
use std::marker::PhantomData;
@@ -606,6 +606,150 @@ pub struct ResponseRouterData<Flow, R, Request, Response> {
pub http_code: u16,
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub enum RecipientIdType {
+ ConnectorId(Secret<String>),
+ LockerId(Secret<String>),
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantAccountData {
+ Iban {
+ iban: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ Bacs {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+}
+
+impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData {
+ fn foreign_from(from: MerchantAccountData) -> Self {
+ match from {
+ MerchantAccountData::Iban {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Iban {
+ iban,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id,
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ }
+ }
+}
+
+impl From<api_models::admin::MerchantAccountData> for MerchantAccountData {
+ fn from(from: api_models::admin::MerchantAccountData) -> Self {
+ match from {
+ api_models::admin::MerchantAccountData::Iban {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Iban {
+ iban,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id,
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantRecipientData {
+ ConnectorRecipientId(Secret<String>),
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
+}
+
+impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData {
+ fn foreign_from(value: MerchantRecipientData) -> Self {
+ match value {
+ MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id),
+ MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ MerchantRecipientData::AccountData(data) => {
+ Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data))
+ }
+ }
+ }
+}
+
+impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData {
+ fn from(value: api_models::admin::MerchantRecipientData) -> Self {
+ match value {
+ api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
+ Self::ConnectorRecipientId(id)
+ }
+ api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ api_models::admin::MerchantRecipientData::AccountData(data) => {
+ Self::AccountData(data.into())
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AdditionalMerchantData {
+ OpenBankingRecipientData(MerchantRecipientData),
+}
+
+impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData {
+ fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self {
+ match value {
+ api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => {
+ Self::OpenBankingRecipientData(MerchantRecipientData::from(data))
+ }
+ }
+ }
+}
+
+impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData {
+ fn foreign_from(value: AdditionalMerchantData) -> Self {
+ match value {
+ AdditionalMerchantData::OpenBankingRecipientData(data) => {
+ Self::OpenBankingRecipientData(
+ api_models::admin::MerchantRecipientData::foreign_from(data),
+ )
+ }
+ }
+ }
+}
+
impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self {
match value {
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index 6c2f6a06e1e..2cf091eda12 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -40,6 +40,7 @@ pub struct MerchantConnectorAccount {
pub pm_auth_config: Option<serde_json::Value>,
pub status: enums::ConnectorStatus,
pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ pub additional_merchant_data: Option<Encryptable<Secret<serde_json::Value>>>,
}
#[derive(Debug)]
@@ -101,6 +102,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
},
)
}
@@ -148,6 +150,17 @@ impl behaviour::Conversion for MerchantConnectorAccount {
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector wallets details".to_string(),
})?,
+ additional_merchant_data: if let Some(data) = other.additional_merchant_data {
+ Some(
+ Encryptable::decrypt(data, key.peek(), GcmAes256)
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting additional_merchant_data".to_string(),
+ })?,
+ )
+ } else {
+ None
+ },
})
}
@@ -177,6 +190,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
+ additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
})
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index b06599769f4..d1f01ac8ef7 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -26,6 +26,7 @@ use crate::{
},
services::authentication::get_header_value_by_key,
types::{
+ self as router_types,
api::{self as api_types, routing as routing_types},
storage,
},
@@ -977,6 +978,19 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo
applepay_verified_domains: item.applepay_verified_domains,
pm_auth_config: item.pm_auth_config,
status: item.status,
+ additional_merchant_data: item
+ .additional_merchant_data
+ .map(|data| {
+ let data = data.into_inner();
+ serde_json::Value::parse_value::<router_types::AdditionalMerchantData>(
+ data.expose(),
+ "AdditionalMerchantData",
+ )
+ .attach_printable("Unable to deserialize additional_merchant_data")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ })
+ .transpose()?
+ .map(api_models::admin::AdditionalMerchantData::foreign_from),
})
}
}
diff --git a/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql b/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql
new file mode 100644
index 00000000000..7614b52872d
--- /dev/null
+++ b/migrations/2024-04-12-100925_mca_additional_merchant_data/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS additional_merchant_data;
\ No newline at end of file
diff --git a/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql b/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql
new file mode 100644
index 00000000000..4b48796785e
--- /dev/null
+++ b/migrations/2024-04-12-100925_mca_additional_merchant_data/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS additional_merchant_data BYTEA DEFAULT NULL;
\ No newline at end of file
| 2024-02-21T14:45:22Z |
## Description
<!-- Describe your changes in detail -->
- Added connector call in payment connector create to facilitate merchant recipient creation at connector end.
- Added alternative locker call for creation of recipient at Hyperswitch's end in case the connector does not support it.
- Added validation for merchant bank account data
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 43741df4a76a66faa472dacd66b396232a2fbdbf |
1. Create an MCA account with `connector_type` as `payment_processor` and an open banking connector
```
curl --location --request POST 'http://localhost:8080/account/merchant_1720607250/connectors' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data-raw '{
"connector_type": "payment_processor",
"connector_name": "plaid",
"connector_label": "plaid3",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "Some_key",
"key1": "Some_key"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
}
},
{
"payment_method_type": "giropay",
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
}
},
{
"payment_method_type": "ideal",
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
}
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_currencies": {
"type": "enable_only",
"list": [
"USD",
"GBP",
"CAD",
"AUD",
"EUR"
]
}
}
]
}
],
"additional_merchant_data": {
"open_banking_recipient_data": {
"account_data": {
"bacs": {
"sort_code": "200000",
"account_number": "55779911",
"name": "merchant_name"
}
}
}
},
"metadata": {
"city": "NY",
"unit": "246"
}
}'
```
Successful Response should look like this -
```
{
"connector_type": "payment_processor",
"connector_name": "plaid",
"connector_label": "plaid3",
"merchant_connector_id": "mca_c0iTEayEJMViYwEhTCOG",
"profile_id": "pro_UgP3FfqWGhfPLuUqYtJF",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "Some_key",
"key1": "Some_key"
},
"payment_methods_enabled": [
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "giropay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 10000,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"USD",
"GBP",
"CAD",
"AUD",
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"city": "NY",
"unit": "246"
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": {
"open_banking_recipient_data": {
"account_data": {
"bacs": {
"account_number": "55779911",
"sort_code": "200000",
"name": "merchant_name",
"connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74"
}
}
}
}
}
```
Response when the connector does not support recipient creation (locker call to be made in this)
```
{
"connector_type": "payment_processor",
"connector_name": "plaid",
"connector_label": "plaid3",
"merchant_connector_id": "mca_6bIUIrWNSbqssRO89Zxx",
"profile_id": "pro_UgP3FfqWGhfPLuUqYtJF",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "Some_key",
"key1": "Some_key"
},
"payment_methods_enabled": [
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "giropay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 10000,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": {
"type": "enable_only",
"list": [
"USD",
"GBP",
"CAD",
"AUD",
"EUR"
]
},
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"city": "NY",
"unit": "246"
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": {
"open_banking_recipient_data": {
"account_data": {
"bacs": {
"account_number": "55779911",
"sort_code": "200000",
"name": "merchant_name"
}
}
}
}
}
```
| [
"config/config.example.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/api_models/src/admin.rs",
"crates/common_enums/src/enums.rs",
"crates/diesel_models/src/... | |
juspay/hyperswitch | juspay__hyperswitch-3756 | Bug: fix(invite): set user status to invitation sent if a registered user is invited
| diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 54fbecc64f3..96753236c1c 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -666,7 +666,13 @@ async fn handle_existing_user_invitation(
merchant_id: user_from_token.merchant_id.clone(),
role_id: request.role_id.clone(),
org_id: user_from_token.org_id.clone(),
- status: UserStatus::Active,
+ status: {
+ if cfg!(feature = "email") {
+ UserStatus::InvitationSent
+ } else {
+ UserStatus::Active
+ }
+ },
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id.clone(),
created_at: now,
| 2024-02-21T13:40:29Z |
## Description
<!-- Describe your changes in detail -->
This PR will set the status of the user who has been invited but already registered with Hyperswitch as InvitationSent
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #3756
# | 7c63c76011cec5fb398cff90b6237578c132b87d |
Local SES.
```
curl --location 'http://localhost:8080/user/user/invite_multiple \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"email": "email of the registered user“,
"name": "name",
"role_id": "some valid role"
}
```
```
curl --location 'http://localhost:8080/user/user/list' \
--header 'Authorization: Bearer JWT'
```
In this api response, the invited user status will be InvitationSent
```
[
{
"email": "invited user email",
"name": "invited user name",
"role_id": "merchant_admin",
"role_name": "Admin",
"status": "InvitationSent",
"last_modified_at": "2024-02-21T13:37:26.847Z"
}
]
```
| [
"crates/router/src/core/user.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3733 | Bug: [FIX] Add update mandate config in docker-compose file
### Feature Description
Add update mandate config in docker-compose file
### Possible Implementation
Add update mandate config in docker-compose file
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 3f7c64624fa..8170132bb85 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -359,6 +359,9 @@ bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.giropay = {connector_list = "adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
[connector_customer]
connector_list = "gocardless,stax,stripe"
| 2024-02-20T17:07:37Z |
## Description
add update mandate config in docker_compose.toml file
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 6aeb44091b34f202b60868028979b3720e3507ce | Cannot test this PR as this is just a config addition
| [
"config/docker_compose.toml"
] | |
juspay/hyperswitch | juspay__hyperswitch-3729 | Bug: refactor: remove permissions from files and forex apis
| diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 78df1d6823e..215227b91a3 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -29,7 +29,6 @@ pub enum Permission {
MerchantAccountWrite,
MerchantConnectorAccountRead,
MerchantConnectorAccountWrite,
- ForexRead,
RoutingRead,
RoutingWrite,
DisputeRead,
@@ -38,8 +37,6 @@ pub enum Permission {
MandateWrite,
CustomerRead,
CustomerWrite,
- FileRead,
- FileWrite,
Analytics,
ThreeDsDecisionManagerWrite,
ThreeDsDecisionManagerRead,
@@ -55,14 +52,12 @@ pub enum PermissionModule {
Payments,
Refunds,
MerchantAccount,
- Forex,
Connectors,
Routing,
Analytics,
Mandates,
Customer,
Disputes,
- Files,
ThreeDsDecisionManager,
SurchargeDecisionManager,
AccountCreate,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 82569579cfc..b8168fc5329 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2167,3 +2167,51 @@ pub enum ConnectorStatus {
Inactive,
Active,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum RoleScope {
+ Merchant,
+ Organization,
+}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum PermissionGroup {
+ OperationsView,
+ OperationsManage,
+ ConnectorsView,
+ ConnectorsManage,
+ WorkflowsView,
+ WorkflowsManage,
+ AnalyticsView,
+ UsersView,
+ UsersManage,
+ MerchantDetailsView,
+ MerchantDetailsManage,
+ OrganizationManage,
+}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 4ca5b4c986c..3ee7e811873 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -501,53 +501,3 @@ pub enum DashboardMetadata {
IsMultipleConfiguration,
IsChangePasswordRequired,
}
-
-#[derive(
- Clone,
- Copy,
- Debug,
- Eq,
- PartialEq,
- serde::Deserialize,
- serde::Serialize,
- strum::Display,
- strum::EnumString,
- frunk::LabelledGeneric,
-)]
-#[diesel_enum(storage_type = "db_enum")]
-#[serde(rename_all = "snake_case")]
-#[strum(serialize_all = "snake_case")]
-pub enum RoleScope {
- Merchant,
- Organization,
-}
-
-#[derive(
- Clone,
- Copy,
- Debug,
- Eq,
- PartialEq,
- serde::Serialize,
- serde::Deserialize,
- strum::Display,
- strum::EnumString,
- frunk::LabelledGeneric,
-)]
-#[diesel_enum(storage_type = "text")]
-#[serde(rename_all = "snake_case")]
-#[strum(serialize_all = "snake_case")]
-pub enum PermissionGroup {
- OperationsView,
- OperationsManage,
- ConnectorsView,
- ConnectorsManage,
- WorkflowsView,
- WorkflowsManage,
- AnalyticsView,
- UsersView,
- UsersManage,
- MerchantDetailsView,
- MerchantDetailsManage,
- OrganizationManage,
-}
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index b8704aebbd0..a54576cc91b 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -21,6 +21,23 @@ impl Role {
.await
}
+ pub async fn find_by_role_id_in_merchant_scope(
+ conn: &PgPooledConn,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::role_id.eq(role_id.to_owned()).and(
+ dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id
+ .eq(org_id.to_owned())
+ .and(dsl::scope.eq(RoleScope::Organization))),
+ ),
+ )
+ .await
+ }
+
pub async fn update_by_role_id(
conn: &PgPooledConn,
role_id: &str,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 54fbecc64f3..e7639af3918 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -617,9 +617,9 @@ async fn handle_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
) -> UserResult<InviteMultipleUserResponse> {
- let inviter_user = user_from_token.get_user(state).await?;
+ let inviter_user = user_from_token.get_user_from_db(state).await?;
- if inviter_user.email == request.email {
+ if inviter_user.get_email() == request.email {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User Inviting themselves".to_string(),
)
@@ -926,7 +926,7 @@ pub async fn switch_merchant_id(
.filter(|role| role.status == UserStatus::Active)
.collect::<Vec<_>>();
- let user = user_from_token.get_user(&state).await?.into();
+ let user = user_from_token.get_user_from_db(&state).await?;
let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) {
let key_store = state
@@ -995,7 +995,7 @@ pub async fn create_merchant_account(
user_from_token: auth::UserFromToken,
req: user_api::UserMerchantCreate,
) -> UserResponse<()> {
- let user_from_db: domain::UserFromStorage = user_from_token.get_user(&state).await?.into();
+ 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();
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index 7318f9973f1..3f6180158a5 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -459,8 +459,8 @@ async fn insert_metadata(
#[cfg(feature = "email")]
{
- let user_data = user.get_user(state).await?;
- let user_email = domain::UserEmail::from_pii_email(user_data.email.clone())
+ let user_data = user.get_user_from_db(state).await?;
+ let user_email = domain::UserEmail::from_pii_email(user_data.get_email())
.change_context(UserErrors::InternalServerError)?
.get_secret()
.expose();
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 14be9bb6991..16047bc3eb7 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -172,7 +172,7 @@ pub async fn transfer_org_ownership(
auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
- let user_from_db = domain::UserFromStorage::from(user_from_token.get_user(&state).await?);
+ let user_from_db = user_from_token.get_user_from_db(&state).await?;
let user_role = user_from_db
.get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id)
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0897deb87e5..213417b1318 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2274,6 +2274,17 @@ impl RoleInterface for KafkaStore {
self.diesel_store.find_role_by_role_id(role_id).await
}
+ async fn find_role_by_role_id_in_merchant_scope(
+ &self,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store
+ .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
+ .await
+ }
+
async fn update_role_by_role_id(
&self,
role_id: &str,
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index da2abf15ff7..90e1e97e377 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -1,3 +1,4 @@
+use common_enums::enums;
use diesel_models::role as storage;
use error_stack::{IntoReport, ResultExt};
@@ -20,6 +21,13 @@ pub trait RoleInterface {
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError>;
+ async fn find_role_by_role_id_in_merchant_scope(
+ &self,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
async fn update_role_by_role_id(
&self,
role_id: &str,
@@ -59,6 +67,19 @@ impl RoleInterface for Store {
.into_report()
}
+ async fn find_role_by_role_id_in_merchant_scope(
+ &self,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::find_by_role_id_in_merchant_scope(&conn, role_id, merchant_id, org_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn update_role_by_role_id(
&self,
role_id: &str,
@@ -149,6 +170,30 @@ impl RoleInterface for MockDb {
)
}
+ async fn find_role_by_role_id_in_merchant_scope(
+ &self,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let roles = self.roles.lock().await;
+ roles
+ .iter()
+ .find(|role| {
+ role.role_id == role_id
+ && (role.merchant_id == merchant_id
+ || (role.org_id == org_id && role.scope == enums::RoleScope::Organization))
+ })
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No role available in merchant scope for role_id = {role_id}, \
+ merchant_id = {merchant_id} and org_id = {org_id}"
+ ))
+ .into(),
+ )
+ }
+
async fn update_role_by_role_id(
&self,
role_id: &str,
diff --git a/crates/router/src/routes/currency.rs b/crates/router/src/routes/currency.rs
index 1e185851717..74a559e88e9 100644
--- a/crates/router/src/routes/currency.rs
+++ b/crates/router/src/routes/currency.rs
@@ -4,7 +4,7 @@ use router_env::Flow;
use crate::{
core::{api_locking, currency},
routes::AppState,
- services::{api, authentication as auth, authorization::permissions::Permission},
+ services::{api, authentication as auth},
};
pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
@@ -17,7 +17,7 @@ pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> Htt
|state, _auth: auth::AuthenticationData, _| currency::retrieve_forex(state),
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::ForexRead),
+ &auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -49,7 +49,7 @@ pub async fn convert_forex(
},
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::ForexRead),
+ &auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/files.rs b/crates/router/src/routes/files.rs
index 95f4007cb91..63dfb38c614 100644
--- a/crates/router/src/routes/files.rs
+++ b/crates/router/src/routes/files.rs
@@ -2,7 +2,7 @@ use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
-use crate::{core::api_locking, services::authorization::permissions::Permission};
+use crate::core::api_locking;
pub mod transformers;
use super::app::AppState;
@@ -47,7 +47,7 @@ pub async fn files_create(
|state, auth, req| files_create_core(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::FileWrite),
+ &auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -89,7 +89,7 @@ pub async fn files_delete(
|state, auth, req| files_delete_core(state, auth.merchant_account, req),
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::FileWrite),
+ &auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -131,7 +131,7 @@ pub async fn files_retrieve(
|state, auth, req| files_retrieve_core(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::FileRead),
+ &auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 990e0785306..1004982d292 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -749,6 +749,48 @@ where
}
}
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for DashboardNoPermissionAuth
+where
+ A: AppStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ &payload.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ };
+ Ok((
+ auth.clone(),
+ AuthenticationType::MerchantJwt {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+}
+
pub trait ClientSecretFetch {
fn get_client_secret(&self) -> Option<&String>;
}
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 450a5a738c3..d982317e023 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -31,13 +31,11 @@ pub enum PermissionModule {
Refunds,
MerchantAccount,
Connectors,
- Forex,
Routing,
Analytics,
Mandates,
Customer,
Disputes,
- Files,
ThreeDsDecisionManager,
SurchargeDecisionManager,
AccountCreate,
@@ -51,12 +49,10 @@ impl PermissionModule {
Self::MerchantAccount => "Accounts module permissions allow the user to view and update account details, configure webhooks and much more",
Self::Connectors => "All connector related actions - like configuring new connectors, viewing and updating connector configuration lies with this module",
Self::Routing => "All actions related to new, active, and past routing stacks take place here",
- Self::Forex => "Forex module permissions allow the user to view and query the forex rates",
Self::Analytics => "Permission to view and analyse the data relating to payments, refunds, sdk etc.",
Self::Mandates => "Everything related to mandates - like creating and viewing mandate related information are within this module",
Self::Customer => "Everything related to customers - like creating and viewing customer related information are within this module",
Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module",
- Self::Files => "Permissions for uploading, deleting and viewing files for disputes",
Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant",
Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant",
Self::AccountCreate => "Create new account within your organization"
@@ -108,11 +104,6 @@ impl ModuleInfo {
Permission::MerchantConnectorAccountWrite,
]),
},
- PermissionModule::Forex => Self {
- module: module_name,
- description,
- permissions: PermissionInfo::new(&[Permission::ForexRead]),
- },
PermissionModule::Routing => Self {
module: module_name,
description,
@@ -150,11 +141,6 @@ impl ModuleInfo {
Permission::DisputeWrite,
]),
},
- PermissionModule::Files => Self {
- module: module_name,
- description,
- permissions: PermissionInfo::new(&[Permission::FileRead, Permission::FileWrite]),
- },
PermissionModule::ThreeDsDecisionManager => Self {
module: module_name,
description,
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 5c5e3ecce30..3e022e8f666 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -12,7 +12,6 @@ pub enum Permission {
MerchantAccountWrite,
MerchantConnectorAccountRead,
MerchantConnectorAccountWrite,
- ForexRead,
RoutingRead,
RoutingWrite,
DisputeRead,
@@ -21,8 +20,6 @@ pub enum Permission {
MandateWrite,
CustomerRead,
CustomerWrite,
- FileRead,
- FileWrite,
Analytics,
ThreeDsDecisionManagerWrite,
ThreeDsDecisionManagerRead,
@@ -50,7 +47,6 @@ impl Permission {
Self::MerchantConnectorAccountWrite => {
"Create, update, verify and delete connector configurations"
}
- Self::ForexRead => "Query Forex data",
Self::RoutingRead => "View routing configuration",
Self::RoutingWrite => "Create and activate routing configurations",
Self::DisputeRead => "View disputes",
@@ -59,8 +55,6 @@ impl Permission {
Self::MandateWrite => "Create and update mandates",
Self::CustomerRead => "View customers",
Self::CustomerWrite => "Create, update and delete customers",
- Self::FileRead => "View files",
- Self::FileWrite => "Create, update and delete files",
Self::Analytics => "Access to analytics module",
Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules",
Self::ThreeDsDecisionManagerRead => {
diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs
index fd98d90c191..bd0f37e2a0d 100644
--- a/crates/router/src/services/authorization/predefined_permissions.rs
+++ b/crates/router/src/services/authorization/predefined_permissions.rs
@@ -50,7 +50,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MerchantConnectorAccountWrite,
Permission::RoutingRead,
Permission::RoutingWrite,
- Permission::ForexRead,
Permission::ThreeDsDecisionManagerWrite,
Permission::ThreeDsDecisionManagerRead,
Permission::SurchargeDecisionManagerWrite,
@@ -61,8 +60,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MandateWrite,
Permission::CustomerRead,
Permission::CustomerWrite,
- Permission::FileRead,
- Permission::FileWrite,
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
@@ -84,14 +81,12 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MerchantAccountRead,
Permission::MerchantConnectorAccountRead,
Permission::RoutingRead,
- Permission::ForexRead,
Permission::ThreeDsDecisionManagerRead,
Permission::SurchargeDecisionManagerRead,
Permission::Analytics,
Permission::DisputeRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
Permission::UsersRead,
],
name: None,
@@ -117,7 +112,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MerchantConnectorAccountWrite,
Permission::RoutingRead,
Permission::RoutingWrite,
- Permission::ForexRead,
Permission::ThreeDsDecisionManagerWrite,
Permission::ThreeDsDecisionManagerRead,
Permission::SurchargeDecisionManagerWrite,
@@ -128,8 +122,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MandateWrite,
Permission::CustomerRead,
Permission::CustomerWrite,
- Permission::FileRead,
- Permission::FileWrite,
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
@@ -156,7 +148,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MerchantAccountRead,
Permission::MerchantAccountWrite,
Permission::MerchantConnectorAccountRead,
- Permission::ForexRead,
Permission::MerchantConnectorAccountWrite,
Permission::RoutingRead,
Permission::RoutingWrite,
@@ -170,8 +161,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MandateWrite,
Permission::CustomerRead,
Permission::CustomerWrite,
- Permission::FileRead,
- Permission::FileWrite,
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
@@ -190,7 +179,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::RefundRead,
Permission::ApiKeyRead,
Permission::MerchantAccountRead,
- Permission::ForexRead,
Permission::MerchantConnectorAccountRead,
Permission::RoutingRead,
Permission::ThreeDsDecisionManagerRead,
@@ -198,7 +186,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::DisputeRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
Permission::Analytics,
Permission::UsersRead,
],
@@ -216,7 +203,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::RefundRead,
Permission::ApiKeyRead,
Permission::MerchantAccountRead,
- Permission::ForexRead,
Permission::MerchantConnectorAccountRead,
Permission::RoutingRead,
Permission::ThreeDsDecisionManagerRead,
@@ -224,7 +210,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::DisputeRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
@@ -244,7 +229,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::ApiKeyRead,
Permission::ApiKeyWrite,
Permission::MerchantAccountRead,
- Permission::ForexRead,
Permission::MerchantConnectorAccountRead,
Permission::RoutingRead,
Permission::ThreeDsDecisionManagerRead,
@@ -252,7 +236,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::DisputeRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
Permission::Analytics,
Permission::UsersRead,
],
@@ -272,7 +255,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::RefundWrite,
Permission::ApiKeyRead,
Permission::MerchantAccountRead,
- Permission::ForexRead,
Permission::MerchantConnectorAccountRead,
Permission::MerchantConnectorAccountWrite,
Permission::RoutingRead,
@@ -284,7 +266,6 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::DisputeRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
Permission::Analytics,
Permission::UsersRead,
],
@@ -301,15 +282,12 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::PaymentRead,
Permission::RefundRead,
Permission::RefundWrite,
- Permission::ForexRead,
Permission::DisputeRead,
Permission::DisputeWrite,
Permission::MerchantAccountRead,
Permission::MerchantConnectorAccountRead,
Permission::MandateRead,
Permission::CustomerRead,
- Permission::FileRead,
- Permission::FileWrite,
Permission::Analytics,
],
name: Some("Customer Support"),
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 468fa8e4cd2..ab32febf9b4 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -802,14 +802,12 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule {
info::PermissionModule::Payments => Self::Payments,
info::PermissionModule::Refunds => Self::Refunds,
info::PermissionModule::MerchantAccount => Self::MerchantAccount,
- info::PermissionModule::Forex => Self::Forex,
info::PermissionModule::Connectors => Self::Connectors,
info::PermissionModule::Routing => Self::Routing,
info::PermissionModule::Analytics => Self::Analytics,
info::PermissionModule::Mandates => Self::Mandates,
info::PermissionModule::Customer => Self::Customer,
info::PermissionModule::Disputes => Self::Disputes,
- info::PermissionModule::Files => Self::Files,
info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager,
info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager,
info::PermissionModule::AccountCreate => Self::AccountCreate,
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 9c2d2c1fd3f..86b298822ac 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -48,13 +48,13 @@ impl UserFromToken {
Ok(merchant_account)
}
- pub async fn get_user(&self, state: &AppState) -> UserResult<diesel_models::user::User> {
+ pub async fn get_user_from_db(&self, state: &AppState) -> UserResult<UserFromStorage> {
let user = state
.store
.find_user_by_id(&self.user_id)
.await
.change_context(UserErrors::InternalServerError)?;
- Ok(user)
+ Ok(user.into())
}
}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 9c7150c08da..b677e89269e 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -38,7 +38,6 @@ impl From<Permission> for user_role_api::Permission {
Permission::MerchantAccountWrite => Self::MerchantAccountWrite,
Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead,
Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite,
- Permission::ForexRead => Self::ForexRead,
Permission::RoutingRead => Self::RoutingRead,
Permission::RoutingWrite => Self::RoutingWrite,
Permission::DisputeRead => Self::DisputeRead,
@@ -47,8 +46,6 @@ impl From<Permission> for user_role_api::Permission {
Permission::MandateWrite => Self::MandateWrite,
Permission::CustomerRead => Self::CustomerRead,
Permission::CustomerWrite => Self::CustomerWrite,
- Permission::FileRead => Self::FileRead,
- Permission::FileWrite => Self::FileWrite,
Permission::Analytics => Self::Analytics,
Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite,
Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead,
| 2024-02-20T13:56:27Z |
## Description
<!-- Describe your changes in detail -->
This PR will remove permissions for Files and Forex apis.
It also adds `find_role_by_role_id_in_merchant_scope` db function.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #3729
# | cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0 |
Postman.
- Files - Read (`/files` POST)
```
curl --location 'http://localhost:8080/files' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{user_token}}' \
--form 'purpose="dispute_evidence"' \
--form 'file=@"/Users/mani.dchandra/Pictures/sample.pdf"' \
--form 'dispute_id="{{dispute_id}}"'
```
```
{
"file_id": "file_id"
}
```
- Files - Delete (`/files/{file_id}` DELETE)
```
curl --location --request DELETE 'http://localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{user_token}}'
```
```
{
"error": {
"type": "invalid_request",
"message": "Not Supported because provider is not Router",
"code": "IR_23"
}
}
```
Currently deletion will not be possible for dispute evidence. But you can hit this api without the `FileWrite` permission.
- Files - Retrieve (`/files/{file_id}` GET)
```
curl --location 'http://localhost:8080/files/file_Uy7bK9lFFaBDXGhivUjo' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{user_token}}'
```
This api will return contents of the uploaded files.
Above APIs will now work with JWTs with roles which doesn't have `FileRead`/`FileWrite` permissions.
- Forex - Rates (`/forex/rates` GET)
```
curl --location 'http://localhost:8080/forex/rates' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{user_token}}'
```
- Forex - Convert from minor (`/forex/convert_from_minor` GET)
```
curl --location 'http://localhost:8080/forex/convert_from_minor?amount=100&from_currency=USD&to_currency=INR' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer {{user_token}}'
```
```
{
"converted_amount": "82.89544400",
"currency": "INR"
}
```
will now work with JWTs with roles which doesn't have `ForexRead` permission.
| [
"crates/api_models/src/user_role.rs",
"crates/common_enums/src/enums.rs",
"crates/diesel_models/src/enums.rs",
"crates/diesel_models/src/query/role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user/dashboard_metadata.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/db/k... | |
juspay/hyperswitch | juspay__hyperswitch-3726 | Bug: [FEATURE]: [Adyen] populate connector_transaction_id for Adyen Payment Response
### :memo: Feature Description
- populate connector_transaction_id for Adyen Payment Response
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
- yes | diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 072b542eee0..d8213e2db98 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3159,9 +3159,11 @@ pub fn get_redirection_response(
let connector_metadata = get_wait_screen_metadata(&response)?;
- // We don't get connector transaction id for redirections in Adyen.
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ resource_id: match response.psp_reference.as_ref() {
+ Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()),
+ None => types::ResponseId::NoResponseId,
+ },
redirection_data,
mandate_reference: None,
connector_metadata,
@@ -3264,9 +3266,11 @@ pub fn get_qr_code_response(
};
let connector_metadata = get_qr_metadata(&response)?;
- // We don't get connector transaction id for redirections in Adyen.
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ resource_id: match response.psp_reference.as_ref() {
+ Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()),
+ None => types::ResponseId::NoResponseId,
+ },
redirection_data: None,
mandate_reference: None,
connector_metadata,
| 2024-02-20T13:26:34Z |
## Description
<!-- Describe your changes in detail -->
populate connector_transaction_id for Adyen Payment Response - (RedirectionResponse and QrCodeResponseResponse)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0 | PIx via Adyen request - (it uses QrCodeResponseResponse)
```
{
"amount": 5000,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"profile_id": "pro_sx78reJN0zgRzB5UGicx",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"payment_method": "bank_transfer",
"payment_method_type": "pix",
"payment_method_data": {
"bank_transfer": {
"pix": {}
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Pix response
```
{
"payment_id": "pay_HciK53YclKPcpOY7J4Zx",
"merchant_id": "merchant_1708428346",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_HciK53YclKPcpOY7J4Zx_secret_mhOJoO92ETjFntcpFlzd",
"created": "2024-02-20T13:27:59.206Z",
"currency": "BRL",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_transfer",
"payment_method_data": "bank_transfer",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"billing": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "qr_code_information",
"image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAEICAAAAACGnTUjAAADfUlEQVR4nO3QS25dOQwA0c7+F90foGpCgKCeE3cGqQN4QEq6fqgff/+V/xQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIVAIFAKFQCFQCBQChUAhUAgUAoVAIXCG+PHv31f4Xd87y708n3td5xffbwqBQqAQKAQKgUKgEHgOcd3Tdn/uneV+8p7nc7683i8ECoFCoBAoBAqBQuDjEM7TPHee5vmc9bp3nua586YQKAQKgUKgECgECoFvD+G88d4033nP/Zynee68KQQKgUKgECgECoFC4H8PMffOcj95z/M5T/PceVMIFAKFQCFQCBQChcDHIS7zvvPF+5PvPZ/z5fV+IVAIFAKFQCFQCBQCzyE+5Xd9/6vnT/l+UwgUAoVAIVAIFAKFwBniZ/nD/T/bLPfyfO5/tUKgECgECoFCoBAoBM4Q1w+Z584b72ne99z9nC/el+/mfioECoFCoBAoBAqBQuAMcfEfye/Nva7zje8mvzPPt/2mECgECoFCoBAoBAqBj0P4Dya/4/mcde3l+dx/l0KgECgECoFCoBAoBM4Q/qCN773nrGsvz907b7Z72/5SCBQChUAhUAgUAoXAcwjvOV+8r/nuOpf3vnou720KgUKgECgECoFCoBB4DqHtvvc832bNvbPcy3P3c5b7TxUChUAhUAgUAoVAIXCG2PgD5vvXvfMr3+l6P+9fCoFCoBAoBAqBQqAQ+HIIzR80v+f5tb/myXN5b9tfCoFCoBAoBAqBQqAQOEPMD2t7N+/Pe567d5Z7zfOL7+c795tCoBAoBAqBQqAQKATOED/LH3T9H+9ttve+m+fuNc+nQqAQKAQKgUKgECgEzhDzg6/8ru+dX/lOvnf/Or8qBAqBQqAQKAQKgULgOcR1T9v91/01T/PcefJ8UwgUAoVAIVAIFAKFwMchnKd5fs36dH/xnXw/91MhUAgUAoVAIVAIFALfHkLu5bl758nzzeu77Z4KgUKgECgECoFCoBD4bSEuvp/v5v51vhQChUAhUAgUAoVAIfBxiMvr/Xlvzpp752k7d38pBAqBQqAQKAQKgULgOcSn/K7vr1lzP+eN9zTvz/OpECgECoFCoBAoBAqBM8SfohAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgUKgECgECoFCoBAoBAqBQqAQKAQKgX8A/Ak4Wyhn58sAAAAASUVORK5CYII=",
"display_to_timestamp": 1708439280000,
"qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=TestQRCodeEMVToken"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "pix",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1708435679,
"expires": 1708439279,
"secret": "epk_286a4b57f8a34e969f09879055c1ecca"
},
"manual_retry_allowed": null,
"connector_transaction_id": "QS3SDRRC564DCG65", (it should not be null)
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_qisu2wRsK4dq0H3hKKpM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-20T13:42:59.206Z",
"fingerprint": null
}
```
In Response check for `"connector_transaction_id": "some string"`, (it should not be null)
Payment Request for Blik via Adyen - (it uses RedirectionResponse)
```
{
"amount": 10000,
"currency": "PLN",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 10000,
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"profile_id": "pro_sx78reJN0zgRzB5UGicx",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"payment_method": "bank_redirect",
"payment_method_type": "blik",
"payment_method_data": {
"bank_redirect": {
"blik": {
"blik_code":"777987"
}
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "PL"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "PL",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Blik Response
```
{
"payment_id": "pay_brzqtt6cdm5rL3HAYPxk",
"merchant_id": "merchant_1708428346",
"status": "processing",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3",
"created": "2024-02-20T13:30:26.642Z",
"currency": "PLN",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_redirect",
"payment_method_data": "bank_redirect",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "PL",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"billing": {
"address": {
"city": "San Fransico",
"country": "PL",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "wait_screen_information",
"display_from_timestamp": 1708435828625707000,
"display_to_timestamp": 1708435888625707000
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "blik",
"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": 1708435826,
"expires": 1708439426,
"secret": "epk_940c1cecdd6b49928d2047f91ff5659c"
},
"manual_retry_allowed": false,
"connector_transaction_id": "DQ7M74SBGTGLNK82",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_qisu2wRsK4dq0H3hKKpM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-20T13:45:26.642Z",
"fingerprint": null
}
```
In Response check for `"connector_transaction_id": "some string"`, (it should not be null)
| [
"crates/router/src/connector/adyen/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3725 | Bug: Feat(analytics): dispute filter api
| diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index ead3b1699ec..fed029f2edb 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -23,6 +23,7 @@ use crate::{
metrics::{latency::LatencyAvg, ApiEventMetricRow},
},
connector_events::events::ConnectorEventsResult,
+ disputes::filters::DisputeFilterRow,
outgoing_webhook_event::events::OutgoingWebhookLogsResult,
sdk_events::events::SdkEventsResult,
types::TableEngine,
@@ -168,6 +169,7 @@ impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
for ClickhouseClient
{
}
+impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {}
#[derive(Debug, serde::Serialize)]
struct CkhQuery {
@@ -277,6 +279,18 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
}
}
+impl TryInto<DisputeFilterRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<DisputeFilterRow, Self::Error> {
+ serde_json::from_value(self)
+ .into_report()
+ .change_context(ParsingError::StructParseFailure(
+ "Failed to parse DisputeFilterRow in clickhouse results",
+ ))
+ }
+}
+
impl TryInto<ApiEventMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
diff --git a/crates/analytics/src/disputes.rs b/crates/analytics/src/disputes.rs
new file mode 100644
index 00000000000..b6d7e6280c7
--- /dev/null
+++ b/crates/analytics/src/disputes.rs
@@ -0,0 +1,5 @@
+mod core;
+
+pub mod filters;
+
+pub use self::core::get_filters;
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs
new file mode 100644
index 00000000000..8ccbbdea6d2
--- /dev/null
+++ b/crates/analytics/src/disputes/core.rs
@@ -0,0 +1,91 @@
+use api_models::analytics::{
+ disputes::DisputeDimensions, DisputeFilterValue, DisputeFiltersResponse,
+ GetDisputeFilterRequest,
+};
+use error_stack::ResultExt;
+
+use super::filters::{get_dispute_filter_for_dimension, DisputeFilterRow};
+use crate::{
+ errors::{AnalyticsError, AnalyticsResult},
+ AnalyticsProvider,
+};
+
+pub async fn get_filters(
+ pool: &AnalyticsProvider,
+ req: GetDisputeFilterRequest,
+ merchant_id: &String,
+) -> AnalyticsResult<DisputeFiltersResponse> {
+ let mut res = DisputeFiltersResponse::default();
+ for dim in req.group_by_names {
+ let values = match pool {
+ AnalyticsProvider::Sqlx(pool) => {
+ get_dispute_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
+ .await
+ }
+ AnalyticsProvider::Clickhouse(pool) => {
+ get_dispute_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
+ .await
+ }
+ AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
+ let ckh_result = get_dispute_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ ckh_pool,
+ )
+ .await;
+ let sqlx_result = get_dispute_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ sqlx_pool,
+ )
+ .await;
+ 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 disputes analytics filters")
+ },
+ _ => {}
+ };
+ ckh_result
+ }
+ AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
+ let ckh_result = get_dispute_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ ckh_pool,
+ )
+ .await;
+ let sqlx_result = get_dispute_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ sqlx_pool,
+ )
+ .await;
+ 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 disputes analytics filters")
+ },
+ _ => {}
+ };
+ sqlx_result
+ }
+ }
+ .change_context(AnalyticsError::UnknownError)?
+ .into_iter()
+ .filter_map(|fil: DisputeFilterRow| match dim {
+ DisputeDimensions::DisputeStatus => fil.dispute_status,
+ DisputeDimensions::DisputeStage => fil.dispute_stage,
+ DisputeDimensions::ConnectorStatus => fil.connector_status,
+ DisputeDimensions::Connector => fil.connector,
+ })
+ .collect::<Vec<String>>();
+ res.query_data.push(DisputeFilterValue {
+ dimension: dim,
+ values,
+ })
+ }
+ Ok(res)
+}
diff --git a/crates/analytics/src/disputes/filters.rs b/crates/analytics/src/disputes/filters.rs
new file mode 100644
index 00000000000..9b03c4de940
--- /dev/null
+++ b/crates/analytics/src/disputes/filters.rs
@@ -0,0 +1,52 @@
+use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow},
+};
+pub trait DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {}
+
+pub async fn get_dispute_filter_for_dimension<T>(
+ dimension: DisputeDimensions,
+ merchant: &String,
+ time_range: &TimeRange,
+ pool: &T,
+) -> FiltersResult<Vec<DisputeFilterRow>>
+where
+ T: AnalyticsDataSource + DisputeFilterAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ query_builder.add_select_column(dimension).switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant)
+ .switch()?;
+
+ query_builder.set_distinct();
+
+ query_builder
+ .execute_query::<DisputeFilterRow, _>(pool)
+ .await
+ .change_context(FiltersError::QueryBuildingError)?
+ .change_context(FiltersError::QueryExecutionFailure)
+}
+#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
+pub struct DisputeFilterRow {
+ pub connector: Option<String>,
+ pub dispute_status: Option<String>,
+ pub connector_status: Option<String>,
+ pub dispute_stage: Option<String>,
+}
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index a4e925519ce..0fb8d9eea6e 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -1,5 +1,6 @@
mod clickhouse;
pub mod core;
+pub mod disputes;
pub mod errors;
pub mod metrics;
pub mod payments;
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index b924987f004..bc21ab8f0f4 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -4,6 +4,7 @@ use api_models::{
analytics::{
self as analytics_api,
api_event::ApiEventDimensions,
+ disputes::DisputeDimensions,
payments::{PaymentDimensions, PaymentDistributions},
refunds::{RefundDimensions, RefundType},
sdk_events::{SdkEventDimensions, SdkEventNames},
@@ -362,6 +363,8 @@ impl_to_sql_for_to_string!(
PaymentDimensions,
&PaymentDistributions,
RefundDimensions,
+ &DisputeDimensions,
+ DisputeDimensions,
PaymentMethod,
PaymentMethodType,
AuthenticationType,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 1fb7a9b4509..0aeffeafa9e 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -144,6 +144,7 @@ impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {}
impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {}
impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}
impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {}
+impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {}
#[async_trait::async_trait]
impl AnalyticsDataSource for SqlxClient {
@@ -425,6 +426,35 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow {
}
}
+impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let dispute_status: Option<String> =
+ row.try_get("dispute_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 connector_status: Option<String> =
+ row.try_get("connector_status").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ Ok(Self {
+ dispute_stage,
+ dispute_status,
+ connector,
+ connector_status,
+ })
+ }
+}
+
impl ToSql<SqlxClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
Ok(self.to_string())
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 1115d40b19d..c12f8e7adfe 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -5,6 +5,7 @@ use masking::Secret;
use self::{
api_event::{ApiEventDimensions, ApiEventMetrics},
+ disputes::DisputeDimensions,
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
@@ -247,3 +248,26 @@ pub struct GetApiEventMetricRequest {
#[serde(default)]
pub delta: bool,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+
+pub struct GetDisputeFilterRequest {
+ pub time_range: TimeRange,
+ #[serde(default)]
+ pub group_by_names: Vec<DisputeDimensions>,
+}
+
+#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct DisputeFiltersResponse {
+ pub query_data: Vec<DisputeFilterValue>,
+}
+
+#[derive(Debug, serde::Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+
+pub struct DisputeFilterValue {
+ pub dimension: DisputeDimensions,
+ pub values: Vec<String>,
+}
diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs
index 19d552d45d4..4b4b7ba3830 100644
--- a/crates/api_models/src/analytics/disputes.rs
+++ b/crates/api_models/src/analytics/disputes.rs
@@ -44,6 +44,7 @@ pub enum DisputeDimensions {
Connector,
DisputeStatus,
ConnectorStatus,
+ DisputeStage,
}
impl From<DisputeDimensions> for NameDescription {
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index ae0525ac609..59b2d54016a 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -95,7 +95,9 @@ impl_misc_api_event_type!(
SdkEventsRequest,
ReportRequest,
ConnectorEventsRequest,
- OutgoingWebhookLogsRequest
+ OutgoingWebhookLogsRequest,
+ GetDisputeFilterRequest,
+ DisputeFiltersResponse
);
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 325ca980243..d126d23c8ae 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -88,6 +88,10 @@ pub mod routes {
web::resource("metrics/api_events")
.route(web::post().to(get_api_events_metrics)),
)
+ .service(
+ web::resource("filters/disputes")
+ .route(web::post().to(get_dispute_filters)),
+ )
}
route
}
@@ -582,4 +586,30 @@ pub mod routes {
))
.await
}
+
+ pub async fn get_dispute_filters(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetDisputeFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth: AuthenticationData, req| async move {
+ analytics::disputes::get_filters(
+ &state.pool,
+ req,
+ &auth.merchant_account.merchant_id,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 9139b5eed41..be6aa257d74 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -54,6 +54,7 @@ pub enum AnalyticsFlow {
GetApiEventFilters,
GetConnectorEvents,
GetOutgoingWebhookEvents,
+ GetDisputeFilters,
}
impl FlowMetric for AnalyticsFlow {}
| 2024-02-20T10:56:43Z |
## Description
added filter api for dispute analytics
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0 | Hit the curl mentioned in the comment below.
response should be the distinct value of dispute dimension given in request
To get the dispute dimensions hit dispute info api follow the link below
https://github.com/juspay/hyperswitch/pull/3693
| [
"crates/analytics/src/clickhouse.rs",
"crates/analytics/src/disputes.rs",
"crates/analytics/src/disputes/core.rs",
"crates/analytics/src/disputes/filters.rs",
"crates/analytics/src/lib.rs",
"crates/analytics/src/query.rs",
"crates/analytics/src/sqlx.rs",
"crates/api_models/src/analytics.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-3717 | Bug: feat: change role apis to support custom roles
| diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 215227b91a3..1c4c28aa993 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,3 +1,4 @@
+use common_enums::RoleScope;
use common_utils::pii;
use crate::user::DashboardEntryResponse;
@@ -7,9 +8,10 @@ pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponse {
- pub role_id: &'static str,
+ pub role_id: String,
pub permissions: Vec<Permission>,
- pub role_name: &'static str,
+ pub role_name: String,
+ pub role_scope: RoleScope,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index d126d23c8ae..51fb6ff822b 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -497,7 +497,7 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth(Permission::PaymentWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e7639af3918..5b634920cf6 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -18,10 +18,8 @@ use crate::services::email::types as email_types;
use crate::{
consts,
routes::AppState,
- services::{
- authentication as auth, authorization::predefined_permissions, ApplicationResponse,
- },
- types::domain,
+ services::{authentication as auth, authorization::roles, ApplicationResponse},
+ types::{domain, transformers::ForeignInto},
utils,
};
pub mod dashboard_metadata;
@@ -444,7 +442,16 @@ pub async fn invite_user(
.into());
}
- if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &request.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_invitable() {
return Err(UserErrors::InvalidRoleId.into())
.attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
@@ -626,7 +633,16 @@ async fn handle_invitation(
.into());
}
- if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ let role_info = roles::get_role_info_from_role_id(
+ state,
+ &request.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_invitable() {
return Err(UserErrors::InvalidRoleId.into())
.attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
@@ -915,20 +931,18 @@ pub async fn switch_merchant_id(
.into());
}
- let user_roles = state
- .store
- .list_user_roles_by_user_id(&user_from_token.user_id)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let active_user_roles = user_roles
- .into_iter()
- .filter(|role| role.status == UserStatus::Active)
- .collect::<Vec<_>>();
-
let user = user_from_token.get_user_from_db(&state).await?;
- let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InternalServerError)?;
+
+ let (token, role_id) = if role_info.is_internal() {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -967,6 +981,17 @@ pub async fn switch_merchant_id(
.await?;
(token, user_from_token.role_id)
} else {
+ let user_roles = state
+ .store
+ .list_user_roles_by_user_id(&user_from_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let active_user_roles = user_roles
+ .into_iter()
+ .filter(|role| role.status == UserStatus::Active)
+ .collect::<Vec<_>>();
+
let user_role = active_user_roles
.iter()
.find(|role| role.merchant_id == request.merchant_id)
@@ -1051,17 +1076,47 @@ pub async fn get_users_for_merchant_account(
state: AppState,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::GetUsersResponse> {
- let users = state
+ let users_and_user_roles = state
.store
.find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str())
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("No users for given merchant id")?
+ .attach_printable("No users for given merchant id")?;
+
+ let users_user_roles_and_roles =
+ futures::future::try_join_all(users_and_user_roles.into_iter().map(
+ |(user, user_role)| async {
+ roles::get_role_info_from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_role.merchant_id,
+ &user_role.org_id,
+ )
+ .await
+ .map(|role_info| (user, user_role, role_info))
+ .to_not_found_response(UserErrors::InternalServerError)
+ },
+ ))
+ .await?;
+
+ let user_details_vec = users_user_roles_and_roles
.into_iter()
- .filter_map(|(user, role)| domain::UserAndRoleJoined(user, role).try_into().ok())
+ .map(|(user, user_role, role_info)| {
+ let user = domain::UserFromStorage::from(user);
+ user_api::UserDetails {
+ email: user.get_email(),
+ name: user.get_name(),
+ role_id: user_role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ status: user_role.status.foreign_into(),
+ last_modified_at: user_role.last_modified,
+ }
+ })
.collect();
- Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users)))
+ Ok(ApplicationResponse::Json(user_api::GetUsersResponse(
+ user_details_vec,
+ )))
}
#[cfg(feature = "email")]
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 16047bc3eb7..c2dfd34322c 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -10,7 +10,7 @@ use crate::{
routes::AppState,
services::{
authentication::{self as auth},
- authorization::{info, predefined_permissions},
+ authorization::{info, roles},
ApplicationResponse,
},
types::domain,
@@ -30,58 +30,96 @@ pub async fn get_authorization_info(
))
}
-pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRolesResponse> {
+pub async fn list_invitable_roles(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_role_api::ListRolesResponse> {
+ let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES
+ .iter()
+ .filter(|(_, role_info)| role_info.is_invitable())
+ .map(|(role_id, role_info)| user_role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_id.to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
+ let custom_roles_map = state
+ .store
+ .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(roles::RoleInfo::from)
+ .filter(|role_info| role_info.is_invitable())
+ .map(|role_info| user_role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
Ok(ApplicationResponse::Json(user_role_api::ListRolesResponse(
- predefined_permissions::PREDEFINED_PERMISSIONS
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .filter_map(|(role_id, role_info)| {
- utils::user_role::get_role_name_and_permission_response(role_info).map(
- |(permissions, role_name)| user_role_api::RoleInfoResponse {
- permissions,
- role_id,
- role_name,
- },
- )
- })
- .collect(),
+ predefined_roles_map.chain(custom_roles_map).collect(),
)))
}
pub async fn get_role(
- _state: AppState,
+ state: AppState,
+ user_from_token: auth::UserFromToken,
role: user_role_api::GetRoleRequest,
) -> UserResponse<user_role_api::RoleInfoResponse> {
- let info = predefined_permissions::PREDEFINED_PERMISSIONS
- .get_key_value(role.role_id.as_str())
- .and_then(|(role_id, role_info)| {
- utils::user_role::get_role_name_and_permission_response(role_info).map(
- |(permissions, role_name)| user_role_api::RoleInfoResponse {
- permissions,
- role_id,
- role_name,
- },
- )
- })
- .ok_or(UserErrors::InvalidRoleId)?;
+ let role_info = roles::get_role_info_from_role_id(
+ &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());
+ }
- Ok(ApplicationResponse::Json(info))
+ let permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(user_role_api::RoleInfoResponse {
+ permissions,
+ role_id: role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }))
}
pub async fn get_role_from_token(
- _state: AppState,
- user: auth::UserFromToken,
+ state: AppState,
+ user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_role_api::Permission>> {
- Ok(ApplicationResponse::Json(
- predefined_permissions::PREDEFINED_PERMISSIONS
- .get(user.role_id.as_str())
- .ok_or(UserErrors::InternalServerError.into())
- .attach_printable("Invalid Role Id in JWT")?
- .get_permissions()
- .iter()
- .map(|&per| per.into())
- .collect(),
- ))
+ let role_info = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?;
+
+ let permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(permissions))
}
pub async fn update_user_role(
@@ -89,7 +127,16 @@ pub async fn update_user_role(
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
) -> UserResponse<()> {
- if !predefined_permissions::is_role_updatable(&req.role_id)? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &req.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_updatable() {
return Err(UserErrors::InvalidRoleOperation.into())
.attach_printable(format!("User role cannot be updated to {}", req.role_id));
}
@@ -110,10 +157,19 @@ pub async fn update_user_role(
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
- if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? {
+ let role_to_be_updated = roles::get_role_info_from_role_id(
+ &state,
+ &user_role_to_be_updated.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ if !role_to_be_updated.is_updatable() {
return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!(
"User role cannot be updated from {}",
- user_role_to_be_updated.role_id
+ role_to_be_updated.get_role_id()
));
}
@@ -270,7 +326,15 @@ pub async fn delete_user_role(
.find(|&role| role.merchant_id == user_from_token.merchant_id.as_str())
{
Some(user_role) => {
- if !predefined_permissions::is_role_deletable(&user_role.role_id)? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ if !role_info.is_deletable() {
return Err(UserErrors::InvalidDeleteOperation.into())
.attach_printable(format!("role_id = {} is not deletable", user_role.role_id));
}
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a863bc2b662..ea51383c94b 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -291,7 +291,7 @@ pub async fn delete_sample_data(
&http_req,
payload.into_inner(),
sample_data::delete_sample_data_for_user,
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth(Permission::MerchantAccountWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index f84c158332b..63e2ce37269 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -36,7 +36,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt
state.clone(),
&req,
(),
- |state, _: (), _| user_role_core::list_roles(state),
+ |state, user, _| user_role_core::list_invitable_roles(state, user),
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -57,7 +57,7 @@ pub async fn get_role(
state.clone(),
&req,
request_payload,
- |state, _: (), req| user_role_core::get_role(state, req),
+ user_role_core::get_role,
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 1004982d292..34153ef6e8f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -503,8 +503,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
Ok((
(),
@@ -532,8 +532,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
Ok((
UserFromToken {
@@ -570,8 +570,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.required_permission, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.required_permission, &permissions)?;
// Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
@@ -613,8 +613,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
let key_store = state
.store()
@@ -663,8 +663,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
let key_store = state
.store()
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index cad9b1ece62..034773a07ea 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -1,14 +1,50 @@
-use crate::core::errors::{ApiErrorResponse, RouterResult};
+use common_enums::PermissionGroup;
+
+use super::authentication::AuthToken;
+use crate::{
+ core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt},
+ routes::app::AppStateInfo,
+};
pub mod info;
+pub mod permission_groups;
pub mod permissions;
-pub mod predefined_permissions;
+pub mod roles;
+
+pub async fn get_permissions<A>(
+ state: &A,
+ token: &AuthToken,
+) -> RouterResult<Vec<permissions::Permission>>
+where
+ A: AppStateInfo + Sync,
+{
+ if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
+ Ok(get_permissions_from_groups(
+ role_info.get_permission_groups(),
+ ))
+ } else {
+ state
+ .store()
+ .find_role_by_role_id_in_merchant_scope(
+ &token.role_id,
+ &token.merchant_id,
+ &token.org_id,
+ )
+ .await
+ .map(|role| get_permissions_from_groups(&role.groups))
+ .to_not_found_response(ApiErrorResponse::InvalidJwtToken)
+ }
+}
-pub fn get_permissions(role: &str) -> RouterResult<&Vec<permissions::Permission>> {
- predefined_permissions::PREDEFINED_PERMISSIONS
- .get(role)
- .map(|role_info| role_info.get_permissions())
- .ok_or(ApiErrorResponse::InvalidJwtToken.into())
+pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> {
+ groups
+ .iter()
+ .flat_map(|group| {
+ permission_groups::get_permissions_vec(group)
+ .iter()
+ .cloned()
+ })
+ .collect()
}
pub fn check_authorization(
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
new file mode 100644
index 00000000000..246a4ce91dc
--- /dev/null
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -0,0 +1,86 @@
+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,
+ }
+}
+
+pub static OPERATIONS_VIEW: [Permission; 6] = [
+ Permission::PaymentRead,
+ Permission::RefundRead,
+ Permission::MandateRead,
+ Permission::DisputeRead,
+ Permission::CustomerRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static OPERATIONS_MANAGE: [Permission; 6] = [
+ Permission::PaymentWrite,
+ Permission::RefundWrite,
+ Permission::MandateWrite,
+ Permission::DisputeWrite,
+ Permission::CustomerWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static CONNECTORS_VIEW: [Permission; 2] = [
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static CONNECTORS_MANAGE: [Permission; 2] = [
+ Permission::MerchantConnectorAccountWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static WORKFLOWS_VIEW: [Permission; 5] = [
+ Permission::RoutingRead,
+ Permission::ThreeDsDecisionManagerRead,
+ Permission::SurchargeDecisionManagerRead,
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static WORKFLOWS_MANAGE: [Permission; 5] = [
+ Permission::RoutingWrite,
+ Permission::ThreeDsDecisionManagerWrite,
+ Permission::SurchargeDecisionManagerWrite,
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static ANALYTICS_VIEW: [Permission; 2] =
+ [Permission::Analytics, Permission::MerchantAccountRead];
+
+pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead];
+
+pub static USERS_MANAGE: [Permission; 2] =
+ [Permission::UsersWrite, Permission::MerchantAccountRead];
+
+pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead];
+
+pub static MERCHANT_DETAILS_MANAGE: [Permission; 4] = [
+ Permission::MerchantAccountWrite,
+ Permission::ApiKeyRead,
+ Permission::ApiKeyWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static ORGANIZATION_MANAGE: [Permission; 2] = [
+ Permission::MerchantAccountCreate,
+ Permission::MerchantAccountRead,
+];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 3e022e8f666..8d436618b32 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -1,6 +1,6 @@
use strum::Display;
-#[derive(PartialEq, Display, Clone, Debug, Copy)]
+#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)]
pub enum Permission {
PaymentRead,
PaymentWrite,
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
new file mode 100644
index 00000000000..6372799f98c
--- /dev/null
+++ b/crates/router/src/services/authorization/roles.rs
@@ -0,0 +1,100 @@
+use std::collections::HashSet;
+
+use common_enums::{PermissionGroup, RoleScope};
+use common_utils::errors::CustomResult;
+
+use super::{permission_groups::get_permissions_vec, permissions::Permission};
+use crate::{core::errors, routes::AppState};
+
+pub mod predefined_roles;
+
+#[derive(Clone)]
+pub struct RoleInfo {
+ role_id: String,
+ role_name: String,
+ groups: Vec<PermissionGroup>,
+ scope: RoleScope,
+ is_invitable: bool,
+ is_deletable: bool,
+ is_updatable: bool,
+ is_internal: bool,
+}
+
+impl RoleInfo {
+ pub fn get_role_id(&self) -> &str {
+ &self.role_id
+ }
+
+ pub fn get_role_name(&self) -> &str {
+ &self.role_name
+ }
+
+ pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> {
+ &self.groups
+ }
+
+ pub fn get_scope(&self) -> RoleScope {
+ self.scope
+ }
+
+ pub fn is_invitable(&self) -> bool {
+ self.is_invitable
+ }
+
+ pub fn is_deletable(&self) -> bool {
+ self.is_deletable
+ }
+
+ pub fn is_internal(&self) -> bool {
+ self.is_internal
+ }
+
+ pub fn is_updatable(&self) -> bool {
+ self.is_updatable
+ }
+
+ pub fn get_permissions_set(&self) -> HashSet<Permission> {
+ self.groups
+ .iter()
+ .flat_map(|group| get_permissions_vec(group).iter().copied())
+ .collect()
+ }
+
+ pub fn check_permission_exists(&self, required_permission: &Permission) -> bool {
+ self.groups
+ .iter()
+ .any(|group| get_permissions_vec(group).contains(required_permission))
+ }
+}
+
+pub async fn get_role_info_from_role_id(
+ state: &AppState,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+) -> CustomResult<RoleInfo, errors::StorageError> {
+ if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
+ Ok(role.clone())
+ } else {
+ state
+ .store
+ .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
+ .await
+ .map(RoleInfo::from)
+ }
+}
+
+impl From<diesel_models::role::Role> for RoleInfo {
+ fn from(role: diesel_models::role::Role) -> Self {
+ Self {
+ role_id: role.role_id,
+ role_name: role.role_name,
+ groups: role.groups.into_iter().map(Into::into).collect(),
+ scope: role.scope,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ }
+ }
+}
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
new file mode 100644
index 00000000000..9accf094ea4
--- /dev/null
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -0,0 +1,210 @@
+use std::collections::HashMap;
+
+use common_enums::{PermissionGroup, RoleScope};
+use once_cell::sync::Lazy;
+
+use super::RoleInfo;
+use crate::consts;
+
+pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
+ let mut roles = HashMap::new();
+ roles.insert(
+ consts::user_role::ROLE_ID_INTERNAL_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::OrganizationManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(),
+ role_name: "Internal Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: true,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
+ role_name: "Internal View Only".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: true,
+ },
+ );
+
+ roles.insert(
+ consts::user_role::ROLE_ID_ORGANIZATION_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::OrganizationManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ role_name: "Organization Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: false,
+ },
+ );
+
+ // MERCHANT ROLES
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
+ role_name: "Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
+ role_name: "View Only".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
+ role_name: "IAM".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
+ role_name: "Developer".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
+ role_name: "Operator".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
+ role_name: "Customer Support".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles
+});
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index ab32febf9b4..263b0e52b8a 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -25,11 +25,7 @@ use crate::{
},
db::StorageInterface,
routes::AppState,
- services::{
- authentication as auth,
- authentication::UserFromToken,
- authorization::{info, predefined_permissions},
- },
+ services::{authentication as auth, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -824,32 +820,6 @@ impl From<info::PermissionInfo> for user_role_api::PermissionInfo {
}
}
-pub struct UserAndRoleJoined(pub storage_user::User, pub UserRole);
-
-impl TryFrom<UserAndRoleJoined> for user_api::UserDetails {
- type Error = ();
- fn try_from(user_and_role: UserAndRoleJoined) -> Result<Self, Self::Error> {
- let status = match user_and_role.1.status {
- UserStatus::Active => user_role_api::UserStatus::Active,
- UserStatus::InvitationSent => user_role_api::UserStatus::InvitationSent,
- };
-
- let role_id = user_and_role.1.role_id;
- let role_name = predefined_permissions::get_role_name_from_id(role_id.as_str())
- .ok_or(())?
- .to_string();
-
- Ok(Self {
- email: user_and_role.0.email,
- name: user_and_role.0.name,
- role_id,
- status,
- role_name,
- last_modified_at: user_and_role.0.last_modified_at,
- })
- }
-}
-
pub enum SignInWithRoleStrategyType {
SingleRole(SignInWithSingleRoleStrategy),
MultipleRoles(SignInWithMultipleRolesStrategy),
@@ -947,3 +917,12 @@ impl SignInWithMultipleRolesStrategy {
))
}
}
+
+impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
+ fn foreign_from(value: UserStatus) -> Self {
+ match value {
+ UserStatus::Active => Self::Active,
+ UserStatus::InvitationSent => Self::InvitationSent,
+ }
+ }
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 86b298822ac..e9b7143a26e 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -9,7 +9,10 @@ use masking::{ExposeInterface, Secret};
use crate::{
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
- services::authentication::{AuthToken, UserFromToken},
+ services::{
+ authentication::{AuthToken, UserFromToken},
+ authorization::roles::{self, RoleInfo},
+ },
types::domain::{self, MerchantAccount, UserFromStorage},
};
@@ -19,7 +22,10 @@ pub mod password;
pub mod sample_data;
impl UserFromToken {
- pub async fn get_merchant_account(&self, state: AppState) -> UserResult<MerchantAccount> {
+ pub async fn get_merchant_account_from_db(
+ &self,
+ state: AppState,
+ ) -> UserResult<MerchantAccount> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -56,6 +62,12 @@ impl UserFromToken {
.change_context(UserErrors::InternalServerError)?;
Ok(user.into())
}
+
+ pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> {
+ roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ }
}
pub async fn generate_jwt_auth_token(
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index b677e89269e..ef69219b4c9 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,29 +1,6 @@
use api_models::user_role as user_role_api;
-use crate::{
- consts,
- services::authorization::{permissions::Permission, predefined_permissions::RoleInfo},
-};
-
-pub fn is_internal_role(role_id: &str) -> bool {
- role_id == consts::user_role::ROLE_ID_INTERNAL_ADMIN
- || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER
-}
-
-pub fn get_role_name_and_permission_response(
- role_info: &RoleInfo,
-) -> Option<(Vec<user_role_api::Permission>, &'static str)> {
- role_info.get_name().map(|name| {
- (
- role_info
- .get_permissions()
- .iter()
- .map(|&per| per.into())
- .collect::<Vec<user_role_api::Permission>>(),
- name,
- )
- })
-}
+use crate::services::authorization::permissions::Permission;
impl From<Permission> for user_role_api::Permission {
fn from(value: Permission) -> Self {
| 2024-02-20T08:57:15Z |
## Description
<!-- Describe your changes in detail -->
This PR will add checks in authorization to check for custom roles.
This PR also add custom roles functionality to apis which were dealing with roles.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 support custom roles.
Closes #3717
Closes #3718
#
### Roles
| Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Operations View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Operations Manage | ✓ | ✓ | | | | ✓ | |
| Connectors View | ✓ | ✓ | ✓ | | ✓ | ✓ | |
| Connectors Manage | ✓ | ✓ | | | | | |
| Workflows View | ✓ | ✓ | ✓ | | | ✓ | |
| Workflows Manage | ✓ | ✓ | | | | | |
| Analytics View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users Manage | ✓ | ✓ | | ✓ | | | |
| Merchant Details View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| MerchantDetails Manage | ✓ | ✓ | | | ✓ | | |
| Organization Manage | ✓ | | | | | | |
### Groups
| Permission | Operations View | Operations Manage | Connectors View | Connectors Manage | Workflows View | Workflows Manage | Analytics View | Users View | Users Manage | Merchant Details View | Merchant Details Manage | Organization Manage |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Payment Read | ✓ | | | | | | | | | | | |
| Payment Write | | ✓ | | | | | | | | | | |
| Refund Read | ✓ | | | | | | | | | | | |
| Refund Write | | ✓ | | | | | | | | | | |
| Dispute Read | ✓ | | | | | | | | | | | |
| Dispute Write | | ✓ | | | | | | | | | | |
| Mandate Read | ✓ | | | | | | | | | | | |
| Mandate Write | | ✓ | | | | | | | | | | |
| Customer Read | ✓ | | | | | | | | | | | |
| Customer Write | | ✓ | | | | | | | | | | |
| Api Key Read | | | | | | | | | | | ✓ | |
| Api Key Write | | | | | | | | | | | ✓ | |
| Merchant Account Read | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Merchant Account Write | | | | | | | | | | | ✓ | |
| Merchant Connector Account Read | | | ✓ | | ✓ | ✓ | | | | | | |
| Merchant Connector Account Write | | | | ✓ | | | | | | | | |
| Routing Read | | | | | ✓ | | | | | | | |
| Routing Write | | | | | | ✓ | | | | | | |
| Analytics | | | | | | | ✓ | | | | | |
| 3DS Manager Read | | | | | ✓ | | | | | | | |
| 3DS Manger Write | | | | | | ✓ | | | | | | |
| Surcharge Decision Manager Read | | | | | ✓ | | | | | | | |
| Surcharge Decision Manager Write | | | | | | ✓ | | | | | | |
| Users Read | | | | | | | | ✓ | | | | |
| Users Write | | | | | | | | | ✓ | | | |
| Merchant Account Create | | | | | | | | | | | | ✓ |
All the APIs will perform according to these roles from now on.
----
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT'
```
```
[
{
"role_id": "merchant_developer",
"permissions": [
"CustomerRead",
"MerchantAccountRead",
"Analytics",
"UsersRead",
"PaymentRead",
"MerchantAccountWrite",
"MerchantConnectorAccountRead",
"ApiKeyRead",
"MandateRead",
"RefundRead",
"DisputeRead",
"ApiKeyWrite"
],
"role_name": "Developer",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"permissions": [
"DisputeWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"CustomerWrite",
"DisputeRead",
"MandateWrite",
"MerchantConnectorAccountRead",
"MerchantAccountRead",
"PaymentWrite",
"MandateRead",
"RefundRead",
"PaymentRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"Analytics",
"UsersRead",
"CustomerRead"
],
"role_name": "Operator",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"PaymentRead",
"MerchantAccountRead",
"Analytics",
"DisputeRead",
"UsersRead",
"MandateRead",
"UsersWrite",
"RefundRead",
"CustomerRead"
],
"role_name": "IAM",
"role_scope": "organization"
},
{
"role_id": "merchant_view_only",
"permissions": [
"MerchantConnectorAccountRead",
"SurchargeDecisionManagerRead",
"UsersRead",
"Analytics",
"ThreeDsDecisionManagerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"RoutingRead",
"CustomerRead",
"RefundRead",
"PaymentRead"
],
"role_name": "View Only",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"RefundRead",
"UsersRead",
"Analytics",
"CustomerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"PaymentRead"
],
"role_name": "Customer Support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"permissions": [
"Analytics",
"RoutingRead",
"ApiKeyRead",
"MerchantAccountRead",
"MandateWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"ThreeDsDecisionManagerWrite",
"CustomerRead",
"MerchantAccountWrite",
"ApiKeyWrite",
"ThreeDsDecisionManagerRead",
"PaymentWrite",
"MerchantConnectorAccountRead",
"PaymentRead",
"MerchantConnectorAccountWrite",
"UsersRead",
"UsersWrite",
"DisputeRead",
"MandateRead",
"DisputeWrite",
"CustomerWrite",
"RoutingWrite",
"RefundRead",
"SurchargeDecisionManagerWrite"
],
"role_name": "Admin",
"role_scope": "organization"
}
]
```
---
```
curl --location 'http://localhost:8080/user/role/role_id' \
--header 'Authorization: Bearer JWT'
```
```
{
"role_id": "rold_id",
"permissions": [ permissions as mentioned above ],
"role_name": "name",
"role_scope": "organization"
}
``` | 4ae28e48cd73a9f96b6ae24babf167824fd182a0 |
### Roles
| Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Operations View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Operations Manage | ✓ | ✓ | | | | ✓ | |
| Connectors View | ✓ | ✓ | ✓ | | ✓ | ✓ | |
| Connectors Manage | ✓ | ✓ | | | | | |
| Workflows View | ✓ | ✓ | ✓ | | | ✓ | |
| Workflows Manage | ✓ | ✓ | | | | | |
| Analytics View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users Manage | ✓ | ✓ | | ✓ | | | |
| Merchant Details View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| MerchantDetails Manage | ✓ | ✓ | | | ✓ | | |
| Organization Manage | ✓ | | | | | | |
### Groups
| Permission | Operations View | Operations Manage | Connectors View | Connectors Manage | Workflows View | Workflows Manage | Analytics View | Users View | Users Manage | Merchant Details View | Merchant Details Manage | Organization Manage |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Payment Read | ✓ | | | | | | | | | | | |
| Payment Write | | ✓ | | | | | | | | | | |
| Refund Read | ✓ | | | | | | | | | | | |
| Refund Write | | ✓ | | | | | | | | | | |
| Dispute Read | ✓ | | | | | | | | | | | |
| Dispute Write | | ✓ | | | | | | | | | | |
| Mandate Read | ✓ | | | | | | | | | | | |
| Mandate Write | | ✓ | | | | | | | | | | |
| Customer Read | ✓ | | | | | | | | | | | |
| Customer Write | | ✓ | | | | | | | | | | |
| Api Key Read | | | | | | | | | | | ✓ | |
| Api Key Write | | | | | | | | | | | ✓ | |
| Merchant Account Read | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Merchant Account Write | | | | | | | | | | | ✓ | |
| Merchant Connector Account Read | | | ✓ | | ✓ | ✓ | | | | | | |
| Merchant Connector Account Write | | | | ✓ | | | | | | | | |
| Routing Read | | | | | ✓ | | | | | | | |
| Routing Write | | | | | | ✓ | | | | | | |
| Analytics | | | | | | | ✓ | | | | | |
| 3DS Manager Read | | | | | ✓ | | | | | | | |
| 3DS Manger Write | | | | | | ✓ | | | | | | |
| Surcharge Decision Manager Read | | | | | ✓ | | | | | | | |
| Surcharge Decision Manager Write | | | | | | ✓ | | | | | | |
| Users Read | | | | | | | | ✓ | | | | |
| Users Write | | | | | | | | | ✓ | | | |
| Merchant Account Create | | | | | | | | | | | | ✓ |
All the APIs will perform according to these roles from now on.
----
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT'
```
```
[
{
"role_id": "merchant_developer",
"permissions": [
"CustomerRead",
"MerchantAccountRead",
"Analytics",
"UsersRead",
"PaymentRead",
"MerchantAccountWrite",
"MerchantConnectorAccountRead",
"ApiKeyRead",
"MandateRead",
"RefundRead",
"DisputeRead",
"ApiKeyWrite"
],
"role_name": "Developer",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"permissions": [
"DisputeWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"CustomerWrite",
"DisputeRead",
"MandateWrite",
"MerchantConnectorAccountRead",
"MerchantAccountRead",
"PaymentWrite",
"MandateRead",
"RefundRead",
"PaymentRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"Analytics",
"UsersRead",
"CustomerRead"
],
"role_name": "Operator",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"PaymentRead",
"MerchantAccountRead",
"Analytics",
"DisputeRead",
"UsersRead",
"MandateRead",
"UsersWrite",
"RefundRead",
"CustomerRead"
],
"role_name": "IAM",
"role_scope": "organization"
},
{
"role_id": "merchant_view_only",
"permissions": [
"MerchantConnectorAccountRead",
"SurchargeDecisionManagerRead",
"UsersRead",
"Analytics",
"ThreeDsDecisionManagerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"RoutingRead",
"CustomerRead",
"RefundRead",
"PaymentRead"
],
"role_name": "View Only",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"RefundRead",
"UsersRead",
"Analytics",
"CustomerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"PaymentRead"
],
"role_name": "Customer Support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"permissions": [
"Analytics",
"RoutingRead",
"ApiKeyRead",
"MerchantAccountRead",
"MandateWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"ThreeDsDecisionManagerWrite",
"CustomerRead",
"MerchantAccountWrite",
"ApiKeyWrite",
"ThreeDsDecisionManagerRead",
"PaymentWrite",
"MerchantConnectorAccountRead",
"PaymentRead",
"MerchantConnectorAccountWrite",
"UsersRead",
"UsersWrite",
"DisputeRead",
"MandateRead",
"DisputeWrite",
"CustomerWrite",
"RoutingWrite",
"RefundRead",
"SurchargeDecisionManagerWrite"
],
"role_name": "Admin",
"role_scope": "organization"
}
]
```
---
```
curl --location 'http://localhost:8080/user/role/role_id' \
--header 'Authorization: Bearer JWT'
```
```
{
"role_id": "rold_id",
"permissions": [ permissions as mentioned above ],
"role_name": "name",
"role_scope": "organization"
}
```
| [
"crates/api_models/src/user_role.rs",
"crates/router/src/analytics.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/routes/user_role.rs",
"crates/router/src/services/authentication.rs",
"crates/router/src/services/auth... | |
juspay/hyperswitch | juspay__hyperswitch-3718 | Bug: feat: integrate custom roles with authz
| diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 215227b91a3..1c4c28aa993 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,3 +1,4 @@
+use common_enums::RoleScope;
use common_utils::pii;
use crate::user::DashboardEntryResponse;
@@ -7,9 +8,10 @@ pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponse {
- pub role_id: &'static str,
+ pub role_id: String,
pub permissions: Vec<Permission>,
- pub role_name: &'static str,
+ pub role_name: String,
+ pub role_scope: RoleScope,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index d126d23c8ae..51fb6ff822b 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -497,7 +497,7 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth(Permission::PaymentWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e7639af3918..5b634920cf6 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -18,10 +18,8 @@ use crate::services::email::types as email_types;
use crate::{
consts,
routes::AppState,
- services::{
- authentication as auth, authorization::predefined_permissions, ApplicationResponse,
- },
- types::domain,
+ services::{authentication as auth, authorization::roles, ApplicationResponse},
+ types::{domain, transformers::ForeignInto},
utils,
};
pub mod dashboard_metadata;
@@ -444,7 +442,16 @@ pub async fn invite_user(
.into());
}
- if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &request.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_invitable() {
return Err(UserErrors::InvalidRoleId.into())
.attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
@@ -626,7 +633,16 @@ async fn handle_invitation(
.into());
}
- if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ let role_info = roles::get_role_info_from_role_id(
+ state,
+ &request.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_invitable() {
return Err(UserErrors::InvalidRoleId.into())
.attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
@@ -915,20 +931,18 @@ pub async fn switch_merchant_id(
.into());
}
- let user_roles = state
- .store
- .list_user_roles_by_user_id(&user_from_token.user_id)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let active_user_roles = user_roles
- .into_iter()
- .filter(|role| role.status == UserStatus::Active)
- .collect::<Vec<_>>();
-
let user = user_from_token.get_user_from_db(&state).await?;
- let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InternalServerError)?;
+
+ let (token, role_id) = if role_info.is_internal() {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -967,6 +981,17 @@ pub async fn switch_merchant_id(
.await?;
(token, user_from_token.role_id)
} else {
+ let user_roles = state
+ .store
+ .list_user_roles_by_user_id(&user_from_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let active_user_roles = user_roles
+ .into_iter()
+ .filter(|role| role.status == UserStatus::Active)
+ .collect::<Vec<_>>();
+
let user_role = active_user_roles
.iter()
.find(|role| role.merchant_id == request.merchant_id)
@@ -1051,17 +1076,47 @@ pub async fn get_users_for_merchant_account(
state: AppState,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::GetUsersResponse> {
- let users = state
+ let users_and_user_roles = state
.store
.find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str())
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("No users for given merchant id")?
+ .attach_printable("No users for given merchant id")?;
+
+ let users_user_roles_and_roles =
+ futures::future::try_join_all(users_and_user_roles.into_iter().map(
+ |(user, user_role)| async {
+ roles::get_role_info_from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_role.merchant_id,
+ &user_role.org_id,
+ )
+ .await
+ .map(|role_info| (user, user_role, role_info))
+ .to_not_found_response(UserErrors::InternalServerError)
+ },
+ ))
+ .await?;
+
+ let user_details_vec = users_user_roles_and_roles
.into_iter()
- .filter_map(|(user, role)| domain::UserAndRoleJoined(user, role).try_into().ok())
+ .map(|(user, user_role, role_info)| {
+ let user = domain::UserFromStorage::from(user);
+ user_api::UserDetails {
+ email: user.get_email(),
+ name: user.get_name(),
+ role_id: user_role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ status: user_role.status.foreign_into(),
+ last_modified_at: user_role.last_modified,
+ }
+ })
.collect();
- Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users)))
+ Ok(ApplicationResponse::Json(user_api::GetUsersResponse(
+ user_details_vec,
+ )))
}
#[cfg(feature = "email")]
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 16047bc3eb7..c2dfd34322c 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -10,7 +10,7 @@ use crate::{
routes::AppState,
services::{
authentication::{self as auth},
- authorization::{info, predefined_permissions},
+ authorization::{info, roles},
ApplicationResponse,
},
types::domain,
@@ -30,58 +30,96 @@ pub async fn get_authorization_info(
))
}
-pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRolesResponse> {
+pub async fn list_invitable_roles(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_role_api::ListRolesResponse> {
+ let predefined_roles_map = roles::predefined_roles::PREDEFINED_ROLES
+ .iter()
+ .filter(|(_, role_info)| role_info.is_invitable())
+ .map(|(role_id, role_info)| user_role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_id.to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
+ let custom_roles_map = state
+ .store
+ .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(roles::RoleInfo::from)
+ .filter(|role_info| role_info.is_invitable())
+ .map(|role_info| user_role_api::RoleInfoResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ });
+
Ok(ApplicationResponse::Json(user_role_api::ListRolesResponse(
- predefined_permissions::PREDEFINED_PERMISSIONS
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .filter_map(|(role_id, role_info)| {
- utils::user_role::get_role_name_and_permission_response(role_info).map(
- |(permissions, role_name)| user_role_api::RoleInfoResponse {
- permissions,
- role_id,
- role_name,
- },
- )
- })
- .collect(),
+ predefined_roles_map.chain(custom_roles_map).collect(),
)))
}
pub async fn get_role(
- _state: AppState,
+ state: AppState,
+ user_from_token: auth::UserFromToken,
role: user_role_api::GetRoleRequest,
) -> UserResponse<user_role_api::RoleInfoResponse> {
- let info = predefined_permissions::PREDEFINED_PERMISSIONS
- .get_key_value(role.role_id.as_str())
- .and_then(|(role_id, role_info)| {
- utils::user_role::get_role_name_and_permission_response(role_info).map(
- |(permissions, role_name)| user_role_api::RoleInfoResponse {
- permissions,
- role_id,
- role_name,
- },
- )
- })
- .ok_or(UserErrors::InvalidRoleId)?;
+ let role_info = roles::get_role_info_from_role_id(
+ &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());
+ }
- Ok(ApplicationResponse::Json(info))
+ let permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(user_role_api::RoleInfoResponse {
+ permissions,
+ role_id: role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }))
}
pub async fn get_role_from_token(
- _state: AppState,
- user: auth::UserFromToken,
+ state: AppState,
+ user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_role_api::Permission>> {
- Ok(ApplicationResponse::Json(
- predefined_permissions::PREDEFINED_PERMISSIONS
- .get(user.role_id.as_str())
- .ok_or(UserErrors::InternalServerError.into())
- .attach_printable("Invalid Role Id in JWT")?
- .get_permissions()
- .iter()
- .map(|&per| per.into())
- .collect(),
- ))
+ let role_info = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?;
+
+ let permissions = role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect();
+
+ Ok(ApplicationResponse::Json(permissions))
}
pub async fn update_user_role(
@@ -89,7 +127,16 @@ pub async fn update_user_role(
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
) -> UserResponse<()> {
- if !predefined_permissions::is_role_updatable(&req.role_id)? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &req.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if !role_info.is_updatable() {
return Err(UserErrors::InvalidRoleOperation.into())
.attach_printable(format!("User role cannot be updated to {}", req.role_id));
}
@@ -110,10 +157,19 @@ pub async fn update_user_role(
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
- if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? {
+ let role_to_be_updated = roles::get_role_info_from_role_id(
+ &state,
+ &user_role_to_be_updated.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ if !role_to_be_updated.is_updatable() {
return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!(
"User role cannot be updated from {}",
- user_role_to_be_updated.role_id
+ role_to_be_updated.get_role_id()
));
}
@@ -270,7 +326,15 @@ pub async fn delete_user_role(
.find(|&role| role.merchant_id == user_from_token.merchant_id.as_str())
{
Some(user_role) => {
- if !predefined_permissions::is_role_deletable(&user_role.role_id)? {
+ let role_info = roles::get_role_info_from_role_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ if !role_info.is_deletable() {
return Err(UserErrors::InvalidDeleteOperation.into())
.attach_printable(format!("role_id = {} is not deletable", user_role.role_id));
}
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a863bc2b662..ea51383c94b 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -291,7 +291,7 @@ pub async fn delete_sample_data(
&http_req,
payload.into_inner(),
sample_data::delete_sample_data_for_user,
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth(Permission::MerchantAccountWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index f84c158332b..63e2ce37269 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -36,7 +36,7 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt
state.clone(),
&req,
(),
- |state, _: (), _| user_role_core::list_roles(state),
+ |state, user, _| user_role_core::list_invitable_roles(state, user),
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -57,7 +57,7 @@ pub async fn get_role(
state.clone(),
&req,
request_payload,
- |state, _: (), req| user_role_core::get_role(state, req),
+ user_role_core::get_role,
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 1004982d292..34153ef6e8f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -503,8 +503,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
Ok((
(),
@@ -532,8 +532,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
Ok((
UserFromToken {
@@ -570,8 +570,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.required_permission, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.required_permission, &permissions)?;
// Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
@@ -613,8 +613,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
let key_store = state
.store()
@@ -663,8 +663,8 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(&payload.role_id)?;
- authorization::check_authorization(&self.0, permissions)?;
+ let permissions = authorization::get_permissions(state, &payload).await?;
+ authorization::check_authorization(&self.0, &permissions)?;
let key_store = state
.store()
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index cad9b1ece62..034773a07ea 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -1,14 +1,50 @@
-use crate::core::errors::{ApiErrorResponse, RouterResult};
+use common_enums::PermissionGroup;
+
+use super::authentication::AuthToken;
+use crate::{
+ core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt},
+ routes::app::AppStateInfo,
+};
pub mod info;
+pub mod permission_groups;
pub mod permissions;
-pub mod predefined_permissions;
+pub mod roles;
+
+pub async fn get_permissions<A>(
+ state: &A,
+ token: &AuthToken,
+) -> RouterResult<Vec<permissions::Permission>>
+where
+ A: AppStateInfo + Sync,
+{
+ if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
+ Ok(get_permissions_from_groups(
+ role_info.get_permission_groups(),
+ ))
+ } else {
+ state
+ .store()
+ .find_role_by_role_id_in_merchant_scope(
+ &token.role_id,
+ &token.merchant_id,
+ &token.org_id,
+ )
+ .await
+ .map(|role| get_permissions_from_groups(&role.groups))
+ .to_not_found_response(ApiErrorResponse::InvalidJwtToken)
+ }
+}
-pub fn get_permissions(role: &str) -> RouterResult<&Vec<permissions::Permission>> {
- predefined_permissions::PREDEFINED_PERMISSIONS
- .get(role)
- .map(|role_info| role_info.get_permissions())
- .ok_or(ApiErrorResponse::InvalidJwtToken.into())
+pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> {
+ groups
+ .iter()
+ .flat_map(|group| {
+ permission_groups::get_permissions_vec(group)
+ .iter()
+ .cloned()
+ })
+ .collect()
}
pub fn check_authorization(
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
new file mode 100644
index 00000000000..246a4ce91dc
--- /dev/null
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -0,0 +1,86 @@
+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,
+ }
+}
+
+pub static OPERATIONS_VIEW: [Permission; 6] = [
+ Permission::PaymentRead,
+ Permission::RefundRead,
+ Permission::MandateRead,
+ Permission::DisputeRead,
+ Permission::CustomerRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static OPERATIONS_MANAGE: [Permission; 6] = [
+ Permission::PaymentWrite,
+ Permission::RefundWrite,
+ Permission::MandateWrite,
+ Permission::DisputeWrite,
+ Permission::CustomerWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static CONNECTORS_VIEW: [Permission; 2] = [
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static CONNECTORS_MANAGE: [Permission; 2] = [
+ Permission::MerchantConnectorAccountWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static WORKFLOWS_VIEW: [Permission; 5] = [
+ Permission::RoutingRead,
+ Permission::ThreeDsDecisionManagerRead,
+ Permission::SurchargeDecisionManagerRead,
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static WORKFLOWS_MANAGE: [Permission; 5] = [
+ Permission::RoutingWrite,
+ Permission::ThreeDsDecisionManagerWrite,
+ Permission::SurchargeDecisionManagerWrite,
+ Permission::MerchantConnectorAccountRead,
+ Permission::MerchantAccountRead,
+];
+
+pub static ANALYTICS_VIEW: [Permission; 2] =
+ [Permission::Analytics, Permission::MerchantAccountRead];
+
+pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead];
+
+pub static USERS_MANAGE: [Permission; 2] =
+ [Permission::UsersWrite, Permission::MerchantAccountRead];
+
+pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead];
+
+pub static MERCHANT_DETAILS_MANAGE: [Permission; 4] = [
+ Permission::MerchantAccountWrite,
+ Permission::ApiKeyRead,
+ Permission::ApiKeyWrite,
+ Permission::MerchantAccountRead,
+];
+
+pub static ORGANIZATION_MANAGE: [Permission; 2] = [
+ Permission::MerchantAccountCreate,
+ Permission::MerchantAccountRead,
+];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 3e022e8f666..8d436618b32 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -1,6 +1,6 @@
use strum::Display;
-#[derive(PartialEq, Display, Clone, Debug, Copy)]
+#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)]
pub enum Permission {
PaymentRead,
PaymentWrite,
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
new file mode 100644
index 00000000000..6372799f98c
--- /dev/null
+++ b/crates/router/src/services/authorization/roles.rs
@@ -0,0 +1,100 @@
+use std::collections::HashSet;
+
+use common_enums::{PermissionGroup, RoleScope};
+use common_utils::errors::CustomResult;
+
+use super::{permission_groups::get_permissions_vec, permissions::Permission};
+use crate::{core::errors, routes::AppState};
+
+pub mod predefined_roles;
+
+#[derive(Clone)]
+pub struct RoleInfo {
+ role_id: String,
+ role_name: String,
+ groups: Vec<PermissionGroup>,
+ scope: RoleScope,
+ is_invitable: bool,
+ is_deletable: bool,
+ is_updatable: bool,
+ is_internal: bool,
+}
+
+impl RoleInfo {
+ pub fn get_role_id(&self) -> &str {
+ &self.role_id
+ }
+
+ pub fn get_role_name(&self) -> &str {
+ &self.role_name
+ }
+
+ pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> {
+ &self.groups
+ }
+
+ pub fn get_scope(&self) -> RoleScope {
+ self.scope
+ }
+
+ pub fn is_invitable(&self) -> bool {
+ self.is_invitable
+ }
+
+ pub fn is_deletable(&self) -> bool {
+ self.is_deletable
+ }
+
+ pub fn is_internal(&self) -> bool {
+ self.is_internal
+ }
+
+ pub fn is_updatable(&self) -> bool {
+ self.is_updatable
+ }
+
+ pub fn get_permissions_set(&self) -> HashSet<Permission> {
+ self.groups
+ .iter()
+ .flat_map(|group| get_permissions_vec(group).iter().copied())
+ .collect()
+ }
+
+ pub fn check_permission_exists(&self, required_permission: &Permission) -> bool {
+ self.groups
+ .iter()
+ .any(|group| get_permissions_vec(group).contains(required_permission))
+ }
+}
+
+pub async fn get_role_info_from_role_id(
+ state: &AppState,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+) -> CustomResult<RoleInfo, errors::StorageError> {
+ if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
+ Ok(role.clone())
+ } else {
+ state
+ .store
+ .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
+ .await
+ .map(RoleInfo::from)
+ }
+}
+
+impl From<diesel_models::role::Role> for RoleInfo {
+ fn from(role: diesel_models::role::Role) -> Self {
+ Self {
+ role_id: role.role_id,
+ role_name: role.role_name,
+ groups: role.groups.into_iter().map(Into::into).collect(),
+ scope: role.scope,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ }
+ }
+}
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
new file mode 100644
index 00000000000..9accf094ea4
--- /dev/null
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -0,0 +1,210 @@
+use std::collections::HashMap;
+
+use common_enums::{PermissionGroup, RoleScope};
+use once_cell::sync::Lazy;
+
+use super::RoleInfo;
+use crate::consts;
+
+pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
+ let mut roles = HashMap::new();
+ roles.insert(
+ consts::user_role::ROLE_ID_INTERNAL_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::OrganizationManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(),
+ role_name: "Internal Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: true,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
+ role_name: "Internal View Only".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: true,
+ },
+ );
+
+ roles.insert(
+ consts::user_role::ROLE_ID_ORGANIZATION_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::OrganizationManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ role_name: "Organization Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: false,
+ is_deletable: false,
+ is_updatable: false,
+ is_internal: false,
+ },
+ );
+
+ // MERCHANT ROLES
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
+ role_name: "Admin".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
+ role_name: "View Only".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
+ role_name: "IAM".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
+ role_name: "Developer".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
+ role_name: "Operator".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
+ role_name: "Customer Support".to_string(),
+ scope: RoleScope::Organization,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles
+});
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index ab32febf9b4..263b0e52b8a 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -25,11 +25,7 @@ use crate::{
},
db::StorageInterface,
routes::AppState,
- services::{
- authentication as auth,
- authentication::UserFromToken,
- authorization::{info, predefined_permissions},
- },
+ services::{authentication as auth, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -824,32 +820,6 @@ impl From<info::PermissionInfo> for user_role_api::PermissionInfo {
}
}
-pub struct UserAndRoleJoined(pub storage_user::User, pub UserRole);
-
-impl TryFrom<UserAndRoleJoined> for user_api::UserDetails {
- type Error = ();
- fn try_from(user_and_role: UserAndRoleJoined) -> Result<Self, Self::Error> {
- let status = match user_and_role.1.status {
- UserStatus::Active => user_role_api::UserStatus::Active,
- UserStatus::InvitationSent => user_role_api::UserStatus::InvitationSent,
- };
-
- let role_id = user_and_role.1.role_id;
- let role_name = predefined_permissions::get_role_name_from_id(role_id.as_str())
- .ok_or(())?
- .to_string();
-
- Ok(Self {
- email: user_and_role.0.email,
- name: user_and_role.0.name,
- role_id,
- status,
- role_name,
- last_modified_at: user_and_role.0.last_modified_at,
- })
- }
-}
-
pub enum SignInWithRoleStrategyType {
SingleRole(SignInWithSingleRoleStrategy),
MultipleRoles(SignInWithMultipleRolesStrategy),
@@ -947,3 +917,12 @@ impl SignInWithMultipleRolesStrategy {
))
}
}
+
+impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
+ fn foreign_from(value: UserStatus) -> Self {
+ match value {
+ UserStatus::Active => Self::Active,
+ UserStatus::InvitationSent => Self::InvitationSent,
+ }
+ }
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 86b298822ac..e9b7143a26e 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -9,7 +9,10 @@ use masking::{ExposeInterface, Secret};
use crate::{
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
- services::authentication::{AuthToken, UserFromToken},
+ services::{
+ authentication::{AuthToken, UserFromToken},
+ authorization::roles::{self, RoleInfo},
+ },
types::domain::{self, MerchantAccount, UserFromStorage},
};
@@ -19,7 +22,10 @@ pub mod password;
pub mod sample_data;
impl UserFromToken {
- pub async fn get_merchant_account(&self, state: AppState) -> UserResult<MerchantAccount> {
+ pub async fn get_merchant_account_from_db(
+ &self,
+ state: AppState,
+ ) -> UserResult<MerchantAccount> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -56,6 +62,12 @@ impl UserFromToken {
.change_context(UserErrors::InternalServerError)?;
Ok(user.into())
}
+
+ pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> {
+ roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ }
}
pub async fn generate_jwt_auth_token(
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index b677e89269e..ef69219b4c9 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,29 +1,6 @@
use api_models::user_role as user_role_api;
-use crate::{
- consts,
- services::authorization::{permissions::Permission, predefined_permissions::RoleInfo},
-};
-
-pub fn is_internal_role(role_id: &str) -> bool {
- role_id == consts::user_role::ROLE_ID_INTERNAL_ADMIN
- || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER
-}
-
-pub fn get_role_name_and_permission_response(
- role_info: &RoleInfo,
-) -> Option<(Vec<user_role_api::Permission>, &'static str)> {
- role_info.get_name().map(|name| {
- (
- role_info
- .get_permissions()
- .iter()
- .map(|&per| per.into())
- .collect::<Vec<user_role_api::Permission>>(),
- name,
- )
- })
-}
+use crate::services::authorization::permissions::Permission;
impl From<Permission> for user_role_api::Permission {
fn from(value: Permission) -> Self {
| 2024-02-20T08:57:15Z |
## Description
<!-- Describe your changes in detail -->
This PR will add checks in authorization to check for custom roles.
This PR also add custom roles functionality to apis which were dealing with roles.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 support custom roles.
Closes #3717
Closes #3718
#
### Roles
| Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Operations View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Operations Manage | ✓ | ✓ | | | | ✓ | |
| Connectors View | ✓ | ✓ | ✓ | | ✓ | ✓ | |
| Connectors Manage | ✓ | ✓ | | | | | |
| Workflows View | ✓ | ✓ | ✓ | | | ✓ | |
| Workflows Manage | ✓ | ✓ | | | | | |
| Analytics View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users Manage | ✓ | ✓ | | ✓ | | | |
| Merchant Details View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| MerchantDetails Manage | ✓ | ✓ | | | ✓ | | |
| Organization Manage | ✓ | | | | | | |
### Groups
| Permission | Operations View | Operations Manage | Connectors View | Connectors Manage | Workflows View | Workflows Manage | Analytics View | Users View | Users Manage | Merchant Details View | Merchant Details Manage | Organization Manage |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Payment Read | ✓ | | | | | | | | | | | |
| Payment Write | | ✓ | | | | | | | | | | |
| Refund Read | ✓ | | | | | | | | | | | |
| Refund Write | | ✓ | | | | | | | | | | |
| Dispute Read | ✓ | | | | | | | | | | | |
| Dispute Write | | ✓ | | | | | | | | | | |
| Mandate Read | ✓ | | | | | | | | | | | |
| Mandate Write | | ✓ | | | | | | | | | | |
| Customer Read | ✓ | | | | | | | | | | | |
| Customer Write | | ✓ | | | | | | | | | | |
| Api Key Read | | | | | | | | | | | ✓ | |
| Api Key Write | | | | | | | | | | | ✓ | |
| Merchant Account Read | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Merchant Account Write | | | | | | | | | | | ✓ | |
| Merchant Connector Account Read | | | ✓ | | ✓ | ✓ | | | | | | |
| Merchant Connector Account Write | | | | ✓ | | | | | | | | |
| Routing Read | | | | | ✓ | | | | | | | |
| Routing Write | | | | | | ✓ | | | | | | |
| Analytics | | | | | | | ✓ | | | | | |
| 3DS Manager Read | | | | | ✓ | | | | | | | |
| 3DS Manger Write | | | | | | ✓ | | | | | | |
| Surcharge Decision Manager Read | | | | | ✓ | | | | | | | |
| Surcharge Decision Manager Write | | | | | | ✓ | | | | | | |
| Users Read | | | | | | | | ✓ | | | | |
| Users Write | | | | | | | | | ✓ | | | |
| Merchant Account Create | | | | | | | | | | | | ✓ |
All the APIs will perform according to these roles from now on.
----
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT'
```
```
[
{
"role_id": "merchant_developer",
"permissions": [
"CustomerRead",
"MerchantAccountRead",
"Analytics",
"UsersRead",
"PaymentRead",
"MerchantAccountWrite",
"MerchantConnectorAccountRead",
"ApiKeyRead",
"MandateRead",
"RefundRead",
"DisputeRead",
"ApiKeyWrite"
],
"role_name": "Developer",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"permissions": [
"DisputeWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"CustomerWrite",
"DisputeRead",
"MandateWrite",
"MerchantConnectorAccountRead",
"MerchantAccountRead",
"PaymentWrite",
"MandateRead",
"RefundRead",
"PaymentRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"Analytics",
"UsersRead",
"CustomerRead"
],
"role_name": "Operator",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"PaymentRead",
"MerchantAccountRead",
"Analytics",
"DisputeRead",
"UsersRead",
"MandateRead",
"UsersWrite",
"RefundRead",
"CustomerRead"
],
"role_name": "IAM",
"role_scope": "organization"
},
{
"role_id": "merchant_view_only",
"permissions": [
"MerchantConnectorAccountRead",
"SurchargeDecisionManagerRead",
"UsersRead",
"Analytics",
"ThreeDsDecisionManagerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"RoutingRead",
"CustomerRead",
"RefundRead",
"PaymentRead"
],
"role_name": "View Only",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"RefundRead",
"UsersRead",
"Analytics",
"CustomerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"PaymentRead"
],
"role_name": "Customer Support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"permissions": [
"Analytics",
"RoutingRead",
"ApiKeyRead",
"MerchantAccountRead",
"MandateWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"ThreeDsDecisionManagerWrite",
"CustomerRead",
"MerchantAccountWrite",
"ApiKeyWrite",
"ThreeDsDecisionManagerRead",
"PaymentWrite",
"MerchantConnectorAccountRead",
"PaymentRead",
"MerchantConnectorAccountWrite",
"UsersRead",
"UsersWrite",
"DisputeRead",
"MandateRead",
"DisputeWrite",
"CustomerWrite",
"RoutingWrite",
"RefundRead",
"SurchargeDecisionManagerWrite"
],
"role_name": "Admin",
"role_scope": "organization"
}
]
```
---
```
curl --location 'http://localhost:8080/user/role/role_id' \
--header 'Authorization: Bearer JWT'
```
```
{
"role_id": "rold_id",
"permissions": [ permissions as mentioned above ],
"role_name": "name",
"role_scope": "organization"
}
``` | 4ae28e48cd73a9f96b6ae24babf167824fd182a0 |
### Roles
| Group | Org Admin | Merchant Admin | Merchant View Only | Merchant IAM Admin | Merchant Developer | Merchant Operator | Merchant Customer Support |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Operations View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Operations Manage | ✓ | ✓ | | | | ✓ | |
| Connectors View | ✓ | ✓ | ✓ | | ✓ | ✓ | |
| Connectors Manage | ✓ | ✓ | | | | | |
| Workflows View | ✓ | ✓ | ✓ | | | ✓ | |
| Workflows Manage | ✓ | ✓ | | | | | |
| Analytics View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Users Manage | ✓ | ✓ | | ✓ | | | |
| Merchant Details View | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| MerchantDetails Manage | ✓ | ✓ | | | ✓ | | |
| Organization Manage | ✓ | | | | | | |
### Groups
| Permission | Operations View | Operations Manage | Connectors View | Connectors Manage | Workflows View | Workflows Manage | Analytics View | Users View | Users Manage | Merchant Details View | Merchant Details Manage | Organization Manage |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| Payment Read | ✓ | | | | | | | | | | | |
| Payment Write | | ✓ | | | | | | | | | | |
| Refund Read | ✓ | | | | | | | | | | | |
| Refund Write | | ✓ | | | | | | | | | | |
| Dispute Read | ✓ | | | | | | | | | | | |
| Dispute Write | | ✓ | | | | | | | | | | |
| Mandate Read | ✓ | | | | | | | | | | | |
| Mandate Write | | ✓ | | | | | | | | | | |
| Customer Read | ✓ | | | | | | | | | | | |
| Customer Write | | ✓ | | | | | | | | | | |
| Api Key Read | | | | | | | | | | | ✓ | |
| Api Key Write | | | | | | | | | | | ✓ | |
| Merchant Account Read | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Merchant Account Write | | | | | | | | | | | ✓ | |
| Merchant Connector Account Read | | | ✓ | | ✓ | ✓ | | | | | | |
| Merchant Connector Account Write | | | | ✓ | | | | | | | | |
| Routing Read | | | | | ✓ | | | | | | | |
| Routing Write | | | | | | ✓ | | | | | | |
| Analytics | | | | | | | ✓ | | | | | |
| 3DS Manager Read | | | | | ✓ | | | | | | | |
| 3DS Manger Write | | | | | | ✓ | | | | | | |
| Surcharge Decision Manager Read | | | | | ✓ | | | | | | | |
| Surcharge Decision Manager Write | | | | | | ✓ | | | | | | |
| Users Read | | | | | | | | ✓ | | | | |
| Users Write | | | | | | | | | ✓ | | | |
| Merchant Account Create | | | | | | | | | | | | ✓ |
All the APIs will perform according to these roles from now on.
----
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT'
```
```
[
{
"role_id": "merchant_developer",
"permissions": [
"CustomerRead",
"MerchantAccountRead",
"Analytics",
"UsersRead",
"PaymentRead",
"MerchantAccountWrite",
"MerchantConnectorAccountRead",
"ApiKeyRead",
"MandateRead",
"RefundRead",
"DisputeRead",
"ApiKeyWrite"
],
"role_name": "Developer",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"permissions": [
"DisputeWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"CustomerWrite",
"DisputeRead",
"MandateWrite",
"MerchantConnectorAccountRead",
"MerchantAccountRead",
"PaymentWrite",
"MandateRead",
"RefundRead",
"PaymentRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"Analytics",
"UsersRead",
"CustomerRead"
],
"role_name": "Operator",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"PaymentRead",
"MerchantAccountRead",
"Analytics",
"DisputeRead",
"UsersRead",
"MandateRead",
"UsersWrite",
"RefundRead",
"CustomerRead"
],
"role_name": "IAM",
"role_scope": "organization"
},
{
"role_id": "merchant_view_only",
"permissions": [
"MerchantConnectorAccountRead",
"SurchargeDecisionManagerRead",
"UsersRead",
"Analytics",
"ThreeDsDecisionManagerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"RoutingRead",
"CustomerRead",
"RefundRead",
"PaymentRead"
],
"role_name": "View Only",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"RefundRead",
"UsersRead",
"Analytics",
"CustomerRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"PaymentRead"
],
"role_name": "Customer Support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"permissions": [
"Analytics",
"RoutingRead",
"ApiKeyRead",
"MerchantAccountRead",
"MandateWrite",
"RefundWrite",
"SurchargeDecisionManagerRead",
"ThreeDsDecisionManagerWrite",
"CustomerRead",
"MerchantAccountWrite",
"ApiKeyWrite",
"ThreeDsDecisionManagerRead",
"PaymentWrite",
"MerchantConnectorAccountRead",
"PaymentRead",
"MerchantConnectorAccountWrite",
"UsersRead",
"UsersWrite",
"DisputeRead",
"MandateRead",
"DisputeWrite",
"CustomerWrite",
"RoutingWrite",
"RefundRead",
"SurchargeDecisionManagerWrite"
],
"role_name": "Admin",
"role_scope": "organization"
}
]
```
---
```
curl --location 'http://localhost:8080/user/role/role_id' \
--header 'Authorization: Bearer JWT'
```
```
{
"role_id": "rold_id",
"permissions": [ permissions as mentioned above ],
"role_name": "name",
"role_scope": "organization"
}
```
| [
"crates/api_models/src/user_role.rs",
"crates/router/src/analytics.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/routes/user_role.rs",
"crates/router/src/services/authentication.rs",
"crates/router/src/services/auth... | |
juspay/hyperswitch | juspay__hyperswitch-3716 | Bug: [BUG] Payment status changes when capture method validation fails
### Bug Description
If a connector doesn't support a particular capture method, confirm call fails and payment status changes to processing.
### Expected Behavior
If a connector doesn't support a particular capture method, confirm call should fail and payment status should remain unchanged.
### Actual Behavior
If a connector doesn't support a particular capture method, confirm call fails and payment status changes to processing.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Create a merchant with stripe connector
2. Create a payment with capture method `manual_multiple` and `cofirm = false`. Status with be `requires_confirmation`.
3. Confirm the payment. Confirm operation will fail and status will change to processing.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 7842678a92a..d7d122c3252 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -72,13 +72,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
- connector
- .connector
- .validate_capture_method(
- self.request.capture_method,
- self.request.payment_method_type,
- )
- .to_payment_failed_response()?;
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
@@ -210,13 +203,19 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
+ connector
+ .connector
+ .validate_capture_method(
+ self.request.capture_method,
+ self.request.payment_method_type,
+ )
+ .to_payment_failed_response()?;
let connector_integration: services::BoxedConnectorIntegration<
'_,
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
-
connector_integration
.execute_pretasks(self, state)
.await
| 2024-02-20T07:43:54Z |
## Description
<!-- Describe your changes in detail -->
Currently capture method validation is done in `decide_flows`(after update_trackers). Because of this intent status changes to `processing`.
In this PR, I have validated capture method in `build_flow_specific_connector_request`(before udpate_trackers). Hence intent status will remain same as before.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 073310c1f671ccbb71cc5c8725eca9771e511589 |
Manual
1. Create a merchant with stripe connector
2. Create a payment without payment_method_data and confirm: false and capture_method : manual_multiple.
<img width="1728" alt="Screenshot 2024-02-20 at 1 03 21 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/78b52bb8-42a6-499d-b588-3d7dc9cdde3c">
3. Confirm the payment
<img width="1728" alt="Screenshot 2024-02-20 at 1 03 37 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c318010e-9245-4adc-9e61-a6fce7c979c3">
4. Do Psyn -> Status remains `requires payment method`
<img width="1728" alt="Screenshot 2024-02-20 at 1 03 48 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/fad5b52e-955a-405c-bc28-685a1ea58686">
| [
"crates/router/src/core/payments/flows/authorize_flow.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3770 | Bug: [FEATURE] : [Bluesnap] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 63ca7750303..201ddc221fc 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -591,7 +591,7 @@ pub struct BluesnapCompletePaymentsRequest {
amount: String,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
- pf_token: String,
+ pf_token: Secret<String>,
three_d_secure: Option<BluesnapThreeDSecureInfo>,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
@@ -627,7 +627,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
meta_data: Vec::<RequestMetadata>::foreign_from(metadata.peek().to_owned()),
});
- let pf_token = item
+ let token = item
.router_data
.request
.redirect_response
@@ -673,7 +673,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
item.router_data.request.get_email()?,
)?,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
- pf_token,
+ pf_token: Secret::new(token),
transaction_meta_data,
})
}
| 2024-02-20T06:20:23Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Bluesnap.
[Bluesnap Doc](https://developers.bluesnap.com/v8976-JSON/reference/bluesnap-payment-api-json)
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for Bluesnap
Sanity test
1. Payment create - 3ds card
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
Response
```
"{\"connector_name\":\"bluesnap\",\"flow\":\"Authorize\",\"request\":\"{\\\"ccNumber\\\":\\\"512345**********\\\",\\\"expDate\\\":\\\"*** alloc::string::String ***\\\"}\",\"masked_response\":\"{\\\"payment_fields_token\\\":\\\"66282e40db55c410dc0689772e171f9d20078a6cd322be81f5b087e550fbbe14_\\\"}\",\"error\":null,\"url\":\"https://sandbox.bluesnap.com/services/2/payment-fields-tokens/prefill\",\"method\":\"POST\",\"payment_id\":\"pay_2QBMshgSXePTr9bKsab1\",\"merchant_id\":\"merchant_1708588739\",\"created_at\":1708588782767,\"request_id\":\"018dcfd3-cdb2-77ea-8cbc-568a736877c5\",\"latency\":1540,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201}", event_type: ConnectorApiLogs, event_id: "018dcfd3-cdb2-77ea-8cbc-568a736877c5", log_type: "event"
```
In logs check for
`topic = "hyperswitch-outgoing-connector-events" ` | 5aae1798257b5ee0c5a62104e4711748cdb5f935 | [
"crates/router/src/connector/bluesnap/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3711 | Bug: [REFACTOR] Refactor process tracker (scheduler) code to increase code reusability and improve logging
### Description
1. The process tracker (scheduler) code includes some amount of repetitive code, which can be extracted out to functions with suitable parameters to accommodate all usages. One such instance is the construction of the `ProcessTrackerNew` type, which is being done manually in multiple places, one of which is:
https://github.com/juspay/hyperswitch/blob/fff780218ac356bb9b599896e766dd45266ac34a/crates/router/src/core/payment_methods/vault.rs#L1013-L1027
There exists the `ProcessTrackerExt::make_process_tracker_new()` method which can be used for the purpose, with suitable modifications.
https://github.com/juspay/hyperswitch/blob/fff780218ac356bb9b599896e766dd45266ac34a/crates/scheduler/src/db/process_tracker.rs#L276-L303
2. The methods from the `ProcessTrackerExt` trait can be moved as methods on `diesel_models::ProcessTracker` and `diesel_models::ProcessTrackerNew` types, and the remaining ones (`reset()`, `retry()` and `finish_with_status()`) can be moved to the `ProcessTrackerInterface` trait.
3. The `business_status` column in the `process_tracker` database table contains high cardinality data due to the business status containing the process tracker ID itself, making it difficult for filtering based on business status. This can be improved by removing the process tracker ID from the business status, thus restricting the number of possible values for the column to a reasonably fixed number and reducing cardinality. (Attaching a screenshot of `business_status` column from a testing environment as of now.)

4. The logging setup within the scheduler can be improved to better indicate about errors occurring when things fail within the scheduler. | diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index 9e649279f24..76e280d6bc0 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -1,8 +1,10 @@
+use common_utils::ext_traits::Encode;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
+use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use crate::{enums as storage_enums, schema::process_tracker};
+use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult};
#[derive(
Clone,
@@ -37,6 +39,13 @@ pub struct ProcessTracker {
pub updated_at: PrimitiveDateTime,
}
+impl ProcessTracker {
+ #[inline(always)]
+ pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool {
+ valid_statuses.iter().any(|&x| x == self.business_status)
+ }
+}
+
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = process_tracker)]
pub struct ProcessTrackerNew {
@@ -55,6 +64,42 @@ pub struct ProcessTrackerNew {
pub updated_at: PrimitiveDateTime,
}
+impl ProcessTrackerNew {
+ pub fn new<T>(
+ process_tracker_id: impl Into<String>,
+ task: impl Into<String>,
+ runner: ProcessTrackerRunner,
+ tag: impl IntoIterator<Item = impl Into<String>>,
+ tracking_data: T,
+ schedule_time: PrimitiveDateTime,
+ ) -> StorageResult<Self>
+ where
+ T: Serialize + std::fmt::Debug,
+ {
+ const BUSINESS_STATUS_PENDING: &str = "Pending";
+
+ let current_time = common_utils::date_time::now();
+ Ok(Self {
+ id: process_tracker_id.into(),
+ name: Some(task.into()),
+ tag: tag.into_iter().map(Into::into).collect(),
+ runner: Some(runner.to_string()),
+ retry_count: 0,
+ schedule_time: Some(schedule_time),
+ rule: String::new(),
+ tracking_data: tracking_data
+ .encode_to_value()
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Failed to serialize process tracker tracking data")?,
+ business_status: String::from(BUSINESS_STATUS_PENDING),
+ status: storage_enums::ProcessTrackerStatus::New,
+ event: vec![],
+ created_at: current_time,
+ updated_at: current_time,
+ })
+ }
+}
+
#[derive(Debug)]
pub enum ProcessTrackerUpdate {
Update {
@@ -165,3 +210,39 @@ pub struct ProcessData {
cache_name: String,
process_tracker: ProcessTracker,
}
+
+#[derive(
+ serde::Serialize,
+ serde::Deserialize,
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ strum::EnumString,
+ strum::Display,
+)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
+pub enum ProcessTrackerRunner {
+ PaymentsSyncWorkflow,
+ RefundWorkflowRouter,
+ DeleteTokenizeDataWorkflow,
+ ApiKeyExpiryWorkflow,
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use common_utils::ext_traits::StringExt;
+
+ use super::ProcessTrackerRunner;
+
+ #[test]
+ fn test_enum_to_string() {
+ let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string();
+ let enum_format: ProcessTrackerRunner =
+ string_format.parse_enum("ProcessTrackerRunner").unwrap();
+ assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow);
+ }
+}
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index 5d376a4d7b1..70d24f0493c 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -596,7 +596,12 @@ impl super::RedisConnectionPool {
None => self.pool.xread_map(count, block, streams, ids).await,
}
.into_report()
- .change_context(errors::RedisError::StreamReadFailed)
+ .map_err(|err| match err.current_context().kind() {
+ RedisErrorKind::NotFound | RedisErrorKind::Parse => {
+ err.change_context(errors::RedisError::StreamEmptyOrNotAvailable)
+ }
+ _ => err.change_context(errors::RedisError::StreamReadFailed),
+ })
}
// Consumer Group API
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index caa69ea1394..c2877535daa 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -14,7 +14,6 @@ use router::{
},
logger, routes,
services::{self, api},
- types::storage::ProcessTrackerExt,
workflows,
};
use router_env::{instrument, tracing};
@@ -22,9 +21,7 @@ use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerAppState,
};
-use serde::{Deserialize, Serialize};
use storage_impl::errors::ApplicationError;
-use strum::EnumString;
use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
@@ -209,17 +206,6 @@ pub async fn deep_health_check_func(
Ok(response)
}
-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
-pub enum PTRunner {
- PaymentsSyncWorkflow,
- RefundWorkflowRouter,
- DeleteTokenizeDataWorkflow,
- #[cfg(feature = "email")]
- ApiKeyExpiryWorkflow,
-}
-
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
@@ -229,25 +215,51 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner {
&'a self,
state: &'a routes::AppState,
process: storage::ProcessTracker,
- ) -> Result<(), ProcessTrackerError> {
- let runner = process.runner.clone().get_required_value("runner")?;
- let runner: Option<PTRunner> = runner.parse_enum("PTRunner").ok();
- let operation: Box<dyn ProcessTrackerWorkflow<routes::AppState>> = match runner {
- Some(PTRunner::PaymentsSyncWorkflow) => {
- Box::new(workflows::payment_sync::PaymentsSyncWorkflow)
- }
- Some(PTRunner::RefundWorkflowRouter) => {
- Box::new(workflows::refund_router::RefundWorkflowRouter)
- }
- Some(PTRunner::DeleteTokenizeDataWorkflow) => {
- Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow)
- }
- #[cfg(feature = "email")]
- Some(PTRunner::ApiKeyExpiryWorkflow) => {
- Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow)
+ ) -> CustomResult<(), ProcessTrackerError> {
+ let runner = process
+ .runner
+ .clone()
+ .get_required_value("runner")
+ .change_context(ProcessTrackerError::MissingRequiredField)
+ .attach_printable("Missing runner field in process information")?;
+ let runner: storage::ProcessTrackerRunner = runner
+ .parse_enum("ProcessTrackerRunner")
+ .change_context(ProcessTrackerError::UnexpectedFlow)
+ .attach_printable("Failed to parse workflow runner name")?;
+
+ let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult<
+ Box<dyn ProcessTrackerWorkflow<routes::AppState>>,
+ ProcessTrackerError,
+ > {
+ match runner {
+ storage::ProcessTrackerRunner::PaymentsSyncWorkflow => {
+ Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow))
+ }
+ storage::ProcessTrackerRunner::RefundWorkflowRouter => {
+ Ok(Box::new(workflows::refund_router::RefundWorkflowRouter))
+ }
+ storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new(
+ workflows::tokenized_data::DeleteTokenizeDataWorkflow,
+ )),
+ storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => {
+ #[cfg(feature = "email")]
+ {
+ Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow))
+ }
+
+ #[cfg(not(feature = "email"))]
+ {
+ Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
+ .attach_printable(
+ "Cannot run API key expiry workflow when email feature is disabled",
+ )
+ }
+ }
}
- _ => Err(ProcessTrackerError::UnexpectedFlow)?,
};
+
+ let operation = get_operation(runner)?;
+
let app_state = &state.clone();
let output = operation.execute_workflow(app_state, process.clone()).await;
match output {
@@ -259,11 +271,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner {
Ok(_) => (),
Err(error) => {
logger::error!(%error, "Failed while handling error");
- let status = process
- .finish_with_status(
- state.get_db().as_scheduler(),
- "GLOBAL_FAILURE".to_string(),
- )
+ let status = state
+ .get_db()
+ .as_scheduler()
+ .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string())
.await;
if let Err(err) = status {
logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE");
@@ -294,18 +305,3 @@ async fn start_scheduler(
)
.await
}
-
-#[cfg(test)]
-mod workflow_tests {
- #![allow(clippy::unwrap_used)]
- use common_utils::ext_traits::StringExt;
-
- use super::PTRunner;
-
- #[test]
- fn test_enum_to_string() {
- let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string();
- let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap();
- assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow)
- }
-}
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 21ef4037d81..851b7ba7571 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -156,18 +156,27 @@ impl super::settings::ApiKeys {
use common_utils::fp_utils::when;
#[cfg(feature = "aws_kms")]
- return when(self.kms_encrypted_hash_key.is_default_or_empty(), || {
+ when(self.kms_encrypted_hash_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"API key hashing key must not be empty when KMS feature is enabled".into(),
))
- });
+ })?;
#[cfg(not(feature = "aws_kms"))]
when(self.hash_key.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"API key hashing key must not be empty".into(),
))
- })
+ })?;
+
+ #[cfg(feature = "email")]
+ when(self.expiry_reminder_days.is_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "API key expiry reminder days must not be empty".into(),
+ ))
+ })?;
+
+ Ok(())
}
}
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 39212ab3814..b3f8931cde5 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -11,8 +11,6 @@ use masking::ExposeInterface;
use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
-#[cfg(feature = "email")]
-use crate::types::storage::enums;
use crate::{
configs::settings,
consts,
@@ -28,7 +26,8 @@ const API_KEY_EXPIRY_TAG: &str = "API_KEY";
#[cfg(feature = "email")]
const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY";
#[cfg(feature = "email")]
-const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW";
+const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner =
+ diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow;
#[cfg(feature = "aws_kms")]
use external_services::aws_kms::decrypt::AwsKmsDecrypt;
@@ -245,15 +244,16 @@ pub async fn add_api_key_expiry_task(
api_key.expires_at.map(|expires_at| {
expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
})
- });
+ })
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Failed to obtain initial process tracker schedule time")?;
- if let Some(schedule_time) = schedule_time {
- if schedule_time <= current_time {
- return Ok(());
- }
+ if schedule_time <= current_time {
+ return Ok(());
}
- let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData {
+ let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
// We need API key expiry too, because we need to decide on the schedule_time in
@@ -261,30 +261,18 @@ pub async fn add_api_key_expiry_task(
api_key_expiry: api_key.expires_at,
expiry_reminder_days: expiry_reminder_days.clone(),
};
- let api_key_expiry_workflow_model = serde_json::to_value(api_key_expiry_tracker)
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| {
- format!("unable to serialize API key expiry tracker: {api_key_expiry_tracker:?}")
- })?;
- let process_tracker_entry = storage::ProcessTrackerNew {
- id: generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()),
- name: Some(String::from(API_KEY_EXPIRY_NAME)),
- tag: vec![String::from(API_KEY_EXPIRY_TAG)],
- runner: Some(String::from(API_KEY_EXPIRY_RUNNER)),
- // Retry count specifies, number of times the current process (email) has been retried.
- // It also acts as an index of expiry_reminder_days vector
- retry_count: 0,
+ let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str());
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ API_KEY_EXPIRY_NAME,
+ API_KEY_EXPIRY_RUNNER,
+ [API_KEY_EXPIRY_TAG],
+ api_key_expiry_tracker,
schedule_time,
- rule: String::new(),
- tracking_data: api_key_expiry_workflow_model,
- business_status: String::from("Pending"),
- status: enums::ProcessTrackerStatus::New,
- event: vec![],
- created_at: current_time,
- updated_at: current_time,
- };
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct API key expiry process tracker task")?;
store
.insert_process(process_tracker_entry)
@@ -293,7 +281,7 @@ pub async fn add_api_key_expiry_task(
.attach_printable_lazy(|| {
format!(
"Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}",
- api_key_expiry_tracker.key_id
+ api_key.key_id
)
})?;
metrics::TASKS_ADDED_COUNT.add(
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index b547027a1c7..622fed0738a 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -17,7 +17,7 @@ use crate::{
routes::metrics,
types::{
api, domain,
- storage::{self, enums, ProcessTrackerExt},
+ storage::{self, enums},
},
utils::StringExt,
};
@@ -998,33 +998,31 @@ pub async fn add_delete_tokenized_data_task(
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
- let runner = "DELETE_TOKENIZE_DATA_WORKFLOW";
- let current_time = common_utils::date_time::now();
- let tracking_data = serde_json::to_value(storage::TokenizeCoreWorkflow {
+ let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
+ let process_tracker_id = format!("{runner}_{lookup_key}");
+ let task = runner.to_string();
+ let tag = ["BASILISK-V3"];
+ let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
- })
- .into_report()
+ };
+ let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0)
+ .await
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Failed to obtain initial process tracker schedule time")?;
+
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ &task,
+ runner,
+ tag,
+ tracking_data,
+ schedule_time,
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| format!("unable to convert into value {lookup_key:?}"))?;
-
- let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0).await;
+ .attach_printable("Failed to construct delete tokenized data process tracker task")?;
- let process_tracker_entry = storage::ProcessTrackerNew {
- id: format!("{runner}_{lookup_key}"),
- name: Some(String::from(runner)),
- tag: vec![String::from("BASILISK-V3")],
- runner: Some(String::from(runner)),
- retry_count: 0,
- schedule_time,
- rule: String::new(),
- tracking_data,
- business_status: String::from("Pending"),
- status: enums::ProcessTrackerStatus::New,
- event: vec![],
- created_at: current_time,
- updated_at: current_time,
- };
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
@@ -1056,10 +1054,11 @@ pub async fn start_tokenize_data_workflow(
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
- let id = tokenize_tracker.id.clone();
- tokenize_tracker
- .clone()
- .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}"))
+ db.as_scheduler()
+ .finish_process_with_business_status(
+ tokenize_tracker.clone(),
+ "COMPLETED_BY_PT".to_string(),
+ )
.await?;
}
Err(err) => {
@@ -1104,7 +1103,11 @@ pub async fn retry_delete_tokenize(
match schedule_time {
Some(s_time) => {
- let retry_schedule = pt.retry(db.as_scheduler(), s_time).await;
+ let retry_schedule = db
+ .as_scheduler()
+ .retry_process(pt, s_time)
+ .await
+ .map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
&metrics::CONTEXT,
1,
@@ -1115,10 +1118,11 @@ pub async fn retry_delete_tokenize(
);
retry_schedule
}
- None => {
- pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string())
- .await
- }
+ None => db
+ .as_scheduler()
+ .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string())
+ .await
+ .map_err(Into::into),
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 7348a2b8f0c..050b0dd4b7b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -25,7 +25,7 @@ use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use router_types::transformers::ForeignFrom;
-use scheduler::{db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as pt_utils};
+use scheduler::utils as pt_utils;
use time;
pub use self::operations::{
@@ -2356,28 +2356,32 @@ pub async fn add_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
-) -> Result<(), sch_errors::ProcessTrackerError> {
+) -> CustomResult<(), errors::StorageError> {
let tracking_data = api::PaymentsRetrieveRequest {
force_sync: true,
merchant_id: Some(payment_attempt.merchant_id.clone()),
resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.attempt_id.clone()),
..Default::default()
};
- let runner = "PAYMENTS_SYNC_WORKFLOW";
+ let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow;
let task = "PAYMENTS_SYNC";
+ let tag = ["SYNC", "PAYMENT"];
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
task,
&payment_attempt.attempt_id,
&payment_attempt.merchant_id,
);
- let process_tracker_entry = <storage::ProcessTracker>::make_process_tracker_new(
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
+ tag,
tracking_data,
schedule_time,
- )?;
+ )
+ .map_err(errors::StorageError::from)
+ .into_report()?;
db.insert_process(process_tracker_entry).await?;
Ok(())
@@ -2388,7 +2392,7 @@ pub async fn reset_process_sync_task(
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
) -> Result<(), errors::ProcessTrackerError> {
- let runner = "PAYMENTS_SYNC_WORKFLOW";
+ let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow;
let task = "PAYMENTS_SYNC";
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
@@ -2400,8 +2404,8 @@ pub async fn reset_process_sync_task(
.find_process_by_id(&process_tracker_id)
.await?
.ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?;
- psync_process
- .reset(db.as_scheduler(), schedule_time)
+ db.as_scheduler()
+ .reset_process(psync_process, schedule_time)
.await?;
Ok(())
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 74a382e63de..31671f2862c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1032,7 +1032,6 @@ where
);
super::add_process_sync_task(&*state.store, payment_attempt, stime)
.await
- .into_report()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding task to process tracker")
} else {
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 4b1c33296e6..06030262fbc 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -19,7 +19,7 @@ use crate::{
self,
api::{self, refunds},
domain,
- storage::{self, enums, ProcessTrackerExt},
+ storage::{self, enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
@@ -798,9 +798,9 @@ pub async fn schedule_refund_execution(
) -> RouterResult<storage::Refund> {
// refunds::RefundResponse> {
let db = &*state.store;
- let runner = "REFUND_WORKFLOW_ROUTER";
+ let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
- let task_id = format!("{}_{}_{}", runner, task, refund.internal_reference_id);
+ let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let refund_process = db
.find_process_by_id(&task_id)
@@ -909,10 +909,13 @@ pub async fn sync_refund_with_gateway_workflow(
];
match response.refund_status {
status if terminal_status.contains(&status) => {
- let id = refund_tracker.id.clone();
- refund_tracker
- .clone()
- .finish_with_status(state.store.as_scheduler(), format!("COMPLETED_BY_PT_{id}"))
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(
+ refund_tracker.clone(),
+ "COMPLETED_BY_PT".to_string(),
+ )
.await?
}
_ => {
@@ -1020,18 +1023,29 @@ pub async fn trigger_refund_execute_workflow(
None,
)
.await?;
- add_refund_sync_task(db, &updated_refund, "REFUND_WORKFLOW_ROUTER").await?;
+ add_refund_sync_task(
+ db,
+ &updated_refund,
+ storage::ProcessTrackerRunner::RefundWorkflowRouter,
+ )
+ .await?;
}
(true, enums::RefundStatus::Pending) => {
// create sync task
- add_refund_sync_task(db, &refund, "REFUND_WORKFLOW_ROUTER").await?;
+ add_refund_sync_task(
+ db,
+ &refund,
+ storage::ProcessTrackerRunner::RefundWorkflowRouter,
+ )
+ .await?;
}
(_, _) => {
//mark task as finished
- let id = refund_tracker.id.clone();
- refund_tracker
- .clone()
- .finish_with_status(db.as_scheduler(), format!("COMPLETED_BY_PT_{id}"))
+ db.as_scheduler()
+ .finish_process_with_business_status(
+ refund_tracker.clone(),
+ "COMPLETED_BY_PT".to_string(),
+ )
.await?;
}
};
@@ -1054,29 +1068,23 @@ pub fn refund_to_refund_core_workflow_model(
pub async fn add_refund_sync_task(
db: &dyn db::StorageInterface,
refund: &storage::Refund,
- runner: &str,
+ runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
- let current_time = common_utils::date_time::now();
- let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund))
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?;
let task = "SYNC_REFUND";
- let process_tracker_entry = storage::ProcessTrackerNew {
- id: format!("{}_{}_{}", runner, task, refund.internal_reference_id),
- name: Some(String::from(task)),
- tag: vec![String::from("REFUND")],
- runner: Some(String::from(runner)),
- retry_count: 0,
- schedule_time: Some(common_utils::date_time::now()),
- rule: String::new(),
- tracking_data: refund_workflow_model,
- business_status: String::from("Pending"),
- status: enums::ProcessTrackerStatus::New,
- event: vec![],
- created_at: current_time,
- updated_at: current_time,
- };
+ let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
+ let schedule_time = common_utils::date_time::now();
+ let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
+ let tag = ["REFUND"];
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ refund_workflow_tracking_data,
+ schedule_time,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct refund sync process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
@@ -1101,29 +1109,23 @@ pub async fn add_refund_sync_task(
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &storage::Refund,
- runner: &str,
+ runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
- let current_time = common_utils::date_time::now();
- let refund_workflow_model = serde_json::to_value(refund_to_refund_core_workflow_model(refund))
- .into_report()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| format!("unable to convert into value {:?}", &refund))?;
- let process_tracker_entry = storage::ProcessTrackerNew {
- id: format!("{}_{}_{}", runner, task, refund.internal_reference_id),
- name: Some(String::from(task)),
- tag: vec![String::from("REFUND")],
- runner: Some(String::from(runner)),
- retry_count: 0,
- schedule_time: Some(common_utils::date_time::now()),
- rule: String::new(),
- tracking_data: refund_workflow_model,
- business_status: String::from("Pending"),
- status: enums::ProcessTrackerStatus::New,
- event: vec![],
- created_at: current_time,
- updated_at: current_time,
- };
+ let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
+ let tag = ["REFUND"];
+ let schedule_time = common_utils::date_time::now();
+ let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ refund_workflow_tracking_data,
+ schedule_time,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct refund execute process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
@@ -1177,7 +1179,11 @@ pub async fn retry_refund_sync_task(
match schedule_time {
Some(s_time) => {
- let retry_schedule = pt.retry(db.as_scheduler(), s_time).await;
+ let retry_schedule = db
+ .as_scheduler()
+ .retry_process(pt, s_time)
+ .await
+ .map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
&metrics::CONTEXT,
1,
@@ -1185,9 +1191,10 @@ pub async fn retry_refund_sync_task(
);
retry_schedule
}
- None => {
- pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string())
- .await
- }
+ None => db
+ .as_scheduler()
+ .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string())
+ .await
+ .map_err(Into::into),
}
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0897deb87e5..599c8a3492b 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1396,15 +1396,6 @@ impl ProcessTrackerInterface for KafkaStore {
.process_tracker_update_process_status_by_ids(task_ids, task_update)
.await
}
- async fn update_process_tracker(
- &self,
- this: storage::ProcessTracker,
- process: storage::ProcessTrackerUpdate,
- ) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
- self.diesel_store
- .update_process_tracker(this, process)
- .await
- }
async fn insert_process(
&self,
@@ -1413,6 +1404,32 @@ impl ProcessTrackerInterface for KafkaStore {
self.diesel_store.insert_process(new).await
}
+ async fn reset_process(
+ &self,
+ this: storage::ProcessTracker,
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store.reset_process(this, schedule_time).await
+ }
+
+ async fn retry_process(
+ &self,
+ this: storage::ProcessTracker,
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store.retry_process(this, schedule_time).await
+ }
+
+ async fn finish_process_with_business_status(
+ &self,
+ this: storage::ProcessTracker,
+ business_status: String,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store
+ .finish_process_with_business_status(this, business_status)
+ .await
+ }
+
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 01decc89c4c..27fd6db8e7e 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -43,7 +43,9 @@ pub use data_models::payments::{
payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
PaymentIntent,
};
-pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate};
+pub use diesel_models::{
+ ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate,
+};
pub use scheduler::db::process_tracker;
pub use self::{
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index b9830c4ebc5..e9e1f323708 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -8,11 +8,7 @@ use crate::{
logger::error,
routes::{metrics, AppState},
services::email::types::ApiKeyExpiryReminder,
- types::{
- api,
- domain::UserEmail,
- storage::{self, ProcessTrackerExt},
- },
+ types::{api, domain::UserEmail, storage},
utils::OptionExt,
};
@@ -90,8 +86,10 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow {
== i32::try_from(tracking_data.expiry_reminder_days.len() - 1)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?
{
- process
- .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string())
+ state
+ .get_db()
+ .as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string())
.await?
}
// If tasks are remaining that has to be scheduled
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index b2296e17f70..92057b08899 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -3,7 +3,6 @@ use error_stack::ResultExt;
use router_env::logger;
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
- db::process_tracker::ProcessTrackerExt,
errors as sch_errors, utils as scheduler_utils, SchedulerAppState,
};
@@ -91,12 +90,10 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow {
];
match &payment_data.payment_attempt.status {
status if terminal_status.contains(status) => {
- let id = process.id.clone();
- process
- .finish_with_status(
- state.get_db().as_scheduler(),
- format!("COMPLETED_BY_PT_{id}"),
- )
+ state
+ .get_db()
+ .as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string())
.await?
}
_ => {
@@ -274,11 +271,12 @@ pub async fn retry_sync_task(
match schedule_time {
Some(s_time) => {
- pt.retry(db.as_scheduler(), s_time).await?;
+ db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
- pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string())
+ db.as_scheduler()
+ .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string())
.await?;
Ok(true)
}
diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs
index ccc943afba3..e069db28da7 100644
--- a/crates/scheduler/src/consumer.rs
+++ b/crates/scheduler/src/consumer.rs
@@ -18,9 +18,8 @@ use uuid::Uuid;
use super::env::logger;
pub use super::workflows::ProcessTrackerWorkflow;
use crate::{
- configs::settings::SchedulerSettings,
- db::process_tracker::{ProcessTrackerExt, ProcessTrackerInterface},
- errors, metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface,
+ configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors,
+ metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface,
};
// Valid consumer business statuses
@@ -59,7 +58,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>(
let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0));
let signal = get_allowed_signals()
.map_err(|error| {
- logger::error!("Signal Handler Error: {:?}", error);
+ logger::error!(?error, "Signal Handler Error");
errors::ProcessTrackerError::ConfigurationError
})
.into_report()
@@ -80,8 +79,8 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>(
pt_utils::consumer_operation_handler(
state.clone(),
settings.clone(),
- |err| {
- logger::error!(%err);
+ |error| {
+ logger::error!(?error, "Failed to perform consumer operation");
},
sync::Arc::clone(&consumer_operation_counter),
workflow_selector,
@@ -94,7 +93,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>(
loop {
shutdown_interval.tick().await;
let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire);
- logger::error!("{}", active_tasks);
+ logger::info!("Active tasks: {active_tasks}");
match active_tasks {
0 => {
logger::info!("Terminating consumer");
@@ -130,7 +129,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>(
.consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID)
.await;
if group_created.is_err() {
- logger::info!("Consumer group already exists");
+ logger::info!("Consumer group {group_name} already exists");
}
let mut tasks = state
@@ -148,7 +147,7 @@ pub async fn consumer_operations<T: SchedulerAppState + 'static>(
pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name);
metrics::TASK_CONSUMED.add(&metrics::CONTEXT, 1, &[]);
- // let runner = workflow_selector(task)?.ok_or(errors::ProcessTrackerError::UnexpectedFlow)?;
+
handler.push(tokio::task::spawn(start_workflow(
state.clone(),
task.clone(),
@@ -171,6 +170,11 @@ pub async fn fetch_consumer_tasks(
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?;
+ // Returning early to avoid execution of database queries when `batches` is empty
+ if batches.is_empty() {
+ return Ok(Vec::new());
+ }
+
let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| {
acc.extend_from_slice(
batch
@@ -209,15 +213,20 @@ pub async fn start_workflow<T>(
process: storage::ProcessTracker,
_pickup_time: PrimitiveDateTime,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug,
-) -> Result<(), errors::ProcessTrackerError>
+) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerAppState,
{
tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string());
- logger::info!("{:?}", process.name.as_ref());
+ logger::info!(pt.name=?process.name, pt.id=%process.id);
+
let res = workflow_selector
.trigger_workflow(&state.clone(), process.clone())
- .await;
+ .await
+ .map_err(|error| {
+ logger::error!(?error, "Failed to trigger workflow");
+ error
+ });
metrics::TASK_PROCESSED.add(&metrics::CONTEXT, 1, &[]);
res
}
@@ -228,7 +237,7 @@ pub async fn consumer_error_handler(
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
- logger::error!(pt.name = ?process.name, pt.id = %process.id, ?error, "ERROR: Failed while executing workflow");
+ logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow");
state
.process_tracker_update_process_status_by_ids(
diff --git a/crates/scheduler/src/consumer/workflows.rs b/crates/scheduler/src/consumer/workflows.rs
index 3b897347bed..3e8a4c8e502 100644
--- a/crates/scheduler/src/consumer/workflows.rs
+++ b/crates/scheduler/src/consumer/workflows.rs
@@ -1,8 +1,9 @@
use async_trait::async_trait;
use common_utils::errors::CustomResult;
pub use diesel_models::process_tracker as storage;
+use router_env::logger;
-use crate::{db::process_tracker::ProcessTrackerExt, errors, SchedulerAppState};
+use crate::{errors, SchedulerAppState};
pub type WorkflowSelectorFn =
fn(&storage::ProcessTracker) -> Result<(), errors::ProcessTrackerError>;
@@ -14,15 +15,16 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync {
&'a self,
_state: &'a T,
_process: storage::ProcessTracker,
- ) -> Result<(), errors::ProcessTrackerError> {
+ ) -> CustomResult<(), errors::ProcessTrackerError> {
Err(errors::ProcessTrackerError::NotImplemented)?
}
+
async fn execute_workflow<'a>(
&'a self,
operation: Box<dyn ProcessTrackerWorkflow<T>>,
state: &'a T,
process: storage::ProcessTracker,
- ) -> Result<(), errors::ProcessTrackerError>
+ ) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerAppState,
{
@@ -35,16 +37,18 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync {
.await
{
Ok(_) => (),
- Err(_error) => {
- // logger::error!(%error, "Failed while handling error");
- let status = process
- .finish_with_status(
- state.get_db().as_scheduler(),
- "GLOBAL_FAILURE".to_string(),
- )
+ Err(error) => {
+ logger::error!(
+ ?error,
+ "Failed to handle process tracker workflow execution error"
+ );
+ let status = app_state
+ .get_db()
+ .as_scheduler()
+ .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string())
.await;
- if let Err(_err) = status {
- // logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE");
+ if let Err(error) = status {
+ logger::error!(?error, "Failed to update process business status");
}
}
},
@@ -55,7 +59,7 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync {
#[async_trait]
pub trait ProcessTrackerWorkflow<T>: Send + Sync {
- // The core execution of the workflow
+ /// The core execution of the workflow
async fn execute_workflow<'a>(
&'a self,
_state: &'a T,
@@ -63,9 +67,11 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync {
) -> Result<(), errors::ProcessTrackerError> {
Err(errors::ProcessTrackerError::NotImplemented)?
}
- // Callback function after successful execution of the `execute_workflow`
+
+ /// Callback function after successful execution of the `execute_workflow`
async fn success_handler<'a>(&'a self, _state: &'a T, _process: storage::ProcessTracker) {}
- // Callback function after error received from `execute_workflow`
+
+ /// Callback function after error received from `execute_workflow`
async fn error_handler<'a>(
&'a self,
_state: &'a T,
@@ -75,18 +81,3 @@ pub trait ProcessTrackerWorkflow<T>: Send + Sync {
Err(errors::ProcessTrackerError::NotImplemented)?
}
}
-
-// #[cfg(test)]
-// mod workflow_tests {
-// #![allow(clippy::unwrap_used)]
-// use common_utils::ext_traits::StringExt;
-
-// use super::PTRunner;
-
-// #[test]
-// fn test_enum_to_string() {
-// let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string();
-// let enum_format: PTRunner = string_format.parse_enum("PTRunner").unwrap();
-// assert_eq!(enum_format, PTRunner::PaymentsSyncWorkflow)
-// }
-// }
diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs
index 728c146a64e..ac20d4b293f 100644
--- a/crates/scheduler/src/db/process_tracker.rs
+++ b/crates/scheduler/src/db/process_tracker.rs
@@ -2,11 +2,10 @@ use common_utils::errors::CustomResult;
pub use diesel_models as storage;
use diesel_models::enums as storage_enums;
use error_stack::{IntoReport, ResultExt};
-use serde::Serialize;
use storage_impl::{connection, errors, mock_db::MockDb};
use time::PrimitiveDateTime;
-use crate::{errors as sch_errors, metrics, scheduler::Store, SchedulerInterface};
+use crate::{metrics, scheduler::Store};
#[async_trait::async_trait]
pub trait ProcessTrackerInterface: Send + Sync + 'static {
@@ -32,17 +31,30 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static {
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError>;
- async fn update_process_tracker(
- &self,
- this: storage::ProcessTracker,
- process: storage::ProcessTrackerUpdate,
- ) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
+ async fn reset_process(
+ &self,
+ this: storage::ProcessTracker,
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError>;
+
+ async fn retry_process(
+ &self,
+ this: storage::ProcessTracker,
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError>;
+
+ async fn finish_process_with_business_status(
+ &self,
+ this: storage::ProcessTracker,
+ business_status: String,
+ ) -> CustomResult<(), errors::StorageError>;
+
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
@@ -120,16 +132,58 @@ impl ProcessTrackerInterface for Store {
.into_report()
}
- async fn update_process_tracker(
+ async fn reset_process(
&self,
this: storage::ProcessTracker,
- process: storage::ProcessTrackerUpdate,
- ) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- this.update(&conn, process)
- .await
- .map_err(Into::into)
- .into_report()
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.update_process(
+ this,
+ storage::ProcessTrackerUpdate::StatusRetryUpdate {
+ status: storage_enums::ProcessTrackerStatus::New,
+ retry_count: 0,
+ schedule_time,
+ },
+ )
+ .await?;
+ Ok(())
+ }
+
+ async fn retry_process(
+ &self,
+ this: storage::ProcessTracker,
+ schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
+ metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]);
+ let retry_count = this.retry_count + 1;
+ self.update_process(
+ this,
+ storage::ProcessTrackerUpdate::StatusRetryUpdate {
+ status: storage_enums::ProcessTrackerStatus::Pending,
+ retry_count,
+ schedule_time,
+ },
+ )
+ .await?;
+ Ok(())
+ }
+
+ async fn finish_process_with_business_status(
+ &self,
+ this: storage::ProcessTracker,
+ business_status: String,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.update_process(
+ this,
+ storage::ProcessTrackerUpdate::StatusUpdate {
+ status: storage_enums::ProcessTrackerStatus::Finish,
+ business_status: Some(business_status),
+ },
+ )
+ .await
+ .attach_printable("Failed to update business status of process")?;
+ metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]);
+ Ok(())
}
async fn process_tracker_update_process_status_by_ids(
@@ -215,143 +269,39 @@ impl ProcessTrackerInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
- async fn update_process_tracker(
+ async fn reset_process(
&self,
_this: storage::ProcessTracker,
- _process: storage::ProcessTrackerUpdate,
- ) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
+ _schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
- async fn process_tracker_update_process_status_by_ids(
+ async fn retry_process(
&self,
- _task_ids: Vec<String>,
- _task_update: storage::ProcessTrackerUpdate,
- ) -> CustomResult<usize, errors::StorageError> {
+ _this: storage::ProcessTracker,
+ _schedule_time: PrimitiveDateTime,
+ ) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
-}
-
-#[async_trait::async_trait]
-pub trait ProcessTrackerExt {
- fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool;
-
- fn make_process_tracker_new<'a, T>(
- process_tracker_id: String,
- task: &'a str,
- runner: &'a str,
- tracking_data: T,
- schedule_time: PrimitiveDateTime,
- ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError>
- where
- T: Serialize;
-
- async fn reset(
- self,
- db: &dyn SchedulerInterface,
- schedule_time: PrimitiveDateTime,
- ) -> Result<(), sch_errors::ProcessTrackerError>;
-
- async fn retry(
- self,
- db: &dyn SchedulerInterface,
- schedule_time: PrimitiveDateTime,
- ) -> Result<(), sch_errors::ProcessTrackerError>;
-
- async fn finish_with_status(
- self,
- db: &dyn SchedulerInterface,
- status: String,
- ) -> Result<(), sch_errors::ProcessTrackerError>;
-}
-
-#[async_trait::async_trait]
-impl ProcessTrackerExt for storage::ProcessTracker {
- fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool {
- valid_statuses.iter().any(|x| x == &self.business_status)
- }
-
- fn make_process_tracker_new<'a, T>(
- process_tracker_id: String,
- task: &'a str,
- runner: &'a str,
- tracking_data: T,
- schedule_time: PrimitiveDateTime,
- ) -> Result<storage::ProcessTrackerNew, sch_errors::ProcessTrackerError>
- where
- T: Serialize,
- {
- let current_time = common_utils::date_time::now();
- Ok(storage::ProcessTrackerNew {
- id: process_tracker_id,
- name: Some(String::from(task)),
- tag: vec![String::from("SYNC"), String::from("PAYMENT")],
- runner: Some(String::from(runner)),
- retry_count: 0,
- schedule_time: Some(schedule_time),
- rule: String::new(),
- tracking_data: serde_json::to_value(tracking_data)
- .map_err(|_| sch_errors::ProcessTrackerError::SerializationFailed)?,
- business_status: String::from("Pending"),
- status: storage_enums::ProcessTrackerStatus::New,
- event: vec![],
- created_at: current_time,
- updated_at: current_time,
- })
- }
- async fn reset(
- self,
- db: &dyn SchedulerInterface,
- schedule_time: PrimitiveDateTime,
- ) -> Result<(), sch_errors::ProcessTrackerError> {
- db.update_process_tracker(
- self.clone(),
- storage::ProcessTrackerUpdate::StatusRetryUpdate {
- status: storage_enums::ProcessTrackerStatus::New,
- retry_count: 0,
- schedule_time,
- },
- )
- .await?;
- Ok(())
- }
-
- async fn retry(
- self,
- db: &dyn SchedulerInterface,
- schedule_time: PrimitiveDateTime,
- ) -> Result<(), sch_errors::ProcessTrackerError> {
- metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]);
- db.update_process_tracker(
- self.clone(),
- storage::ProcessTrackerUpdate::StatusRetryUpdate {
- status: storage_enums::ProcessTrackerStatus::Pending,
- retry_count: self.retry_count + 1,
- schedule_time,
- },
- )
- .await?;
- Ok(())
+ async fn finish_process_with_business_status(
+ &self,
+ _this: storage::ProcessTracker,
+ _business_status: String,
+ ) -> CustomResult<(), errors::StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
}
- async fn finish_with_status(
- self,
- db: &dyn SchedulerInterface,
- status: String,
- ) -> Result<(), sch_errors::ProcessTrackerError> {
- db.update_process(
- self,
- storage::ProcessTrackerUpdate::StatusUpdate {
- status: storage_enums::ProcessTrackerStatus::Finish,
- business_status: Some(status),
- },
- )
- .await
- .attach_printable("Failed while updating status of the process")?;
- metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]);
- Ok(())
+ async fn process_tracker_update_process_status_by_ids(
+ &self,
+ _task_ids: Vec<String>,
+ _task_update: storage::ProcessTrackerUpdate,
+ ) -> CustomResult<usize, errors::StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
}
}
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index f6a340e9d59..174efd637e9 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -8,7 +8,7 @@ use diesel_models::enums::{self, ProcessTrackerStatus};
pub use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use redis_interface::{RedisConnectionPool, RedisEntryId};
-use router_env::opentelemetry;
+use router_env::{instrument, opentelemetry, tracing};
use uuid::Uuid;
use super::{
@@ -178,7 +178,7 @@ pub async fn get_batches(
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> {
- let response = conn
+ let response = match conn
.stream_read_with_options(
stream_name,
RedisEntryId::UndeliveredEntryID,
@@ -188,10 +188,20 @@ pub async fn get_batches(
Some((group_name, consumer_name)),
)
.await
- .map_err(|error| {
- logger::warn!(%error, "Warning: finding batch in stream");
- error.change_context(errors::ProcessTrackerError::BatchNotFound)
- })?;
+ {
+ Ok(response) => response,
+ Err(error) => {
+ if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
+ error.current_context()
+ {
+ logger::debug!("No batches processed as stream is empty");
+ return Ok(Vec::new());
+ } else {
+ return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound));
+ }
+ }
+ };
+
metrics::BATCHES_CONSUMED.add(&metrics::CONTEXT, 1, &[]);
let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| {
@@ -217,13 +227,13 @@ pub async fn get_batches(
conn.stream_acknowledge_entries(stream_name, group_name, entry_ids.clone())
.await
.map_err(|error| {
- logger::error!(%error, "Error acknowledging batch in stream");
+ logger::error!(?error, "Error acknowledging batch in stream");
error.change_context(errors::ProcessTrackerError::BatchUpdateFailed)
})?;
conn.stream_delete_entries(stream_name, entry_ids.clone())
.await
.map_err(|error| {
- logger::error!(%error, "Error deleting batch from stream");
+ logger::error!(?error, "Error deleting batch from stream");
error.change_context(errors::ProcessTrackerError::BatchDeleteFailed)
})?;
@@ -231,7 +241,7 @@ pub async fn get_batches(
}
pub fn get_process_tracker_id<'a>(
- runner: &'a str,
+ runner: storage::ProcessTrackerRunner,
task_name: &'a str,
txn_id: &'a str,
merchant_id: &'a str,
@@ -243,6 +253,7 @@ pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime
delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into())))
}
+#[instrument(skip_all)]
pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>(
state: T,
settings: sync::Arc<SchedulerSettings>,
| 2024-02-19T19:59:37Z |
## Description
<!-- Describe your changes in detail -->
This PR contains changes to address the problems listed in #3711, namely:
1. Updates `ProcessTrackerExt::make_process_tracker_new()` method to accept a `tag` parameter in order to increase reusability.
2. Moves the `PTRunner` enum to the `diesel_models::process_tracker` module and renames it as `ProcessTrackerRunner`.
3. Makes use of the `ProcessTrackerExt::make_process_tracker_new()` method to construct all instances of `ProcessTrackerNew` within the codebase.
4. Move `ProcessTrackerExt::make_process_tracker_new()` as `ProcessTrackerNew::new()` method.
5. Removes a redundant `update_process_tracker()` method from the `ProcessTrackerInterface` trait in favor of the `update_process()` method from the same trait.
6. Moves the `reset()`, `retry()` and `finish_with_status()` methods from `ProcessTrackerExt` trait to `ProcessTrackerInterface` trait.
7. Update the business status insertion/updation logic to reduce cardinality of the business status column in the resulting process tracker table.
8. Adds/updates logs that would be displayed when specific parts of the scheduler execution fails.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Resolves #3711.
#
### Sanity testing of process tracker with payments sync workflow
1. Disable any incoming payment webhooks from the connector with which a payment will be created in the next step.
2. Create a payment with a connector such that the payment reaches the processing state.
3. Check if the process tracker performs a payments sync successfully and updates the status of the payment to either succeeded or failed:
1. Immediately after creating the payment, you should see an entry in the `process_tracker` table with status `new` and business status `Pending`. The task should be scheduled to execute in a few minutes' time from the time of creation of the payment.
2. Once the producer picks up the task, the status should be `processing` and business status remains same.
3. Once the consumer picks up the task, the status should be `process_started` and business status remains same. If the execution of the task completes quickly enough, you might not notice this status transition.
4. Once the consumer has successfully completed the execution of the task, the final status should be `finish` and business status should be `COMPLETED_BY_PT`.
5. If you perform a payments retrieve after the execution of the task has completed, the payment intent's status should now be updated to a succeeded or failed state, as reported by the connector.
### Screenshots from local manual testing
- Screenshot of process tracker entry in database after successful payment sync workflow execution:
<img width="1200" alt="Screenshot of process tracker entry in database" src="https://github.com/juspay/hyperswitch/assets/22217505/7be2948e-e666-4d02-9003-306512c39d5c">
As for the logs, I've verified that logs are shown when there are consumer workflow execution errors:
- Screenshot of error log displayed when the process tracker entry in the database table contains a value that does not correspond to a valid `ProcessTrackerRunner` variant:
<img width="800" alt="Screenshot of error indicating invalid workflow runner name" src="https://github.com/juspay/hyperswitch/assets/22217505/2057e83d-873d-4d5c-8d79-b3e349012155">
This can be used to identify if an old version of the `consumer` service is deployed with a relatively newer version of the `router` service with newer process tracker workflows.
- Screenshot of error log displayed when the `email` feature is enabled on the `router` service, but disabled on the `consumer` service:
<img width="800" alt="Screenshot of error indicating email feature being disabled" src="https://github.com/juspay/hyperswitch/assets/22217505/cca4ab95-9ae6-4eb0-820d-3232f0fc1f3f">
This does not typically occur in our hosted environments, since we run builds/images with most (if not all) features enabled. | fff780218ac356bb9b599896e766dd45266ac34a |
Most of the changes involve moving existing code around, which should not affect the functioning of the scheduler, which I've verified by confirming the correct functioning of the payment sync workflow: the workflow now successfully completes with a business status of `COMPLETED_BY_PT` (only) instead of also including the process tracker ID in the business status.
### Sanity testing of process tracker with payments sync workflow
1. Disable any incoming payment webhooks from the connector with which a payment will be created in the next step.
2. Create a payment with a connector such that the payment reaches the processing state.
3. Check if the process tracker performs a payments sync successfully and updates the status of the payment to either succeeded or failed:
1. Immediately after creating the payment, you should see an entry in the `process_tracker` table with status `new` and business status `Pending`. The task should be scheduled to execute in a few minutes' time from the time of creation of the payment.
2. Once the producer picks up the task, the status should be `processing` and business status remains same.
3. Once the consumer picks up the task, the status should be `process_started` and business status remains same. If the execution of the task completes quickly enough, you might not notice this status transition.
4. Once the consumer has successfully completed the execution of the task, the final status should be `finish` and business status should be `COMPLETED_BY_PT`.
5. If you perform a payments retrieve after the execution of the task has completed, the payment intent's status should now be updated to a succeeded or failed state, as reported by the connector.
### Screenshots from local manual testing
- Screenshot of process tracker entry in database after successful payment sync workflow execution:
<img width="1200" alt="Screenshot of process tracker entry in database" src="https://github.com/juspay/hyperswitch/assets/22217505/7be2948e-e666-4d02-9003-306512c39d5c">
As for the logs, I've verified that logs are shown when there are consumer workflow execution errors:
- Screenshot of error log displayed when the process tracker entry in the database table contains a value that does not correspond to a valid `ProcessTrackerRunner` variant:
<img width="800" alt="Screenshot of error indicating invalid workflow runner name" src="https://github.com/juspay/hyperswitch/assets/22217505/2057e83d-873d-4d5c-8d79-b3e349012155">
This can be used to identify if an old version of the `consumer` service is deployed with a relatively newer version of the `router` service with newer process tracker workflows.
- Screenshot of error log displayed when the `email` feature is enabled on the `router` service, but disabled on the `consumer` service:
<img width="800" alt="Screenshot of error indicating email feature being disabled" src="https://github.com/juspay/hyperswitch/assets/22217505/cca4ab95-9ae6-4eb0-820d-3232f0fc1f3f">
This does not typically occur in our hosted environments, since we run builds/images with most (if not all) features enabled.
| [
"crates/diesel_models/src/process_tracker.rs",
"crates/redis_interface/src/commands.rs",
"crates/router/src/bin/scheduler.rs",
"crates/router/src/configs/validations.rs",
"crates/router/src/core/api_keys.rs",
"crates/router/src/core/payment_methods/vault.rs",
"crates/router/src/core/payments.rs",
"cra... | |
juspay/hyperswitch | juspay__hyperswitch-3706 | Bug: feat(invite): Send email to user if user already exist
| diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index d7150af9bc7..ec3e2dce9b2 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -10,11 +10,12 @@ use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
- AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,
- DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest,
- InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest,
- SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
- UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest,
+ AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
+ CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse,
+ InviteUserRequest, InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest,
+ SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
+ SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate,
+ VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -57,6 +58,7 @@ common_utils::impl_misc_api_event_type!(
ReInviteUserRequest,
VerifyEmailRequest,
SendVerifyEmailRequest,
+ AcceptInviteFromEmailRequest,
SignInResponse,
UpdateUserAccountDetailsRequest
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index c3e6908c733..8f77f72aad5 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -118,6 +118,11 @@ pub struct ReInviteUserRequest {
pub email: pii::Email,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct AcceptInviteFromEmailRequest {
+ pub token: Secret<String>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchMerchantIdRequest {
pub merchant_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e7639af3918..dfcfe8dbcd4 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -464,7 +464,7 @@ pub async fn invite_user(
.store
.insert_user_role(UserRoleNew {
user_id: invitee_user_from_db.get_user_id().to_owned(),
- merchant_id: user_from_token.merchant_id,
+ merchant_id: user_from_token.merchant_id.clone(),
role_id: request.role_id,
org_id: user_from_token.org_id,
status: {
@@ -488,8 +488,34 @@ pub async fn invite_user(
}
})?;
+ let is_email_sent;
+ #[cfg(feature = "email")]
+ {
+ let email_contents = email_types::InviteRegisteredUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id,
+ };
+
+ is_email_sent = state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await
+ .map(|email_result| logger::info!(?email_result))
+ .map_err(|email_result| logger::error!(?email_result))
+ .is_ok();
+ }
+ #[cfg(not(feature = "email"))]
+ {
+ is_email_sent = false;
+ }
Ok(ApplicationResponse::Json(user_api::InviteUserResponse {
- is_email_sent: false,
+ is_email_sent,
password: None,
}))
} else if invitee_user
@@ -681,9 +707,37 @@ async fn handle_existing_user_invitation(
}
})?;
+ let is_email_sent;
+ #[cfg(feature = "email")]
+ {
+ let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
+ let email_contents = email_types::InviteRegisteredUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id.clone(),
+ };
+
+ is_email_sent = state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await
+ .map(|email_result| logger::info!(?email_result))
+ .map_err(|email_result| logger::error!(?email_result))
+ .is_ok();
+ }
+ #[cfg(not(feature = "email"))]
+ {
+ is_email_sent = false;
+ }
+
Ok(InviteMultipleUserResponse {
email: request.email.clone(),
- is_email_sent: false,
+ is_email_sent,
password: None,
error: None,
})
@@ -840,6 +894,67 @@ pub async fn resend_invite(
Ok(ApplicationResponse::StatusOk)
}
+#[cfg(feature = "email")]
+pub async fn accept_invite_from_email(
+ state: AppState,
+ request: user_api::AcceptInviteFromEmailRequest,
+) -> UserResponse<user_api::DashboardEntryResponse> {
+ let token = request.token.expose();
+
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
+ let user: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(email_token.get_email())
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let merchant_id = email_token
+ .get_merchant_id()
+ .ok_or(UserErrors::InternalServerError)?;
+
+ let update_status_result = state
+ .store
+ .update_user_role_by_user_id_merchant_id(
+ user.get_user_id(),
+ merchant_id,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user.get_user_id().to_string(),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .update_user_by_user_id(user.get_user_id(), storage_user::UserUpdate::VerifyUser)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ let token =
+ utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?;
+
+ Ok(ApplicationResponse::Json(
+ utils::user::get_dashboard_entry_response(
+ &state,
+ user_from_db,
+ update_status_result,
+ token,
+ )?,
+ ))
+}
+
pub async fn create_internal_user(
state: AppState,
request: user_api::CreateInternalUserRequest,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 41881c60ff7..e9e4b67c782 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1020,7 +1020,11 @@ impl User {
web::resource("/verify_email_request")
.route(web::post().to(verify_email_request)),
)
- .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite)));
+ .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite)))
+ .service(
+ web::resource("/accept_invite_from_email")
+ .route(web::post().to(accept_invite_from_email)),
+ );
}
#[cfg(not(feature = "email"))]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9393e8ae212..efdbb57b33c 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -188,6 +188,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmailWithoutInviteChecks
| Flow::VerifyEmail
+ | Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails => Self::User,
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a863bc2b662..dacfe0e59a6 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -420,6 +420,25 @@ pub async fn resend_invite(
.await
}
+#[cfg(feature = "email")]
+pub async fn accept_invite_from_email(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Json<user_api::AcceptInviteFromEmailRequest>,
+) -> HttpResponse {
+ let flow = Flow::AcceptInviteFromEmail;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ |state, _, request_payload| user_core::accept_invite_from_email(state, request_payload),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "email")]
pub async fn verify_email_without_invite_checks(
state: web::Data<AppState>,
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 598a2620937..46cfad08783 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -28,6 +28,10 @@ pub enum EmailBody {
link: String,
user_name: String,
},
+ AcceptInviteFromEmail {
+ link: String,
+ user_name: String,
+ },
BizEmailProd {
user_name: String,
poc_email: String,
@@ -78,6 +82,14 @@ pub mod html {
link = link
)
}
+ // TODO: Change the linked html for accept invite from email
+ EmailBody::AcceptInviteFromEmail { link, user_name } => {
+ format!(
+ include_str!("assets/invite.html"),
+ username = user_name,
+ link = link
+ )
+ }
EmailBody::ReconActivation { user_name } => {
format!(
include_str!("assets/recon_activation.html"),
@@ -287,6 +299,42 @@ impl EmailData for InviteUser {
})
}
}
+pub struct InviteRegisteredUser {
+ pub recipient_email: domain::UserEmail,
+ pub user_name: domain::UserName,
+ pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub subject: &'static str,
+ pub merchant_id: String,
+}
+
+#[async_trait::async_trait]
+impl EmailData for InviteRegisteredUser {
+ async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
+ let token = EmailToken::new_token(
+ self.recipient_email.clone(),
+ Some(self.merchant_id.clone()),
+ &self.settings,
+ )
+ .await
+ .change_context(EmailError::TokenGenerationFailure)?;
+
+ let invite_user_link = get_link_with_token(
+ &self.settings.email.base_url,
+ token,
+ "accept_invite_from_email",
+ );
+ let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
+ link: invite_user_link,
+ user_name: self.user_name.clone().get_secret().expose(),
+ });
+
+ Ok(EmailContents {
+ subject: self.subject.to_string(),
+ body: external_services::email::IntermediateString::new(body),
+ recipient: self.recipient_email.clone().into_inner(),
+ })
+ }
+}
pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 6649b89911a..994b134520e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -339,6 +339,8 @@ pub enum Flow {
InviteMultipleUser,
/// Reinvite user
ReInviteUser,
+ /// Accept invite from email
+ AcceptInviteFromEmail,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
| 2024-02-19T13:29:01Z |
## Description
<!-- Describe your changes in detail -->
This PR will send an email to the user if the user already exist
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
If the user was already exists then we were directly activating the user. With this PR it will send an email to the user and it will redirect it directly to the dashboard
# | deec8b4eb5493b072eaef0352a735748979cd95d | 1.
Request:
```
curl --location 'http://localhost:8080/user/user/invite_user \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of org_admin user' \
--data-raw '{
"email": "email of the user who already signed up“,
"name":"some name",
"role_id":"some valid role"
}
```
Response
```
{"is_email_sent":true,"password":null}
```
2. Email will be sent to the user email
3. Copy token from the link
4.
Request
```
curl --location 'http://localhost:8080/user/activate_from_email\
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of org_admin user' \
--data-raw '{
"token": copied token
}
```
Response
```
{
"token": "JWT",
"merchant_id": "merchant_id",
"name": "name from email",
"email": "invited_email ",
"verification_days_left": null,
"user_role": "invited_role"
}
```
| [
"crates/api_models/src/events/user.rs",
"crates/api_models/src/user.rs",
"crates/router/src/core/user.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/lock_utils.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/services/email/types.rs",
"crates/router_env/src/logger/types.r... | |
juspay/hyperswitch | juspay__hyperswitch-3870 | Bug: [FEATURE] : [Bitpay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index 148a5a45636..74fa0b5c595 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -140,8 +140,8 @@ pub struct BitpayPaymentResponseData {
pub exception_status: ExceptionStatus,
pub redirect_url: Option<String>,
pub refund_address_request_pending: Option<bool>,
- pub merchant_name: Option<String>,
- pub token: Option<String>,
+ pub merchant_name: Option<Secret<String>>,
+ pub token: Option<Secret<String>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
| 2024-02-19T13:20:26Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Bitpay
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for Bitpay
Sanity test
1. Payment create - card
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
response
```
BitpayPaymentsResponse { data: BitpayPaymentResponseData { url: Some(Url { scheme: "https", cannot_be_a_base: false, username: "", password: None, host: Some(Domain("test.bitpay.com")), port: None, path: "/invoice", query: Some("id=8wNbxWa97mrqBCavAQBmi8"), fragment: None }), status: New, price: 2000, currency: "GBP", amount_paid: 0, invoice_time: Some(1708434493106), rate_refresh_time: Some(1708434493106), expiration_time: Some(1708435393106), current_time: Some(1708434493513), id: "8wNbxWa97mrqBCavAQBmi8", order_id: Some("pay_uE8IRzN7s2e3s4AYLq9N_1"), low_fee_detected: Some(false), display_amount_paid: Some("0"), exception_status: Bool(false), redirect_url: None, refund_address_request_pending: Some(false), merchant_name: Some(*** alloc::string::String ***), token: Some(*** alloc::string::String ***) }, facade: Some("pos/invoice") }
```
In logs check for
`topic = "hyperswitch-outgoing-connector-events" ` | 76ac1a753a08f3ecc8ee264e4bccc47e8b219d1d | [
"crates/router/src/connector/bitpay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3769 | Bug: [FEATURE] : [BOA] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs
index 706532c5d18..fefc80f806c 100644
--- a/crates/router/src/connector/bankofamerica.rs
+++ b/crates/router/src/connector/bankofamerica.rs
@@ -1079,8 +1079,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("bankofamerica 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 {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index b2a9f14ccce..235321f1ac6 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -2,7 +2,7 @@ use api_models::payments;
use base64::Engine;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -113,9 +113,9 @@ pub struct MerchantDefinedInformation {
pub struct BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
@@ -213,7 +213,7 @@ pub struct BillTo {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
- locality: String,
+ locality: Secret<String>,
administrative_area: Secret<String>,
postal_code: Secret<String>,
country: api_enums::CountryAlpha2,
@@ -235,7 +235,7 @@ fn build_bill_to(
first_name: address.get_first_name()?.to_owned(),
last_name: address.get_last_name()?.to_owned(),
address1: address.get_line1()?.to_owned(),
- locality: address.get_city()?.to_owned(),
+ locality: Secret::new(address.get_city()?.to_owned()),
administrative_area: Secret::from(state),
postal_code: address.get_zip()?.to_owned(),
country: address.get_country()?.to_owned(),
@@ -435,7 +435,7 @@ pub struct ClientRiskInformation {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
- name: String,
+ name: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -889,8 +889,8 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformationResponse {
- access_token: String,
- device_data_collection_url: String,
+ access_token: Secret<String>,
+ device_data_collection_url: Secret<String>,
reference_id: String,
}
@@ -1066,10 +1066,12 @@ impl<F>
redirection_data: Some(services::RedirectForm::CybersourceAuthSetup {
access_token: info_response
.consumer_authentication_information
- .access_token,
+ .access_token
+ .expose(),
ddc_url: info_response
.consumer_authentication_information
- .device_data_collection_url,
+ .device_data_collection_url
+ .expose(),
reference_id: info_response
.consumer_authentication_information
.reference_id,
@@ -1322,10 +1324,10 @@ pub enum BankOfAmericaAuthEnrollmentStatus {
pub struct BankOfAmericaConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
@@ -1337,7 +1339,7 @@ pub struct BankOfAmericaThreeDSMetadata {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse {
- access_token: Option<String>,
+ access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
@@ -1420,7 +1422,8 @@ impl<F>
let redirection_data = match (
info_response
.consumer_authentication_information
- .access_token,
+ .access_token
+ .map(|access_token| access_token.expose()),
info_response
.consumer_authentication_information
.step_up_url,
@@ -2023,7 +2026,7 @@ impl
client_risk_information.rules.map(|rules| {
rules
.iter()
- .map(|risk_info| format!(" , {}", risk_info.name))
+ .map(|risk_info| format!(" , {}", risk_info.name.clone().expose()))
.collect::<Vec<String>>()
.join("")
})
| 2024-02-19T12:20:16Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for BOA
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for BOA
Sanity test
1. Payment create - card 3ds
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
response
```
NFO router::events::event_logger: event: "{\"connector_name\":\"bankofamerica\",\"flow\":\"PreProcessing\",\"request\":\"{\\\"paymentInformation\\\":{\\\"card\\\":{\\\"number\\\":\\\"512345**********\\\",\\\"expirationMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"expirationYear\\\":\\\"*** alloc::string::String ***\\\",\\\"securityCode\\\":\\\"*** alloc::string::String ***\\\",\\\"type\\\":\\\"002\\\"}},\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_yHo8Y3B8atd40rrClRkx_1\\\"},\\\"consumerAuthenticationInformation\\\":{\\\"returnUrl\\\":\\\"http://localhost:8080/payments/pay_yHo8Y3B8atd40rrClRkx/merchant_1708425554/redirect/complete/bankofamerica\\\",\\\"referenceId\\\":\\\"1901aba7-33de-49bb-afa0-001a14f95448\\\"},\\\"orderInformation\\\":{\\\"amountDetails\\\":{\\\"totalAmount\\\":\\\"20.00\\\",\\\"currency\\\":\\\"GBP\\\"},\\\"billTo\\\":{\\\"firstName\\\":\\\"*** alloc::string::String ***\\\",\\\"lastName\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"locality\\\":\\\"*** alloc::string::String ***\\\",\\\"administrativeArea\\\":\\\"*** alloc::string::String ***\\\",\\\"postalCode\\\":\\\"*** alloc::string::String ***\\\",\\\"country\\\":\\\"US\\\",\\\"email\\\":\\\"*********@gmail.com\\\"}}}\",\"masked_response\":\"{\\\"id\\\":\\\"7084255709226701604951\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_yHo8Y3B8atd40rrClRkx_1\\\"},\\\"consumerAuthenticationInformation\\\":{\\\"accessToken\\\":null,\\\"stepUpUrl\\\":null,\\\"ucafCollectionIndicator\\\":\\\"2\\\",\\\"cavv\\\":null,\\\"ucafAuthenticationData\\\":\\\"*** alloc::string::String ***\\\",\\\"xid\\\":null,\\\"specificationVersion\\\":\\\"2.1.0\\\",\\\"directoryServerTransactionId\\\":\\\"*** alloc::string::String ***\\\",\\\"indicator\\\":null},\\\"status\\\":\\\"AUTHENTICATION_SUCCESSFUL\\\",\\\"errorInformation\\\":null}\",\"error\":null,\"url\":\"https://apitest.merchant-services.bankofamerica.com/risk/v1/authentications\",\"method\":\"POST\",\"payment_id\":\"pay_yHo8Y3B8atd40rrClRkx\",\"merchant_id\":\"merchant_1708425554\",\"created_at\":1708425571363,\"request_id\":\"018dc619-6993-719c-b539-c698c767a08f\",\"latency\":579,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201}", event_type: ConnectorApiLogs, event_id: "018dc619-6993-719c-b539-c698c767a08f", log_type: "event"
```
In logs check for
`topic = "hyperswitch-outgoing-connector-events" ` | cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0 | [
"crates/router/src/connector/bankofamerica.rs",
"crates/router/src/connector/bankofamerica/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3768 | Bug: [FEATURE] : [Bambora] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index e2d9e18ce96..d453677deb6 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -228,8 +228,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -324,8 +326,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -405,8 +409,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -597,8 +603,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("bambora RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RefundsRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -669,8 +677,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("bambora 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 {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index d2c99bbaca0..c47b0718287 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -1,7 +1,7 @@
use base64::Engine;
-use common_utils::ext_traits::ValueExt;
+use common_utils::{ext_traits::ValueExt, pii::IpAddress};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
@@ -51,7 +51,7 @@ pub struct BamboraPaymentsRequest {
order_number: String,
amount: i64,
payment_method: PaymentMethod,
- customer_ip: Option<std::net::IpAddr>,
+ customer_ip: Option<Secret<String, IpAddress>>,
term_url: Option<String>,
card: BamboraCard,
}
@@ -133,7 +133,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
amount: item.request.amount,
payment_method: PaymentMethod::Card,
card: bambora_card,
- customer_ip: browser_info.ip_address,
+ customer_ip: browser_info
+ .ip_address
+ .map(|ip_address| Secret::new(format!("{ip_address}"))),
term_url: item.request.complete_authorize_url.clone(),
})
}
@@ -235,7 +237,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: Some(
serde_json::to_value(BamboraMeta {
- three_d_session_data: response.three_d_session_data,
+ three_d_session_data: response.three_d_session_data.expose(),
})
.into_report()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
@@ -312,7 +314,7 @@ pub struct BamboraPaymentsResponse {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
- three_d_session_data: String,
+ three_d_session_data: Secret<String>,
contents: String,
}
@@ -334,12 +336,12 @@ pub struct CardResponse {
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct CardData {
- name: Option<String>,
- expiry_month: Option<String>,
- expiry_year: Option<String>,
+ name: Option<Secret<String>>,
+ expiry_month: Option<Secret<String>>,
+ expiry_year: Option<Secret<String>>,
card_type: String,
- last_four: String,
- card_bin: Option<String>,
+ last_four: Secret<String>,
+ card_bin: Option<Secret<String>>,
avs_result: String,
cvd_result: String,
cavv_result: Option<String>,
@@ -357,15 +359,15 @@ pub struct AvsObject {
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AddressData {
- name: String,
- address_line1: String,
- address_line2: String,
+ name: Secret<String>,
+ address_line1: Secret<String>,
+ address_line2: Secret<String>,
city: String,
province: String,
country: String,
- postal_code: String,
- phone_number: String,
- email_address: String,
+ postal_code: Secret<String>,
+ phone_number: Secret<String>,
+ email_address: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
| 2024-02-19T08:53:46Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Bambora
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for bambora
Sanity test
1. Payment create -
Card
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
Card 3ds
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
In logs check for
`topic = "hyperswitch-outgoing-connector-events" `
2. Refund
> _Note: There is an existing issue with this connector #3701. That could affect testing_ | 073310c1f671ccbb71cc5c8725eca9771e511589 | [
"crates/router/src/connector/bambora.rs",
"crates/router/src/connector/bambora/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3694 | Bug: feat(analytics): adding dispute as uri param to analytics info api
| diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 27d42350509..ead3b1699ec 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -130,7 +130,8 @@ impl AnalyticsDataSource for ClickhouseClient {
match table {
AnalyticsCollection::Payment
| AnalyticsCollection::Refund
- | AnalyticsCollection::PaymentIntent => {
+ | AnalyticsCollection::PaymentIntent
+ | AnalyticsCollection::Dispute => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
AnalyticsCollection::SdkEvents => TableEngine::BasicTree,
@@ -374,6 +375,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection {
Self::PaymentIntent => Ok("payment_intents".to_string()),
Self::ConnectorEvents => Ok("connector_events_audit".to_string()),
Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()),
+ Self::Dispute => Ok("dispute".to_string()),
}
}
}
diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs
index 354e1e2f176..6ccf2858e22 100644
--- a/crates/analytics/src/core.rs
+++ b/crates/analytics/src/core.rs
@@ -26,6 +26,11 @@ pub async fn get_domain_info(
download_dimensions: None,
dimensions: utils::get_api_event_dimensions(),
},
+ AnalyticsDomain::Dispute => GetInfoResponse {
+ metrics: utils::get_dispute_metrics_info(),
+ download_dimensions: None,
+ dimensions: utils::get_dispute_dimensions(),
+ },
};
Ok(info)
}
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 562a3a1f64d..1fb7a9b4509 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -445,6 +445,7 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
.attach_printable("ConnectorEvents table is not implemented for Sqlx"))?,
Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?,
+ Self::Dispute => Ok("dispute".to_string()),
}
}
}
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 18e9e9f4334..356d11bb77d 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -17,6 +17,7 @@ pub enum AnalyticsDomain {
Refunds,
SdkEvents,
ApiEvents,
+ Dispute,
}
#[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)]
@@ -28,6 +29,7 @@ pub enum AnalyticsCollection {
PaymentIntent,
ConnectorEvents,
OutgoingWebhookEvent,
+ Dispute,
}
#[allow(dead_code)]
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index 6a0aa973a1e..7bff5c87da6 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -1,5 +1,6 @@
use api_models::analytics::{
api_event::{ApiEventDimensions, ApiEventMetrics},
+ disputes::{DisputeDimensions, DisputeMetrics},
payments::{PaymentDimensions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
@@ -38,3 +39,11 @@ pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> {
pub fn get_api_event_metrics_info() -> Vec<NameDescription> {
ApiEventMetrics::iter().map(Into::into).collect()
}
+
+pub fn get_dispute_metrics_info() -> Vec<NameDescription> {
+ DisputeMetrics::iter().map(Into::into).collect()
+}
+
+pub fn get_dispute_dimensions() -> Vec<NameDescription> {
+ DisputeDimensions::iter().map(Into::into).collect()
+}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index c6ca215f9f7..1115d40b19d 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -13,6 +13,7 @@ pub use crate::payments::TimeRange;
pub mod api_event;
pub mod connector_events;
+pub mod disputes;
pub mod outgoing_webhook_event;
pub mod payments;
pub mod refunds;
diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs
new file mode 100644
index 00000000000..19d552d45d4
--- /dev/null
+++ b/crates/api_models/src/analytics/disputes.rs
@@ -0,0 +1,65 @@
+use super::NameDescription;
+
+#[derive(
+ Clone,
+ 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 DisputeMetrics {
+ DisputesChallenged,
+ DisputesWon,
+ DisputesLost,
+ TotalAmountDisputed,
+ TotalDisputeLostAmount,
+}
+
+#[derive(
+ Debug,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::AsRefStr,
+ PartialEq,
+ PartialOrd,
+ Eq,
+ Ord,
+ strum::Display,
+ strum::EnumIter,
+ Clone,
+ Copy,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum DisputeDimensions {
+ // Do not change the order of these enums
+ // Consult the Dashboard FE folks since these also affects the order of metrics on FE
+ Connector,
+ DisputeStatus,
+ ConnectorStatus,
+}
+
+impl From<DisputeDimensions> for NameDescription {
+ fn from(value: DisputeDimensions) -> Self {
+ Self {
+ name: value.to_string(),
+ desc: String::new(),
+ }
+ }
+}
+
+impl From<DisputeMetrics> for NameDescription {
+ fn from(value: DisputeMetrics) -> Self {
+ Self {
+ name: value.to_string(),
+ desc: String::new(),
+ }
+ }
+}
| 2024-02-19T07:15:26Z |
## Description
added dispute as URI PARAM to info api of analytics
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | df739a302b062277647afe5c3888015272fdc2cf | Hit the curl mentioned below and expected response has posted below
| [
"crates/analytics/src/clickhouse.rs",
"crates/analytics/src/core.rs",
"crates/analytics/src/sqlx.rs",
"crates/analytics/src/types.rs",
"crates/analytics/src/utils.rs",
"crates/api_models/src/analytics.rs",
"crates/api_models/src/analytics/disputes.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3698 | Bug: setup roles table
Setup `roles` table along with db functions to support custom roles. | diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 7ca65ac4b76..4ca5b4c986c 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -17,7 +17,8 @@ pub mod diesel_exports {
DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus,
DbRefundStatus as RefundStatus, DbRefundType as RefundType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
- DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbUserStatus as UserStatus,
+ DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind,
+ DbUserStatus as UserStatus,
};
}
pub use common_enums::*;
@@ -500,3 +501,53 @@ pub enum DashboardMetadata {
IsMultipleConfiguration,
IsChangePasswordRequired,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum RoleScope {
+ Merchant,
+ Organization,
+}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum PermissionGroup {
+ OperationsView,
+ OperationsManage,
+ ConnectorsView,
+ ConnectorsManage,
+ WorkflowsView,
+ WorkflowsManage,
+ AnalyticsView,
+ UsersView,
+ UsersManage,
+ MerchantDetailsView,
+ MerchantDetailsManage,
+ OrganizationManage,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 82b1e29ee83..f7678793bc2 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -39,6 +39,7 @@ pub mod process_tracker;
pub mod query;
pub mod refund;
pub mod reverse_lookup;
+pub mod role;
pub mod routing_algorithm;
#[allow(unused_qualifications)]
pub mod schema;
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index 3a0a008b76b..c395ae3df92 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -32,6 +32,7 @@ pub mod payouts;
pub mod process_tracker;
pub mod refund;
pub mod reverse_lookup;
+pub mod role;
pub mod routing_algorithm;
pub mod user;
pub mod user_role;
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
new file mode 100644
index 00000000000..b8704aebbd0
--- /dev/null
+++ b/crates/diesel_models/src/query/role.rs
@@ -0,0 +1,68 @@
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use router_env::tracing::{self, instrument};
+
+use crate::{
+ enums::RoleScope, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult,
+};
+
+impl RoleNew {
+ #[instrument(skip(conn))]
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl Role {
+ pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::role_id.eq(role_id.to_owned()),
+ )
+ .await
+ }
+
+ pub async fn update_by_role_id(
+ conn: &PgPooledConn,
+ role_id: &str,
+ role_update: RoleUpdate,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::role_id.eq(role_id.to_owned()),
+ RoleUpdateInternal::from(role_update),
+ )
+ .await
+ }
+
+ pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> {
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::role_id.eq(role_id.to_owned()),
+ )
+ .await
+ }
+
+ pub async fn list_roles(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> StorageResult<Vec<Self>> {
+ let predicate = dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id
+ .eq(org_id.to_owned())
+ .and(dsl::scope.eq(RoleScope::Organization)));
+
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ predicate,
+ None,
+ None,
+ Some(dsl::last_modified_at.asc()),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
new file mode 100644
index 00000000000..6b21b1461cd
--- /dev/null
+++ b/crates/diesel_models/src/role.rs
@@ -0,0 +1,83 @@
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
+use time::PrimitiveDateTime;
+
+use crate::{enums, schema::roles};
+
+#[derive(Clone, Debug, Identifiable, Queryable)]
+#[diesel(table_name = roles)]
+pub struct Role {
+ pub id: i32,
+ pub role_name: String,
+ pub role_id: String,
+ pub merchant_id: String,
+ pub org_id: String,
+ #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
+ pub groups: Vec<enums::PermissionGroup>,
+ pub scope: enums::RoleScope,
+ pub created_at: PrimitiveDateTime,
+ pub created_by: String,
+ pub last_modified_at: PrimitiveDateTime,
+ pub last_modified_by: String,
+}
+
+#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
+#[diesel(table_name = roles)]
+pub struct RoleNew {
+ pub role_name: String,
+ pub role_id: String,
+ pub merchant_id: String,
+ pub org_id: String,
+ #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
+ pub groups: Vec<enums::PermissionGroup>,
+ pub scope: enums::RoleScope,
+ pub created_at: PrimitiveDateTime,
+ pub created_by: String,
+ pub last_modified_at: PrimitiveDateTime,
+ pub last_modified_by: String,
+}
+
+#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
+#[diesel(table_name = roles)]
+pub struct RoleUpdateInternal {
+ groups: Option<Vec<enums::PermissionGroup>>,
+ role_name: Option<String>,
+ last_modified_by: String,
+ last_modified_at: PrimitiveDateTime,
+}
+
+pub enum RoleUpdate {
+ UpdateGroup {
+ groups: Vec<enums::PermissionGroup>,
+ last_modified_by: String,
+ },
+ UpdateRoleName {
+ role_name: String,
+ last_modified_by: String,
+ },
+}
+
+impl From<RoleUpdate> for RoleUpdateInternal {
+ fn from(value: RoleUpdate) -> Self {
+ let last_modified_at = common_utils::date_time::now();
+ match value {
+ RoleUpdate::UpdateGroup {
+ groups,
+ last_modified_by,
+ } => Self {
+ groups: Some(groups),
+ role_name: None,
+ last_modified_at,
+ last_modified_by,
+ },
+ RoleUpdate::UpdateRoleName {
+ role_name,
+ last_modified_by,
+ } => Self {
+ groups: None,
+ role_name: Some(role_name),
+ last_modified_at,
+ last_modified_by,
+ },
+ }
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 6c28677432b..2cbcb52fb44 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -994,6 +994,31 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ roles (id) {
+ id -> Int4,
+ #[max_length = 64]
+ role_name -> Varchar,
+ #[max_length = 64]
+ role_id -> Varchar,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 64]
+ org_id -> Varchar,
+ groups -> Array<Nullable<Text>>,
+ scope -> RoleScope,
+ created_at -> Timestamp,
+ #[max_length = 64]
+ created_by -> Varchar,
+ last_modified_at -> Timestamp,
+ #[max_length = 64]
+ last_modified_by -> Varchar,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1095,6 +1120,7 @@ diesel::allow_tables_to_appear_in_same_query!(
process_tracker,
refund,
reverse_lookup,
+ roles,
routing_algorithm,
user_roles,
users,
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 54900177246..d385d94a5de 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -31,6 +31,7 @@ pub mod payout_attempt;
pub mod payouts;
pub mod refund;
pub mod reverse_lookup;
+pub mod role;
pub mod routing_algorithm;
pub mod user;
pub mod user_role;
@@ -111,6 +112,7 @@ pub trait StorageInterface:
+ authorization::AuthorizationInterface
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ + role::RoleInterface
+ 'static
{
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0078f030c5a..0897deb87e5 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -24,6 +24,7 @@ use time::PrimitiveDateTime;
use super::{
dashboard_metadata::DashboardMetadataInterface,
+ role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_role::UserRoleInterface,
};
@@ -2256,3 +2257,45 @@ impl HealthCheckDbInterface for KafkaStore {
self.diesel_store.health_check_db().await
}
}
+
+#[async_trait::async_trait]
+impl RoleInterface for KafkaStore {
+ async fn insert_role(
+ &self,
+ role: storage::RoleNew,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store.insert_role(role).await
+ }
+
+ async fn find_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store.find_role_by_role_id(role_id).await
+ }
+
+ async fn update_role_by_role_id(
+ &self,
+ role_id: &str,
+ role_update: storage::RoleUpdate,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store
+ .update_role_by_role_id(role_id, role_update)
+ .await
+ }
+
+ async fn delete_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store.delete_role_by_role_id(role_id).await
+ }
+
+ async fn list_all_roles(
+ &self,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ self.diesel_store.list_all_roles(merchant_id, org_id).await
+ }
+}
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
new file mode 100644
index 00000000000..da2abf15ff7
--- /dev/null
+++ b/crates/router/src/db/role.rs
@@ -0,0 +1,236 @@
+use diesel_models::role as storage;
+use error_stack::{IntoReport, ResultExt};
+
+use super::MockDb;
+use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ services::Store,
+};
+
+#[async_trait::async_trait]
+pub trait RoleInterface {
+ async fn insert_role(
+ &self,
+ role: storage::RoleNew,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
+ async fn find_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
+ async fn update_role_by_role_id(
+ &self,
+ role_id: &str,
+ role_update: storage::RoleUpdate,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
+ async fn delete_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
+ async fn list_all_roles(
+ &self,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl RoleInterface for Store {
+ async fn insert_role(
+ &self,
+ role: storage::RoleNew,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ role.insert(&conn).await.map_err(Into::into).into_report()
+ }
+
+ async fn find_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::find_by_role_id(&conn, role_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ async fn update_role_by_role_id(
+ &self,
+ role_id: &str,
+ role_update: storage::RoleUpdate,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::update_by_role_id(&conn, role_id, role_update)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ async fn delete_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::delete_by_role_id(&conn, role_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ async fn list_all_roles(
+ &self,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::list_roles(&conn, merchant_id, org_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+}
+
+#[async_trait::async_trait]
+impl RoleInterface for MockDb {
+ async fn insert_role(
+ &self,
+ role: storage::RoleNew,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let mut roles = self.roles.lock().await;
+ if roles
+ .iter()
+ .any(|role_inner| role_inner.role_id == role.role_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "role_id",
+ key: None,
+ })?
+ }
+ let role = storage::Role {
+ id: roles
+ .len()
+ .try_into()
+ .into_report()
+ .change_context(errors::StorageError::MockDbError)?,
+ role_name: role.role_name,
+ role_id: role.role_id,
+ merchant_id: role.merchant_id,
+ org_id: role.org_id,
+ groups: role.groups,
+ scope: role.scope,
+ created_by: role.created_by,
+ created_at: role.created_at,
+ last_modified_at: role.last_modified_at,
+ last_modified_by: role.last_modified_by,
+ };
+ roles.push(role.clone());
+ Ok(role)
+ }
+
+ async fn find_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let roles = self.roles.lock().await;
+ roles
+ .iter()
+ .find(|role| role.role_id == role_id)
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No role available role_id = {role_id}"
+ ))
+ .into(),
+ )
+ }
+
+ async fn update_role_by_role_id(
+ &self,
+ role_id: &str,
+ role_update: storage::RoleUpdate,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let mut roles = self.roles.lock().await;
+ let last_modified_at = common_utils::date_time::now();
+
+ roles
+ .iter_mut()
+ .find(|role| role.role_id == role_id)
+ .map(|role| {
+ *role = match role_update {
+ storage::RoleUpdate::UpdateGroup {
+ groups,
+ last_modified_by,
+ } => storage::Role {
+ groups,
+ last_modified_by,
+ last_modified_at,
+ ..role.to_owned()
+ },
+ storage::RoleUpdate::UpdateRoleName {
+ role_name,
+ last_modified_by,
+ } => storage::Role {
+ role_name,
+ last_modified_at,
+ last_modified_by,
+ ..role.to_owned()
+ },
+ };
+ role.to_owned()
+ })
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No role available for role_id = {role_id}"
+ ))
+ .into(),
+ )
+ }
+
+ async fn delete_role_by_role_id(
+ &self,
+ role_id: &str,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let mut roles = self.roles.lock().await;
+ let role_index = roles
+ .iter()
+ .position(|role| role.role_id == role_id)
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "No role available for role_id = {role_id}"
+ )))?;
+
+ Ok(roles.remove(role_index))
+ }
+
+ async fn list_all_roles(
+ &self,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let roles = self.roles.lock().await;
+
+ let roles_list: Vec<_> = roles
+ .iter()
+ .filter(|role| {
+ role.merchant_id == merchant_id
+ || (role.org_id == org_id
+ && role.scope == diesel_models::enums::RoleScope::Organization)
+ })
+ .cloned()
+ .collect();
+
+ if roles_list.is_empty() {
+ return Err(errors::StorageError::ValueNotFound(format!(
+ "No role found for merchant id = {} and org_id = {}",
+ merchant_id, org_id
+ ))
+ .into());
+ }
+
+ Ok(roles_list)
+ }
+}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index b93cbbbbba9..01decc89c4c 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -31,6 +31,7 @@ pub mod payout_attempt;
pub mod payouts;
pub mod refund;
pub mod reverse_lookup;
+pub mod role;
pub mod routing_algorithm;
pub mod user;
pub mod user_role;
@@ -51,7 +52,8 @@ pub use self::{
dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*,
merchant_key_store::*, payment_link::*, payment_method::*, payout_attempt::*, payouts::*,
- process_tracker::*, refund::*, reverse_lookup::*, routing_algorithm::*, user::*, user_role::*,
+ process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, user::*,
+ user_role::*,
};
use crate::types::api::routing;
diff --git a/crates/router/src/types/storage/role.rs b/crates/router/src/types/storage/role.rs
new file mode 100644
index 00000000000..4a831762a4e
--- /dev/null
+++ b/crates/router/src/types/storage/role.rs
@@ -0,0 +1 @@
+pub use diesel_models::role::*;
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index a6ba763bd91..a1518cea431 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -45,6 +45,7 @@ pub struct MockDb {
pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>,
pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>,
pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>,
+ pub roles: Arc<Mutex<Vec<store::role::Role>>>,
}
impl MockDb {
@@ -82,6 +83,7 @@ impl MockDb {
user_roles: Default::default(),
authorizations: Default::default(),
dashboard_metadata: Default::default(),
+ roles: Default::default(),
})
}
}
diff --git a/migrations/2024-02-14-092225_create_roles_table/down.sql b/migrations/2024-02-14-092225_create_roles_table/down.sql
new file mode 100644
index 00000000000..c8b1c055f7d
--- /dev/null
+++ b/migrations/2024-02-14-092225_create_roles_table/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+DROP INDEX IF EXISTS role_id_index;
+DROP INDEX IF EXISTS roles_merchant_org_index;
+
+DROP TABLE IF EXISTS roles;
+DROP TYPE "RoleScope";
\ No newline at end of file
diff --git a/migrations/2024-02-14-092225_create_roles_table/up.sql b/migrations/2024-02-14-092225_create_roles_table/up.sql
new file mode 100644
index 00000000000..c33c133a078
--- /dev/null
+++ b/migrations/2024-02-14-092225_create_roles_table/up.sql
@@ -0,0 +1,19 @@
+-- Your SQL goes here
+CREATE TYPE "RoleScope" AS ENUM ('merchant','organization');
+
+CREATE TABLE IF NOT EXISTS roles (
+ id SERIAL PRIMARY KEY,
+ role_name VARCHAR(64) NOT NULL,
+ role_id VARCHAR(64) NOT NULL UNIQUE,
+ merchant_id VARCHAR(64) NOT NULL,
+ org_id VARCHAR(64) NOT NULL,
+ groups TEXT[] NOT NULL,
+ scope "RoleScope" NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now(),
+ created_by VARCHAR(64) NOT NULL,
+ last_modified_at TIMESTAMP NOT NULL DEFAULT now(),
+ last_modified_by VARCHAR(64) NOT NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS role_id_index ON roles (role_id);
+CREATE INDEX roles_merchant_org_index ON roles (merchant_id, org_id);
\ No newline at end of file
| 2024-02-18T21:15:04Z |
## Description
Setup roles table to support custom roles.
## Motivation and Context
# | 8038b48a54c937b3fe72b36cec5f20ee87309be4 | Will be dependent on one core PR; checked table schema locally by running the migrations.
After core functions micro PR containing Apis to interact with DB this can be tested in other environments as well.
| [
"crates/diesel_models/src/enums.rs",
"crates/diesel_models/src/lib.rs",
"crates/diesel_models/src/query.rs",
"crates/diesel_models/src/query/role.rs",
"crates/diesel_models/src/role.rs",
"crates/diesel_models/src/schema.rs",
"crates/router/src/db.rs",
"crates/router/src/db/kafka_store.rs",
"crates/r... | |
juspay/hyperswitch | juspay__hyperswitch-2863 | Bug: [REFACTOR] : [Stripe] Error Message For Connector Implementation
### :memo: Feature Description
- In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation.
### :hammer: Possible Implementation
- In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant.
- By doing so, we will throw same error message for all the Connector Implementation
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 6a89232d4e8..03c424a219f 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -684,10 +684,9 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
| enums::PaymentMethodType::FamilyMart
| enums::PaymentMethodType::Seicomart
| enums::PaymentMethodType::PayEasy
- | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ | enums::PaymentMethodType::Walley => Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into()),
}
}
@@ -873,10 +872,9 @@ impl TryFrom<&api_models::enums::BankNames> for StripeBankNames {
api_models::enums::BankNames::AliorBank => Self::AliorBank,
api_models::enums::BankNames::Boz => Self::Boz,
- _ => Err(errors::ConnectorError::NotSupported {
- message: api_enums::PaymentMethod::BankRedirect.to_string(),
- connector: "Stripe",
- })?,
+ _ => Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ ))?,
})
}
}
@@ -919,10 +917,9 @@ impl TryFrom<&api_models::payments::PayLaterData> for StripePaymentMethodType {
| payments::PayLaterData::WalleyRedirect {}
| payments::PayLaterData::AlmaRedirect {}
| payments::PayLaterData::AtomeRedirect {} => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- })
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ ))
}
}
}
@@ -953,10 +950,9 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodType {
| payments::BankRedirectData::OnlineBankingThailand { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
| payments::BankRedirectData::Trustly { .. } => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- })
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ ))
}
}
}
@@ -996,10 +992,9 @@ impl ForeignTryFrom<&payments::WalletData> for Option<StripePaymentMethodType> {
| payments::WalletData::TouchNGoRedirect(_)
| payments::WalletData::SwishQr(_)
| payments::WalletData::WeChatPayRedirect(_) => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- })
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ ))
}
}
}
@@ -1398,10 +1393,9 @@ fn create_stripe_payment_method(
| payments::BankTransferData::CimbVaBankTransfer { .. }
| payments::BankTransferData::DanamonVaBankTransfer { .. }
| payments::BankTransferData::MandiriVaBankTransfer { .. } => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into())
}
}
@@ -1413,10 +1407,9 @@ fn create_stripe_payment_method(
payments::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() {
payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into())
}
},
@@ -1426,10 +1419,9 @@ fn create_stripe_payment_method(
| payments::CardRedirectData::Benefit {}
| payments::CardRedirectData::MomoAtm {}
| payments::CardRedirectData::CardRedirect {} => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into())
}
},
@@ -1456,19 +1448,17 @@ fn create_stripe_payment_method(
| payments::VoucherData::MiniStop(_)
| payments::VoucherData::FamilyMart(_)
| payments::VoucherData::Seicomart(_)
- | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into()),
},
payments::PaymentMethodData::Upi(_)
| payments::PaymentMethodData::MandatePayment
- | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into()),
}
}
@@ -1588,10 +1578,9 @@ impl TryFrom<(&payments::WalletData, Option<types::PaymentMethodToken>)>
| payments::WalletData::TouchNGoRedirect(_)
| payments::WalletData::SwishQr(_)
| payments::WalletData::WeChatPayRedirect(_) => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into())
}
}
@@ -1681,10 +1670,9 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
| payments::BankRedirectData::OnlineBankingThailand { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
| payments::BankRedirectData::Trustly { .. } => {
- Err(errors::ConnectorError::NotSupported {
- message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "stripe",
- }
+ Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ )
.into())
}
}
@@ -3579,10 +3567,9 @@ impl
| api::PaymentMethodData::Upi(_)
| api::PaymentMethodData::CardRedirect(_)
| api::PaymentMethodData::Voucher(_)
- | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported {
- message: format!("{pm_type:?}"),
- connector: "Stripe",
- })?,
+ | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
+ connector_util::get_unimplemented_payment_method_error_message("stripe"),
+ ))?,
}
}
}
| 2024-02-17T02:18:04Z |
## Description
Should close #2863 by changing `NotSupported` to `NotImplemented` error for Stripe
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 783fa0b0dff1e157920d683a75fc579942cd9c06 | Test a Payment Method which is not implemented It should give
Not implemented error
This is an Crypto payment request.
```
{
"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": "crypto",
"payment_method_type": "crypto_currency",
"payment_method_data": {
"crypto": {}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Swangi"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Swangi"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"profile_id": "pro_16j8JOCurimvr2XXG9EE"
}
```
This is a Payment Method which is not implemented for Stripe
| [
"crates/router/src/connector/stripe/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3686 | Bug: [FEATURE]: [Adyen] Use connector_response_reference_id as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
- yes | diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 072b542eee0..00c6ecbd6ab 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -338,6 +338,7 @@ pub struct RedirectionResponse {
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
psp_reference: Option<String>,
+ merchant_reference: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -348,6 +349,7 @@ pub struct PresentToShopperResponse {
action: AdyenPtsAction,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
+ merchant_reference: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -359,6 +361,7 @@ pub struct QrCodeResponseResponse {
refusal_reason_code: Option<String>,
additional_data: Option<QrCodeAdditionalData>,
psp_reference: Option<String>,
+ merchant_reference: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -3166,7 +3169,10 @@ pub fn get_redirection_response(
mandate_reference: None,
connector_metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: response
+ .merchant_reference
+ .clone()
+ .or(response.psp_reference),
incremental_authorization_allowed: None,
};
Ok((status, error, payments_response_data))
@@ -3220,7 +3226,10 @@ pub fn get_present_to_shopper_response(
mandate_reference: None,
connector_metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: response
+ .merchant_reference
+ .clone()
+ .or(response.psp_reference),
incremental_authorization_allowed: None,
};
Ok((status, error, payments_response_data))
@@ -3271,7 +3280,10 @@ pub fn get_qr_code_response(
mandate_reference: None,
connector_metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: response
+ .merchant_reference
+ .clone()
+ .or(response.psp_reference),
incremental_authorization_allowed: None,
};
Ok((status, error, payments_response_data))
@@ -3645,6 +3657,7 @@ pub struct AdyenCaptureResponse {
reference: String,
status: String,
amount: Amount,
+ merchant_reference: Option<String>,
}
impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
@@ -3655,7 +3668,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
item: types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_transaction_id = if item.data.request.multiple_capture_data.is_some() {
- item.response.psp_reference
+ item.response.psp_reference.clone()
} else {
item.response.payment_psp_reference
};
@@ -3670,7 +3683,11 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .merchant_reference
+ .clone()
+ .or(Some(item.response.psp_reference)),
incremental_authorization_allowed: None,
}),
amount_captured: Some(item.response.amount.value),
| 2024-02-16T13:05:53Z |
## Description
<!-- Describe your changes in detail -->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cf3c66636ffee30cdd4353b276a89a8f9fc2d9d0 | Payment Request for Cards
```
{
"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_type": "credit",
"payment_method_data": {
"card": {
"card_number": "371449635398431",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "7373"
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
In Response we should get `"reference_id": "some value",`
```
{
"payment_id": "pay_q9uYD8e8lUUsO8BX1OBN",
"merchant_id": "merchant_1708428346",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "adyen",
"client_secret": "pay_q9uYD8e8lUUsO8BX1OBN_secret_OAZ7LeGk4bwipgEyl7fT",
"created": "2024-02-21T06:56:37.030Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "8431",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "371449",
"card_extended_bin": "37144963",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
}
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": null,
"country_code": 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": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1708498596,
"expires": 1708502196,
"secret": "epk_ed9cc758e8484b5fb018382c33097f4b"
},
"manual_retry_allowed": false,
"connector_transaction_id": "ZK5M8KH2HV8DCG65",
"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_q9uYD8e8lUUsO8BX1OBN_1", (should not be null)
"payment_link": null,
"profile_id": "pro_qisu2wRsK4dq0H3hKKpM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-21T07:11:37.030Z",
"fingerprint": null
}
```
<img width="1728" alt="Screenshot 2024-02-20 at 1 39 43 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/ad497234-2799-4aa9-84af-11aeef3d71d8">
Payment Request for Blik
```
{
"amount": 16000,
"currency": "PLN",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 16000,
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"profile_id": "pro_sx78reJN0zgRzB5UGicx",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"payment_method": "bank_redirect",
"payment_method_type": "blik",
"payment_method_data": {
"bank_redirect": {
"blik": {
"blik_code":"777987"
}
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "PL"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "PL",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
In Response we should get `"reference_id": "some value",`
```
{
"payment_id": "pay_brzqtt6cdm5rL3HAYPxk",
"merchant_id": "merchant_1708428346",
"status": "processing",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_brzqtt6cdm5rL3HAYPxk_secret_eY8ZA1UonKsrJnmGRVC3",
"created": "2024-02-20T13:30:26.642Z",
"currency": "PLN",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_redirect",
"payment_method_data": "bank_redirect",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "PL",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"billing": {
"address": {
"city": "San Fransico",
"country": "PL",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "wait_screen_information",
"display_from_timestamp": 1708435828625707000,
"display_to_timestamp": 1708435888625707000
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "blik",
"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": 1708435826,
"expires": 1708439426,
"secret": "epk_940c1cecdd6b49928d2047f91ff5659c"
},
"manual_retry_allowed": false,
"connector_transaction_id": "DQ7M74SBGTGLNK82",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "some value, (it should not be null)
"payment_link": null,
"profile_id": "pro_qisu2wRsK4dq0H3hKKpM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-20T13:45:26.642Z",
"fingerprint": null
}
```
<img width="1579" alt="Screenshot 2024-02-20 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/0db938b9-8c2a-4e8f-9f42-0cbb414274e3">
Payment Request for PIX
```
{
"amount": 5000,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"profile_id": "pro_sx78reJN0zgRzB5UGicx",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"payment_method": "bank_transfer",
"payment_method_type": "pix",
"payment_method_data": {
"bank_transfer": {
"pix": {}
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Resoonse of PIx
```
{
"payment_id": "pay_jIHarDTbWEuaOXjb7gAa",
"merchant_id": "merchant_1708428346",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_jIHarDTbWEuaOXjb7gAa_secret_Snqq6qd95TFXjk6AlvBN",
"created": "2024-02-21T06:58:43.312Z",
"currency": "BRL",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_transfer",
"payment_method_data": "bank_transfer",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"billing": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
}
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "pix",
"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": 1708498723,
"expires": 1708502323,
"secret": "epk_735c0ab3ea1847d7add23e9c402f217b"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "some value", (should not be null)
"payment_link": null,
"profile_id": "pro_qisu2wRsK4dq0H3hKKpM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_wkHJMOOIYr9gbxJRXn5g",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-21T07:13:43.312Z",
"fingerprint": null
}
```
In Response we should get `"reference_id": "some value",`
<img width="1543" alt="Screenshot 2024-02-20 at 3 10 45 PM" src="https://github.com/juspay/hyperswitch/assets/85639103/c4d6a287-c04e-4bab-8dac-d9ba3d3f9c11">
| [
"crates/router/src/connector/adyen/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3685 | Bug: [REFACTOR] Simplify the method signatures of some methods in the `Encode` extension trait
### Description
The definition of the [`common_utils::ext_traits::Encode`](https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/common_utils/src/ext_traits.rs#L21) trait has a generic type parameter `P`, which is used in only a subset of the trait methods. This causes the type having to be specified when calling methods which don't use that generic type parameter, such as the [`encode_to_value()`](https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/common_utils/src/ext_traits.rs#L78) method, used to convert a type which implements `serde::Serialize` to a `serde_json::Value`.
One such usage is:
https://github.com/juspay/hyperswitch/blob/fb254b8924808e6a2b2a9a31dbed78749836e8d3/crates/router/src/routes/payments/helpers.rs#L76-L80
Ignoring the error handling and propagation bolierplate code, it looks like so:
```rust
use common_utils::ext_traits::Encode; // Include trait in scope
let encoded = Encode::<types::BrowserInformation>::encode_to_value(&browser_info)?;
```
This can be simplified to something like this (since the compiler is able to infer types in most cases):
```rust
use common_utils::ext_traits::Encode; // Include trait in scope
let encoded = browser_info.encode_to_value()?;
```
### Possible Implementation
Remove the generic type parameter `P` on the trait, and add it in the trait methods which use that type parameter.
| diff --git a/add_connector.md b/add_connector.md
index 57fb6fdfff4..ac9d3f8d847 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -531,7 +531,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?;
let checkout_req = types::RequestBody::log_and_get_request_body(
&connector_req,
- utils::Encode::<checkout::PaymentsRequest>::encode_to_string_of_json,
+ utils::Encode::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(checkout_req))
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 1be9762c76c..b95b74b329f 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -625,7 +625,7 @@ impl PaymentsRequest {
> {
self.feature_metadata
.as_ref()
- .map(Encode::<FeatureMetadata>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
}
@@ -637,7 +637,7 @@ impl PaymentsRequest {
> {
self.connector_metadata
.as_ref()
- .map(Encode::<ConnectorMetadata>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
}
@@ -649,7 +649,7 @@ impl PaymentsRequest {
> {
self.allowed_payment_method_types
.as_ref()
- .map(Encode::<Vec<api_enums::PaymentMethodType>>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
}
@@ -663,10 +663,7 @@ impl PaymentsRequest {
.as_ref()
.map(|od| {
od.iter()
- .map(|order| {
- Encode::<OrderDetailsWithAmount>::encode_to_value(order)
- .map(masking::Secret::new)
- })
+ .map(|order| order.encode_to_value().map(masking::Secret::new))
.collect::<Result<Vec<_>, _>>()
})
.transpose()
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs
index d3296f98953..8f97dd75534 100644
--- a/crates/common_utils/src/ext_traits.rs
+++ b/crates/common_utils/src/ext_traits.rs
@@ -18,7 +18,7 @@ use crate::{
/// Encode interface
/// An interface for performing type conversions and serialization
///
-pub trait Encode<'e, P>
+pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
@@ -28,7 +28,7 @@ where
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically to convert into json, by using `serde_json`
///
- fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError>
+ fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
@@ -39,7 +39,7 @@ where
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically, to convert into urlencoded, by using `serde_urlencoded`
///
- fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
+ fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
@@ -88,11 +88,11 @@ where
Self: Serialize;
}
-impl<'e, P, A> Encode<'e, P> for A
+impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
- fn convert_and_encode(&'e self) -> CustomResult<String, errors::ParsingError>
+ fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
@@ -106,7 +106,7 @@ where
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
- fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
+ fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index ce2b138d923..5d376a4d7b1 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -75,7 +75,8 @@ impl super::RedisConnectionPool {
where
V: serde::Serialize + Debug,
{
- let serialized = Encode::<V>::encode_to_vec(&value)
+ let serialized = value
+ .encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl)
.await
@@ -90,7 +91,8 @@ impl super::RedisConnectionPool {
where
V: serde::Serialize + Debug,
{
- let serialized = Encode::<V>::encode_to_vec(&value)
+ let serialized = value
+ .encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key(key, serialized.as_slice()).await
@@ -106,7 +108,8 @@ impl super::RedisConnectionPool {
where
V: serde::Serialize + Debug,
{
- let serialized = Encode::<V>::encode_to_vec(&value)
+ let serialized = value
+ .encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.pool
@@ -307,7 +310,8 @@ impl super::RedisConnectionPool {
where
V: serde::Serialize + Debug,
{
- let serialized = Encode::<V>::encode_to_vec(&value)
+ let serialized = value
+ .encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl)
diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs
index 807278e0aff..0cbd89bdd3e 100644
--- a/crates/router/src/compatibility/stripe/webhooks.rs
+++ b/crates/router/src/compatibility/stripe/webhooks.rs
@@ -2,7 +2,7 @@ use api_models::{
enums::{DisputeStatus, MandateStatus},
webhooks::{self as api},
};
-use common_utils::{crypto::SignMessage, date_time, ext_traits};
+use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode};
use error_stack::{IntoReport, ResultExt};
use router_env::logger;
use serde::Serialize;
@@ -39,10 +39,10 @@ impl OutgoingWebhookType for StripeOutgoingWebhook {
.into_report()
.attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?;
- let webhook_signature_payload =
- ext_traits::Encode::<serde_json::Value>::encode_to_string_of_json(self)
- .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
- .attach_printable("failed encoding outgoing webhook payload")?;
+ let webhook_signature_payload = self
+ .encode_to_string_of_json()
+ .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
+ .attach_printable("failed encoding outgoing webhook payload")?;
let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}");
let v1 = hex::encode(
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index a79826e2f19..05c1a0ede97 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2,6 +2,7 @@
use api_models::payouts::PayoutMethodData;
use api_models::{enums, payments, webhooks};
use cards::CardNumber;
+use common_utils::ext_traits::Encode;
use error_stack::ResultExt;
use masking::PeekInterface;
use reqwest::Url;
@@ -3331,32 +3332,26 @@ pub fn get_qr_metadata(
qr_code_url,
display_to_timestamp,
};
- Some(common_utils::ext_traits::Encode::<
- payments::QrCodeInformation,
- >::encode_to_value(&qr_code_info))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ Some(qr_code_info.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
} else if let (None, Some(qr_code_url)) = (image_data_url.clone(), qr_code_url.clone()) {
let qr_code_info = payments::QrCodeInformation::QrCodeImageUrl {
qr_code_url,
display_to_timestamp,
};
- Some(common_utils::ext_traits::Encode::<
- payments::QrCodeInformation,
- >::encode_to_value(&qr_code_info))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ Some(qr_code_info.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
} else if let (Some(image_data_url), None) = (image_data_url, qr_code_url) {
let qr_code_info = payments::QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp,
};
- Some(common_utils::ext_traits::Encode::<
- payments::QrCodeInformation,
- >::encode_to_value(&qr_code_info))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ Some(qr_code_info.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
} else {
Ok(None)
}
@@ -3481,11 +3476,9 @@ pub fn get_present_to_shopper_metadata(
instructions_url: response.action.instructions_url.clone(),
};
- Some(common_utils::ext_traits::Encode::<
- payments::VoucherNextStepData,
- >::encode_to_value(&voucher_data))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ Some(voucher_data.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
PaymentType::PermataBankTransfer
| PaymentType::BcaBankTransfer
@@ -3503,11 +3496,9 @@ pub fn get_present_to_shopper_metadata(
}),
);
- Some(common_utils::ext_traits::Encode::<
- payments::DokuBankTransferInstructions,
- >::encode_to_value(&voucher_data))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ Some(voucher_data.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
}
PaymentType::Affirm
| PaymentType::Afterpaytouch
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 3377457f38a..bc5bfe86ca1 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -581,9 +581,7 @@ impl<F, T>
.account_number
.as_ref()
.map(|acc_no| {
- Encode::<'_, PaymentDetails>::encode_to_value(
- &construct_refund_payment_details(acc_no.clone()),
- )
+ construct_refund_payment_details(acc_no.clone()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
@@ -658,9 +656,7 @@ impl<F, T>
.account_number
.as_ref()
.map(|acc_no| {
- Encode::<'_, PaymentDetails>::encode_to_value(
- &construct_refund_payment_details(acc_no.clone()),
- )
+ construct_refund_payment_details(acc_no.clone()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index f1c27d72749..63ca7750303 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -294,13 +294,10 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
)),
api::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
api_models::payments::WalletData::GooglePay(payment_method_data) => {
- let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json(
- &BluesnapGooglePayObject {
- payment_method_data: utils::GooglePayWalletData::from(
- payment_method_data,
- ),
- },
- )
+ let gpay_object = BluesnapGooglePayObject {
+ payment_method_data: utils::GooglePayWalletData::from(payment_method_data),
+ }
+ .encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
@@ -350,25 +347,21 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
address.push(add)
}
- let apple_pay_object = Encode::<EncodedPaymentToken>::encode_to_string_of_json(
- &EncodedPaymentToken {
- token: ApplepayPaymentData {
- payment_data: apple_pay_payment_data,
- payment_method: payment_method_data
- .payment_method
- .to_owned()
- .into(),
- transaction_identifier: payment_method_data.transaction_identifier,
- },
- billing_contact: BillingDetails {
- country_code: billing_address.country,
- address_lines: Some(address),
- family_name: billing_address.last_name.to_owned(),
- given_name: billing_address.first_name.to_owned(),
- postal_code: billing_address.zip,
- },
+ let apple_pay_object = EncodedPaymentToken {
+ token: ApplepayPaymentData {
+ payment_data: apple_pay_payment_data,
+ payment_method: payment_method_data.payment_method.to_owned().into(),
+ transaction_identifier: payment_method_data.transaction_identifier,
},
- )
+ billing_contact: BillingDetails {
+ country_code: billing_address.country,
+ address_lines: Some(address),
+ family_name: billing_address.last_name.to_owned(),
+ given_name: billing_address.first_name.to_owned(),
+ postal_code: billing_address.zip,
+ },
+ }
+ .encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index cf1b5a1498d..0d26584c43b 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -2,7 +2,11 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
+use common_utils::{
+ crypto,
+ ext_traits::{ByteSliceExt, Encode},
+ request::RequestContent,
+};
use diesel_models::enums;
use error_stack::{IntoReport, ResultExt};
use masking::PeekInterface;
@@ -30,7 +34,6 @@ use crate::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
- utils,
utils::BytesExt,
};
@@ -1297,7 +1300,8 @@ impl api::IncomingWebhook for Checkout {
} else {
// if payment_event, construct PaymentResponse and then serialize it to json and return.
let payment_response = checkout::PaymentsResponse::try_from(request)?;
- utils::Encode::<checkout::PaymentsResponse>::encode_to_value(&payment_response)
+ payment_response
+ .encode_to_value()
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
};
// Ideally this should be a strict type that has type information
diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs
index 5cb22890b7c..c988bff52ea 100644
--- a/crates/router/src/connector/globepay/transformers.rs
+++ b/crates/router/src/connector/globepay/transformers.rs
@@ -1,3 +1,4 @@
+use common_utils::ext_traits::Encode;
use error_stack::ResultExt;
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -169,11 +170,9 @@ impl<F, T>
.qrcode_img
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
};
- let connector_metadata = Some(common_utils::ext_traits::Encode::<
- GlobepayConnectorMetadata,
- >::encode_to_value(&globepay_metadata))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+ let connector_metadata = Some(globepay_metadata.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_status = item
.response
.result_code
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index bbd7da234b6..fff99109b28 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{ext_traits::Encode, pii};
use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -11,7 +11,6 @@ use crate::{
core::{errors, mandate::MandateBehaviour},
services,
types::{self, api, storage::enums, transformers::ForeignFrom, ErrorResponse},
- utils,
};
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
@@ -271,10 +270,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
),
},
};
- let payment_token =
- utils::Encode::<NoonApplePayTokenData>::encode_to_string_of_json(
- &payment_token_data,
- )
+ let payment_token = payment_token_data
+ .encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(NoonPaymentData::ApplePay(NoonApplePay {
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 4ed6b25b136..d5dd6e813ae 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1,7 +1,9 @@
use api_models::payments;
use common_utils::{
crypto::{self, GenerateDigest},
- date_time, fp_utils, pii,
+ date_time,
+ ext_traits::Encode,
+ fp_utils, pii,
pii::Email,
};
use data_models::mandates::MandateDataType;
@@ -433,23 +435,14 @@ impl TryFrom<payments::GooglePayWalletData> for NuveiPaymentsRequest {
Ok(Self {
payment_option: PaymentOption {
card: Some(Card {
- external_token:
- Some(
- ExternalToken {
- external_token_provider: ExternalTokenProvider::GooglePay,
- mobile_token:
- Secret::new(
- common_utils::ext_traits::Encode::<
- payments::GooglePayWalletData,
- >::encode_to_string_of_json(
- &utils::GooglePayWalletData::from(gpay_data),
- )
- .change_context(
- errors::ConnectorError::RequestEncodingFailed,
- )?,
- ),
- },
+ external_token: Some(ExternalToken {
+ external_token_provider: ExternalTokenProvider::GooglePay,
+ mobile_token: Secret::new(
+ utils::GooglePayWalletData::from(gpay_data)
+ .encode_to_string_of_json()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
+ }),
..Default::default()
}),
..Default::default()
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index e8801e3222b..90b4b0b0bba 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -407,11 +407,7 @@ impl<F, T>
let metadata = item
.response
.transaction_tag
- .map(|txn_tag| {
- Encode::<'_, PayeezyPaymentsMetadata>::encode_to_value(
- &construct_payeezy_payments_metadata(txn_tag),
- )
- })
+ .map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index 9bf5101e8b8..b487740d07d 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -2,7 +2,11 @@ pub mod transformers;
use std::fmt::Debug;
use base64::Engine;
-use common_utils::{date_time, ext_traits::StringExt, request::RequestContent};
+use common_utils::{
+ date_time,
+ ext_traits::{Encode, StringExt},
+ request::RequestContent,
+};
use diesel_models::enums;
use error_stack::{IntoReport, Report, ResultExt};
use masking::{ExposeInterface, PeekInterface};
@@ -938,19 +942,16 @@ impl api::IncomingWebhook for Rapyd {
transformers::WebhookData::Payment(payment_data) => {
let rapyd_response: transformers::RapydPaymentsResponse = payment_data.into();
- utils::Encode::<transformers::RapydPaymentsResponse>::encode_to_value(
- &rapyd_response,
- )
- .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
- }
- transformers::WebhookData::Refund(refund_data) => {
- utils::Encode::<transformers::RefundResponseData>::encode_to_value(&refund_data)
- .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
- }
- transformers::WebhookData::Dispute(dispute_data) => {
- utils::Encode::<transformers::DisputeResponseData>::encode_to_value(&dispute_data)
+ rapyd_response
+ .encode_to_value()
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?
}
+ transformers::WebhookData::Refund(refund_data) => refund_data
+ .encode_to_value()
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?,
+ transformers::WebhookData::Dispute(dispute_data) => dispute_data
+ .encode_to_value()
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?,
};
Ok(Box::new(res_json))
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 6a89232d4e8..8c370317c62 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Deref};
use api_models::{self, enums as api_enums, payments};
use common_utils::{
errors::CustomResult,
- ext_traits::ByteSliceExt,
+ ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
};
@@ -2437,11 +2437,7 @@ pub fn get_connector_metadata(
},
};
- Some(common_utils::ext_traits::Encode::<
- SepaAndBacsBankTransferInstructions,
- >::encode_to_value(
- &bank_transfer_instructions
- ))
+ Some(bank_transfer_instructions.encode_to_value())
}
StripeNextActionResponse::WechatPayDisplayQrCode(response) => {
let wechat_pay_instructions = QrCodeNextInstructions {
@@ -2449,22 +2445,14 @@ pub fn get_connector_metadata(
display_to_timestamp: None,
};
- Some(
- common_utils::ext_traits::Encode::<QrCodeNextInstructions>::encode_to_value(
- &wechat_pay_instructions,
- ),
- )
+ Some(wechat_pay_instructions.encode_to_value())
}
StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => {
let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions {
image_data_url: response.qr_code.image_url_png.to_owned(),
display_to_timestamp: response.qr_code.expires_at.to_owned(),
};
- Some(
- common_utils::ext_traits::Encode::<QrCodeNextInstructions>::encode_to_value(
- &cashapp_qr_instructions,
- ),
- )
+ Some(cashapp_qr_instructions.encode_to_value())
}
_ => None,
})
@@ -3144,10 +3132,8 @@ impl<F, T>
item: types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_source_response = item.response.to_owned();
- let connector_metadata =
- common_utils::ext_traits::Encode::<StripeSourceResponse>::encode_to_value(
- &connector_source_response,
- )
+ let connector_metadata = connector_source_response
+ .encode_to_value()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
// We get pending as the status from stripe, but hyperswitch should give it as requires_customer_action as
// customer has to make payment to the virtual account number given in the source response
@@ -3201,10 +3187,9 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme
item: types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_source_response = item.response.to_owned();
- let connector_metadata =
- common_utils::ext_traits::Encode::<StripeSourceResponse>::encode_to_value(
- &connector_source_response.source,
- )
+ let connector_metadata = connector_source_response
+ .source
+ .encode_to_value()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let status = enums::AttemptStatus::from(item.response.status);
let response = if connector_util::is_payment_failure(status) {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 024ef653faa..4f0ad733805 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -62,36 +62,39 @@ pub async fn create_merchant_account(
let publishable_key = Some(create_merchant_publishable_key());
- let primary_business_details =
- utils::Encode::<Vec<admin_types::PrimaryBusinessDetails>>::encode_to_value(
- &req.primary_business_details.clone().unwrap_or_default(),
- )
+ let primary_business_details = req
+ .primary_business_details
+ .clone()
+ .unwrap_or_default()
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "primary_business_details",
})?;
- let merchant_details: OptionalSecretValue =
- req.merchant_details
- .as_ref()
- .map(|merchant_details| {
- utils::Encode::<api::MerchantDetails>::encode_to_value(merchant_details)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "merchant_details",
- })
- })
- .transpose()?
- .map(Into::into);
+ let merchant_details: OptionalSecretValue = req
+ .merchant_details
+ .as_ref()
+ .map(|merchant_details| {
+ merchant_details.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "merchant_details",
+ },
+ )
+ })
+ .transpose()?
+ .map(Into::into);
- let webhook_details =
- req.webhook_details
- .as_ref()
- .map(|webhook_details| {
- utils::Encode::<api::WebhookDetails>::encode_to_value(webhook_details)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "webhook details",
- })
- })
- .transpose()?;
+ let webhook_details = req
+ .webhook_details
+ .as_ref()
+ .map(|webhook_details| {
+ webhook_details.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "webhook details",
+ },
+ )
+ })
+ .transpose()?;
if let Some(ref routing_algorithm) = req.routing_algorithm {
let _: api_models::routing::RoutingAlgorithm = routing_algorithm
@@ -134,7 +137,7 @@ pub async fn create_merchant_account(
.metadata
.as_ref()
.map(|meta| {
- utils::Encode::<admin_types::MerchantAccountMetadata>::encode_to_value(meta)
+ meta.encode_to_value()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata",
})
@@ -493,12 +496,11 @@ pub async fn merchant_account_update(
.primary_business_details
.as_ref()
.map(|primary_business_details| {
- utils::Encode::<Vec<admin_types::PrimaryBusinessDetails>>::encode_to_value(
- primary_business_details,
+ primary_business_details.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "primary_business_details",
+ },
)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "primary_business_details",
- })
})
.transpose()?;
@@ -548,7 +550,7 @@ pub async fn merchant_account_update(
merchant_details: req
.merchant_details
.as_ref()
- .map(utils::Encode::<api::MerchantDetails>::encode_to_value)
+ .map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to convert merchant_details to a value")?
@@ -563,7 +565,7 @@ pub async fn merchant_account_update(
webhook_details: req
.webhook_details
.as_ref()
- .map(utils::Encode::<api::WebhookDetails>::encode_to_value)
+ .map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
@@ -817,7 +819,8 @@ pub async fn create_payment_connector(
let payment_methods_enabled = match req.payment_methods_enabled {
Some(val) => {
for pm in val.into_iter() {
- let pm_value = utils::Encode::<api::PaymentMethodsEnabled>::encode_to_value(&pm)
+ let pm_value = pm
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed while encoding to serde_json::Value, PaymentMethod",
@@ -929,8 +932,7 @@ pub async fn create_payment_connector(
id: None,
connector_webhook_details: match req.connector_webhook_details {
Some(connector_webhook_details) => {
- Encode::<api_models::admin::MerchantConnectorWebhookDetails>::encode_to_value(
- &connector_webhook_details,
+ connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {}", merchant_id))
@@ -1155,9 +1157,7 @@ pub async fn update_payment_connector(
let payment_methods_enabled = req.payment_methods_enabled.map(|pm_enabled| {
pm_enabled
.iter()
- .flat_map(|payment_method| {
- utils::Encode::<api::PaymentMethodsEnabled>::encode_to_value(payment_method)
- })
+ .flat_map(Encode::encode_to_value)
.collect::<Vec<serde_json::Value>>()
});
@@ -1249,14 +1249,11 @@ pub async fn update_payment_connector(
metadata: req.metadata,
frm_configs,
connector_webhook_details: match &req.connector_webhook_details {
- Some(connector_webhook_details) => {
- Encode::<api_models::admin::MerchantConnectorWebhookDetails>::encode_to_value(
- connector_webhook_details,
- )
+ Some(connector_webhook_details) => connector_webhook_details
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(Some)?
- .map(masking::Secret::new)
- }
+ .map(masking::Secret::new),
None => None,
},
applepay_verified_domains: None,
@@ -1434,7 +1431,8 @@ pub fn get_frm_config_as_secret(
let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value
.iter()
.map(|config| {
- utils::Encode::<api_models::admin::FrmConfigs>::encode_to_value(&config)
+ config
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::ConfigNotFound)
.map(masking::Secret::new)
})
@@ -1597,7 +1595,7 @@ pub async fn update_business_profile(
.webhook_details
.as_ref()
.map(|webhook_details| {
- utils::Encode::<api::WebhookDetails>::encode_to_value(webhook_details).change_context(
+ webhook_details.encode_to_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "webhook details",
},
@@ -1619,10 +1617,11 @@ pub async fn update_business_profile(
.payment_link_config
.as_ref()
.map(|pl_metadata| {
- utils::Encode::<admin_types::BusinessPaymentLinkConfig>::encode_to_value(pl_metadata)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ pl_metadata.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_link_config",
- })
+ },
+ )
})
.transpose()?;
diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs
index e30d11ef6f2..26789470c20 100644
--- a/crates/router/src/core/conditional_config.rs
+++ b/crates/router/src/core/conditional_config.rs
@@ -1,8 +1,8 @@
use api_models::{
conditional_configs::{DecisionManager, DecisionManagerRecord, DecisionManagerResponse},
- routing::{self},
+ routing,
};
-use common_utils::ext_traits::{StringExt, ValueExt};
+use common_utils::ext_traits::{Encode, StringExt, ValueExt};
use diesel_models::configs;
use error_stack::{IntoReport, ResultExt};
use euclid::frontend::ast;
@@ -15,7 +15,7 @@ use crate::{
routes::AppState,
services::api as service_api,
types::domain,
- utils::{self, OptionExt},
+ utils::OptionExt,
};
pub async fn upsert_conditional_config(
@@ -86,10 +86,10 @@ pub async fn upsert_conditional_config(
created_at: previous_record.created_at,
};
- let serialize_updated_str =
- utils::Encode::<DecisionManagerRecord>::encode_to_string_of_json(&new_algo)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize config to string")?;
+ let serialize_updated_str = new_algo
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize config to string")?;
let updated_config = configs::ConfigUpdate::Update {
config: Some(serialize_updated_str),
@@ -121,10 +121,10 @@ pub async fn upsert_conditional_config(
created_at: timestamp,
};
- let serialized_str =
- utils::Encode::<DecisionManagerRecord>::encode_to_string_of_json(&new_rec)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error serializing the config")?;
+ let serialized_str = new_rec
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error serializing the config")?;
let new_config = configs::ConfigNew {
key: key.clone(),
config: serialized_str,
diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs
index f18681f8cfd..644a2220aee 100644
--- a/crates/router/src/core/connector_onboarding/paypal.rs
+++ b/crates/router/src/core/connector_onboarding/paypal.rs
@@ -141,10 +141,10 @@ pub async fn update_mca(
connector_id: String,
auth_details: oss_types::ConnectorAuthType,
) -> RouterResult<oss_api_types::MerchantConnectorResponse> {
- let connector_auth_json =
- Encode::<oss_types::ConnectorAuthType>::encode_to_value(&auth_details)
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Error while deserializing connector_account_details")?;
+ let connector_auth_json = auth_details
+ .encode_to_value()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while deserializing connector_account_details")?;
let request = MerchantConnectorUpdate {
connector_type: common_enums::ConnectorType::PaymentProcessor,
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 285baa33d1a..f53939a8f9d 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -1,5 +1,5 @@
use api_models::{disputes as dispute_models, files as files_api_models};
-use common_utils::ext_traits::ValueExt;
+use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::{IntoReport, ResultExt};
use router_env::{instrument, tracing};
pub mod transformers;
@@ -20,7 +20,6 @@ use crate::{
AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData,
DefendDisputeResponse, SubmitEvidenceRequestData, SubmitEvidenceResponse,
},
- utils,
};
#[instrument(skip(state))]
@@ -384,7 +383,8 @@ pub async fn attach_evidence(
file_id,
);
let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate {
- evidence: utils::Encode::<api::DisputeEvidence>::encode_to_value(&updated_dispute_evidence)
+ evidence: updated_dispute_evidence
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while encoding dispute evidence")?
.into(),
@@ -446,7 +446,8 @@ pub async fn delete_evidence(
let updated_dispute_evidence =
transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type);
let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate {
- evidence: utils::Encode::<api::DisputeEvidence>::encode_to_value(&updated_dispute_evidence)
+ evidence: updated_dispute_evidence
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while encoding dispute evidence")?
.into(),
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index 8bb8a61402e..95349e44755 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -77,9 +77,9 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
- let payment_details: Option<serde_json::Value> =
- Encode::<PaymentDetails>::encode_to_value(&PaymentDetails::from(payment_data.clone()))
- .ok();
+ let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
+ .encode_to_value()
+ .ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.payment_id.clone(),
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
index b92df3d3ef9..ed582574bf5 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
@@ -72,9 +72,9 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
- let payment_details: Option<serde_json::Value> =
- Encode::<PaymentDetails>::encode_to_value(&PaymentDetails::from(payment_data.clone()))
- .ok();
+ let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
+ .encode_to_value()
+ .ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index d58eae371e8..ec3bb7e4299 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -162,7 +162,7 @@ pub async fn update_connector_mandate_id(
let connector_mandate_id = mandate_details
.clone()
.map(|md| {
- Encode::<types::MandateReference>::encode_to_value(&md)
+ md.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(masking::Secret::new)
})
@@ -288,10 +288,10 @@ where
update_history: Some(update_history),
};
- let connector_mandate_ids =
- Encode::<types::MandateReference>::encode_to_value(&updated_mandate_ref)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .map(masking::Secret::new)?;
+ let connector_mandate_ids = updated_mandate_ref
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .map(masking::Secret::new)?;
let _update_mandate_details = state
.store
@@ -384,7 +384,7 @@ where
let mandate_ids = mandate_reference
.as_ref()
.map(|md| {
- Encode::<types::MandateReference>::encode_to_value(&md)
+ md.encode_to_value()
.change_context(
errors::ApiErrorResponse::MandateSerializationFailed,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 4f6d6b4c62b..823d0e321d9 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -18,7 +18,7 @@ use api_models::{
};
use common_utils::{
consts,
- ext_traits::{AsyncExt, StringExt, ValueExt},
+ ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
generate_id,
};
use diesel_models::{
@@ -1568,7 +1568,8 @@ pub async fn list_payment_methods(
routing_info.pre_routing_results = Some(pre_routing_results);
- let encoded = utils::Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_info)
+ let encoded = routing_info
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize payment routing info to value")?;
@@ -3220,11 +3221,13 @@ impl TempLockerCardSupport {
let value1 = vault::VaultPaymentMethod::Card(value1);
let value2 = vault::VaultPaymentMethod::Card(value2);
- let value1 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value1)
+ let value1 = value1
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value1 construction failed when saving card to locker")?;
- let value2 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value2)
+ let value2 = value2
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value2 construction failed when saving card to locker")?;
@@ -3359,7 +3362,7 @@ pub async fn create_encrypted_payment_method_data(
let pm_data_encrypted: Option<Encryption> = pm_data
.as_ref()
- .map(utils::Encode::<PaymentMethodsData>::encode_to_value)
+ .map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Unable to convert payment method data to a value")
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 59b02d01933..e6d447b5497 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -1,7 +1,11 @@
use std::str::FromStr;
use api_models::enums as api_enums;
-use common_utils::{ext_traits::StringExt, pii::Email, request::RequestContent};
+use common_utils::{
+ ext_traits::{Encode, StringExt},
+ pii::Email,
+ request::RequestContent,
+};
use error_stack::ResultExt;
use josekit::jwe;
use serde::{Deserialize, Serialize};
@@ -13,7 +17,7 @@ use crate::{
pii::{prelude::*, Secret},
services::{api as services, encryption},
types::{api, storage},
- utils::{self, OptionExt},
+ utils::OptionExt,
};
#[derive(Debug, Serialize)]
@@ -261,7 +265,8 @@ pub async fn mk_basilisk_req(
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
- let payload = utils::Encode::<encryption::JwsBody>::encode_to_vec(&jws_body)
+ let payload = jws_body
+ .encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
#[cfg(feature = "aws_kms")]
@@ -306,7 +311,8 @@ pub async fn mk_add_locker_request_hs<'a>(
payload: &StoreLockerReq<'a>,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<services::Request, errors::VaultError> {
- let payload = utils::Encode::<StoreLockerReq<'_>>::encode_to_vec(&payload)
+ let payload = payload
+ .encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
#[cfg(feature = "aws_kms")]
@@ -484,7 +490,8 @@ pub async fn mk_get_card_request_hs(
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
- let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body)
+ let payload = card_req_body
+ .encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
#[cfg(feature = "aws_kms")]
@@ -560,7 +567,8 @@ pub async fn mk_delete_card_request_hs(
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
- let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body)
+ let payload = card_req_body
+ .encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
#[cfg(feature = "aws_kms")]
@@ -672,7 +680,8 @@ pub fn mk_card_value1(
card_last_four,
card_token,
};
- let value1_req = utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1)
+ let value1_req = value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value1_req)
}
@@ -691,7 +700,8 @@ pub fn mk_card_value2(
customer_id,
payment_method_id,
};
- let value2_req = utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2)
+ let value2_req = value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value2_req)
}
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 25bac8086d7..b547027a1c7 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1,6 +1,6 @@
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
- ext_traits::BytesExt,
+ ext_traits::{BytesExt, Encode},
generate_id_with_default_len,
};
use error_stack::{report, IntoReport, ResultExt};
@@ -19,7 +19,7 @@ use crate::{
api, domain,
storage::{self, enums, ProcessTrackerExt},
},
- utils::{self, StringExt},
+ utils::StringExt,
};
const VAULT_SERVICE_NAME: &str = "CARD";
@@ -54,7 +54,8 @@ impl Vaultable for api::Card {
card_token: None,
};
- utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
@@ -68,7 +69,8 @@ impl Vaultable for api::Card {
payment_method_id: None,
};
- utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
@@ -121,7 +123,8 @@ impl Vaultable for api_models::payments::BankTransferData {
data: self.to_owned(),
};
- utils::Encode::<api_models::payment_methods::TokenizedBankTransferValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer data")
}
@@ -129,7 +132,8 @@ impl Vaultable for api_models::payments::BankTransferData {
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
let value2 = api_models::payment_methods::TokenizedBankTransferValue2 { customer_id };
- utils::Encode::<api_models::payment_methods::TokenizedBankTransferValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer supplementary data")
}
@@ -165,7 +169,8 @@ impl Vaultable for api::WalletData {
data: self.to_owned(),
};
- utils::Encode::<api::TokenizedWalletValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value1")
}
@@ -173,7 +178,8 @@ impl Vaultable for api::WalletData {
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedWalletValue2 { customer_id };
- utils::Encode::<api::TokenizedWalletValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value2")
}
@@ -209,7 +215,8 @@ impl Vaultable for api_models::payments::BankRedirectData {
data: self.to_owned(),
};
- utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect data")
}
@@ -217,7 +224,8 @@ impl Vaultable for api_models::payments::BankRedirectData {
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
let value2 = api_models::payment_methods::TokenizedBankRedirectValue2 { customer_id };
- utils::Encode::<api_models::payment_methods::TokenizedBankRedirectValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect supplementary data")
}
@@ -272,7 +280,8 @@ impl Vaultable for api::PaymentMethodData {
.attach_printable("Payment method not supported")?,
};
- utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value1")
}
@@ -292,7 +301,8 @@ impl Vaultable for api::PaymentMethodData {
.attach_printable("Payment method not supported")?,
};
- utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value2")
}
@@ -357,7 +367,8 @@ impl Vaultable for api::CardPayout {
card_token: None,
};
- utils::Encode::<api::TokenizedCardValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
@@ -371,7 +382,8 @@ impl Vaultable for api::CardPayout {
payment_method_id: None,
};
- utils::Encode::<api::TokenizedCardValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
@@ -420,7 +432,8 @@ impl Vaultable for api::WalletPayout {
},
};
- utils::Encode::<api::TokenizedWalletValue1>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet value1")
}
@@ -428,7 +441,8 @@ impl Vaultable for api::WalletPayout {
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedWalletValue2 { customer_id };
- utils::Encode::<api::TokenizedWalletValue2>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet value2")
}
@@ -509,11 +523,10 @@ impl Vaultable for api::BankPayout {
},
};
- utils::Encode::<TokenizedBankSensitiveValues>::encode_to_string_of_json(
- &bank_sensitive_data,
- )
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode wallet data bank_sensitive_data")
+ bank_sensitive_data
+ .encode_to_string_of_json()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode wallet data bank_sensitive_data")
}
fn get_value2(&self, customer_id: Option<String>) -> CustomResult<String, errors::VaultError> {
@@ -538,11 +551,10 @@ impl Vaultable for api::BankPayout {
},
};
- utils::Encode::<TokenizedBankInsensitiveValues>::encode_to_string_of_json(
- &bank_insensitive_data,
- )
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode wallet data bank_insensitive_data")
+ bank_insensitive_data
+ .encode_to_string_of_json()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode wallet data bank_insensitive_data")
}
fn from_values(
@@ -619,7 +631,8 @@ impl Vaultable for api::PayoutMethodData {
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?),
};
- utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value1)
+ value1
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value1")
}
@@ -631,7 +644,8 @@ impl Vaultable for api::PayoutMethodData {
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?),
};
- utils::Encode::<VaultPaymentMethod>::encode_to_string_of_json(&value2)
+ value2
+ .encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value2")
}
@@ -822,10 +836,9 @@ pub async fn create_tokenize(
service_name: VAULT_SERVICE_NAME.to_string(),
};
- let payload = utils::Encode::<api::TokenizePayloadRequest>::encode_to_string_of_json(
- &payload_to_be_encrypted,
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let payload = payload_to_be_encrypted
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 38f2df57063..7348a2b8f0c 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2553,10 +2553,11 @@ where
)
.await?;
- let encoded_info =
- Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_data.routing_info)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error serializing payment routing info to serde value")?;
+ let encoded_info = routing_data
+ .routing_info
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("error serializing payment routing info to serde value")?;
payment_data.payment_attempt.connector = routing_data.routed_through;
#[cfg(feature = "connector_choice_mca_id")]
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 2a0aa793385..6bbe1c89a47 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -18,7 +18,6 @@ use crate::{
routes::AppState,
services,
types::{
- self,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
@@ -91,7 +90,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let browser_info = request
.browser_info
.clone()
- .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x))
+ .as_ref()
+ .map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 8349f050135..734839c9b6d 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -25,7 +25,6 @@ use crate::{
routes::AppState,
services,
types::{
- self,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
@@ -354,7 +353,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.browser_info
.clone()
.or(payment_attempt.browser_info)
- .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x))
+ .as_ref()
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
@@ -697,7 +697,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
})
.await
.as_ref()
- .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0f581be3089..2eaa11f44ee 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -149,9 +149,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let browser_info = request
.browser_info
.clone()
- .map(|x| {
- common_utils::ext_traits::Encode::<types::BrowserInformation>::encode_to_value(&x)
- })
+ .as_ref()
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
@@ -708,7 +707,7 @@ impl PaymentCreate {
.await;
let additional_pm_data_value = additional_pm_data
.as_ref()
- .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
@@ -933,12 +932,11 @@ async fn create_payment_link(
payment_id.clone()
);
- let payment_link_config_encoded_value = common_utils::ext_traits::Encode::<
- api_models::admin::PaymentLinkConfig,
- >::encode_to_value(&payment_link_config)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config",
- })?;
+ let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ },
+ )?;
let payment_link_req = storage::PaymentLinkNew {
payment_link_id: payment_link_id.clone(),
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 0666c921422..6bd6ca91100 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -2,6 +2,7 @@ use std::collections::HashMap;
use async_trait::async_trait;
use common_enums::AuthorizationStatus;
+use common_utils::ext_traits::Encode;
use data_models::payments::payment_attempt::PaymentAttempt;
use error_stack::{report, IntoReport, ResultExt};
use futures::FutureExt;
@@ -21,7 +22,6 @@ use crate::{
utils as core_utils,
},
routes::{metrics, AppState},
- services::RedirectForm,
types::{
self, api,
storage::{self, enums},
@@ -590,7 +590,8 @@ 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
- .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data))
+ .as_ref()
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 4e301302abc..0ec11e39f62 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -520,7 +520,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
})
.await
.as_ref()
- .map(Encode::<api_models::payments::AdditionalPaymentData>::encode_to_value)
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 8d74eb3fa96..91b6061c111 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -1,5 +1,6 @@
use std::{str::FromStr, vec::IntoIter};
+use common_utils::ext_traits::Encode;
use diesel_models::enums as storage_enums;
use error_stack::{IntoReport, ResultExt};
use router_env::{
@@ -20,8 +21,7 @@ use crate::{
db::StorageInterface,
routes,
routes::{app, metrics},
- services::{self, RedirectForm},
- types,
+ services, types,
types::{api, domain, storage},
utils,
};
@@ -352,7 +352,8 @@ where
let encoded_data = payment_data.payment_attempt.encoded_data.clone();
let authentication_data = redirection_data
- .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data))
+ .as_ref()
+ .map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 41a8850ab3d..e957fe5faa5 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -336,7 +336,8 @@ impl SurchargeMetadata {
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
- Encode::<SurchargeDetails>::encode_to_string_of_json(&value)
+ value
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index e9ddcb4a563..c544a987ba8 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -162,10 +162,10 @@ pub async fn create_routing_config(
#[cfg(not(feature = "business_profile_routing"))]
{
- let algorithm_str =
- utils::Encode::<routing_types::RoutingAlgorithm>::encode_to_string_of_json(&algorithm)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize routing algorithm to string")?;
+ let algorithm_str = algorithm
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize routing algorithm to string")?;
let mut algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_account
.routing_algorithm
@@ -548,10 +548,10 @@ pub async fn unlink_routing_config(
)
.await?;
- let ref_value =
- Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&routing_algorithm)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed converting routing algorithm ref to json value")?;
+ let ref_value = routing_algorithm
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed converting routing algorithm ref to json value")?;
let merchant_account_update = storage::MerchantAccountUpdate::Update {
merchant_name: None,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index c86e527b00d..71010e9bf8b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -15,7 +15,7 @@ use crate::{
core::errors::{self, RouterResult},
db::StorageInterface,
types::{domain, storage},
- utils::{self, StringExt},
+ utils::StringExt,
};
/// provides the complete merchant routing dictionary that is basically a list of all the routing
@@ -42,10 +42,8 @@ pub async fn get_merchant_routing_dictionary(
records: Vec::new(),
};
- let serialized =
- utils::Encode::<routing_types::RoutingDictionary>::encode_to_string_of_json(
- &new_dictionary,
- )
+ let serialized = new_dictionary
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing newly created merchant dictionary")?;
@@ -86,10 +84,8 @@ pub async fn get_merchant_default_config(
Err(e) if e.current_context().is_db_not_found() => {
let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new();
- let serialized =
- utils::Encode::<Vec<routing_types::RoutableConnectorChoice>>::encode_to_string_of_json(
- &new_config_conns,
- )
+ let serialized = new_config_conns
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while creating and serializing new merchant default config",
@@ -122,10 +118,8 @@ pub async fn update_merchant_default_config(
connectors: Vec<routing_types::RoutableConnectorChoice>,
) -> RouterResult<()> {
let key = get_default_config_key(merchant_id);
- let config_str =
- Encode::<Vec<routing_types::RoutableConnectorChoice>>::encode_to_string_of_json(
- &connectors,
- )
+ let config_str = connectors
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize merchant default routing config during update")?;
@@ -147,10 +141,10 @@ pub async fn update_merchant_routing_dictionary(
dictionary: routing_types::RoutingDictionary,
) -> RouterResult<()> {
let key = get_routing_dictionary_key(merchant_id);
- let dictionary_str =
- Encode::<routing_types::RoutingDictionary>::encode_to_string_of_json(&dictionary)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize routing dictionary during update")?;
+ let dictionary_str = dictionary
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize routing dictionary during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(dictionary_str),
@@ -169,10 +163,10 @@ pub async fn update_routing_algorithm(
algorithm_id: String,
algorithm: routing_types::RoutingAlgorithm,
) -> RouterResult<()> {
- let algorithm_str =
- Encode::<routing_types::RoutingAlgorithm>::encode_to_string_of_json(&algorithm)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize routing algorithm to string")?;
+ let algorithm_str = algorithm
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize routing algorithm to string")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(algorithm_str),
@@ -193,7 +187,8 @@ pub async fn update_merchant_active_algorithm_ref(
key_store: &domain::MerchantKeyStore,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
- let ref_value = Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&algorithm_id)
+ let ref_value = algorithm_id
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed converting routing algorithm ref to json value")?;
@@ -236,7 +231,8 @@ pub async fn update_business_profile_active_algorithm_ref(
current_business_profile: BusinessProfile,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
- let ref_val = Encode::<routing_types::RoutingAlgorithmRef>::encode_to_value(&algorithm_id)
+ let ref_val = algorithm_id
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?;
@@ -282,10 +278,8 @@ pub async fn get_merchant_connector_agnostic_mandate_config(
Err(e) if e.current_context().is_db_not_found() => {
let new_mandate_config: Vec<routing_types::DetailedConnectorChoice> = Vec::new();
- let serialized =
- utils::Encode::<Vec<routing_types::DetailedConnectorChoice>>::encode_to_string_of_json(
- &new_mandate_config,
- )
+ let serialized = new_mandate_config
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error serializing newly created pg agnostic mandate config")?;
@@ -314,10 +308,8 @@ pub async fn update_merchant_connector_agnostic_mandate_config(
mandate_config: Vec<routing_types::DetailedConnectorChoice>,
) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> {
let key = get_pg_agnostic_mandate_config_key(merchant_id);
- let mandate_config_str =
- Encode::<Vec<routing_types::DetailedConnectorChoice>>::encode_to_string_of_json(
- &mandate_config,
- )
+ let mandate_config_str = mandate_config
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to serialize pg agnostic mandate config during update")?;
diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs
index 82615aef284..a17be6ce36e 100644
--- a/crates/router/src/core/surcharge_decision_config.rs
+++ b/crates/router/src/core/surcharge_decision_config.rs
@@ -1,11 +1,11 @@
use api_models::{
- routing::{self},
+ routing,
surcharge_decision_configs::{
SurchargeDecisionConfigReq, SurchargeDecisionManagerRecord,
SurchargeDecisionManagerResponse,
},
};
-use common_utils::ext_traits::{StringExt, ValueExt};
+use common_utils::ext_traits::{Encode, StringExt, ValueExt};
use diesel_models::configs;
use error_stack::{IntoReport, ResultExt};
use euclid::frontend::ast;
@@ -18,7 +18,7 @@ use crate::{
routes::AppState,
services::api as service_api,
types::domain,
- utils::{self, OptionExt},
+ utils::OptionExt,
};
pub async fn upsert_surcharge_decision_config(
@@ -75,10 +75,8 @@ pub async fn upsert_surcharge_decision_config(
merchant_surcharge_configs,
};
- let serialize_updated_str =
- utils::Encode::<SurchargeDecisionManagerRecord>::encode_to_string_of_json(
- &new_algo,
- )
+ let serialize_updated_str = new_algo
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize config to string")?;
@@ -113,10 +111,10 @@ pub async fn upsert_surcharge_decision_config(
created_at: timestamp,
};
- let serialized_str =
- utils::Encode::<SurchargeDecisionManagerRecord>::encode_to_string_of_json(&new_rec)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error serializing the config")?;
+ let serialized_str = new_rec
+ .encode_to_string_of_json()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error serializing the config")?;
let new_config = configs::ConfigNew {
key: key.clone(),
config: serialized_str,
diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs
index fd1babc2065..a0e999971c5 100644
--- a/crates/router/src/core/webhooks/types.rs
+++ b/crates/router/src/core/webhooks/types.rs
@@ -1,5 +1,5 @@
use api_models::webhooks;
-use common_utils::{crypto::SignMessage, ext_traits};
+use common_utils::{crypto::SignMessage, ext_traits::Encode};
use error_stack::ResultExt;
use serde::Serialize;
@@ -21,10 +21,10 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook {
&self,
payment_response_hash_key: Option<String>,
) -> errors::CustomResult<Option<String>, errors::WebhooksFlowError> {
- let webhook_signature_payload =
- ext_traits::Encode::<serde_json::Value>::encode_to_string_of_json(self)
- .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
- .attach_printable("failed encoding outgoing webhook payload")?;
+ let webhook_signature_payload = self
+ .encode_to_string_of_json()
+ .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
+ .attach_printable("failed encoding outgoing webhook payload")?;
Ok(payment_response_hash_key
.map(|key| {
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 0dd20721c3a..d01c4f3784d 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -69,9 +69,9 @@ impl ConnectorAccessToken for Store {
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
let key = format!("access_token_{merchant_id}_{connector_name}");
- let serialized_access_token =
- Encode::<types::AccessToken>::encode_to_string_of_json(&access_token)
- .change_context(errors::StorageError::SerializationFailed)?;
+ let serialized_access_token = access_token
+ .encode_to_string_of_json()
+ .change_context(errors::StorageError::SerializationFailed)?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_key_with_expiry(&key, serialized_access_token, access_token.expires)
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index accb5e8f3f9..9664c29eedc 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -267,7 +267,7 @@ mod storage {
#[cfg(feature = "kv_store")]
mod storage {
- use common_utils::{date_time, fallback_reverse_lookup_not_found};
+ use common_utils::{date_time, ext_traits::Encode, fallback_reverse_lookup_not_found};
use error_stack::{IntoReport, ResultExt};
use redis_interface::HsetnxReply;
use storage_impl::redis::kv_store::{kv_wrapper, KvOperation};
@@ -279,7 +279,7 @@ mod storage {
db::reverse_lookup::ReverseLookupInterface,
services::Store,
types::storage::{self as storage_types, enums, kv},
- utils::{self, db_utils},
+ utils::db_utils,
};
#[async_trait::async_trait]
impl RefundInterface for Store {
@@ -520,10 +520,8 @@ mod storage {
let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id);
let updated_refund = refund.clone().apply_changeset(this.clone());
- let redis_value =
- utils::Encode::<storage_types::Refund>::encode_to_string_of_json(
- &updated_refund,
- )
+ let redis_value = updated_refund
+ .encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index ef7047bffab..89ca36c8c15 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -299,7 +299,8 @@ impl ParentPaymentMethodToken {
token: PaymentTokenData,
state: &AppState,
) -> CustomResult<(), errors::ApiErrorResponse> {
- let token_json_str = Encode::<PaymentTokenData>::encode_to_string_of_json(&token)
+ let token_json_str = token
+ .encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to serialize hyperswitch token to json")?;
let redis_conn = state
diff --git a/crates/router/src/routes/payments/helpers.rs b/crates/router/src/routes/payments/helpers.rs
index 7a1c26b0572..256767f2aea 100644
--- a/crates/router/src/routes/payments/helpers.rs
+++ b/crates/router/src/routes/payments/helpers.rs
@@ -73,7 +73,8 @@ pub fn populate_ip_into_browser_info(
.or_else(|| ip_address_from_header.map(|ip| masking::Secret::new(ip.to_string())));
}
- let encoded = Encode::<types::BrowserInformation>::encode_to_value(&browser_info)
+ let encoded = browser_info
+ .encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to re-encode browser information to json after setting ip address",
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 0157f741d97..b51368da676 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -407,7 +407,7 @@ where
let response = match body {
Ok(body) => {
let connector_http_status_code = Some(body.status_code);
- match connector_integration
+ let handle_response_result = connector_integration
.handle_response(req, Some(&mut connector_event), body)
.map_err(|error| {
if error.current_context()
@@ -423,40 +423,43 @@ where
)
}
error
- }) {
- Ok(mut data) => {
-
- match connector_event.try_into() {
- Ok(event) => {
- state.event_handler().log_event(event);
- }
- Err(err) => {
- logger::error!(error=?err, "Error Logging Connector Event");
- }
- };
- data.connector_http_status_code = connector_http_status_code;
- // Add up multiple external latencies in case of multiple external calls within the same request.
- data.external_latency = Some(
- data.external_latency
- .map_or(external_latency, |val| val + external_latency),
- );
- Ok(data)
- },
- Err(err) => {
-
- connector_event.set_error(json!({"error": err.to_string()}));
-
- match connector_event.try_into() {
- Ok(event) => {
- state.event_handler().log_event(event);
- }
- Err(err) => {
- logger::error!(error=?err, "Error Logging Connector Event");
- }
+ });
+ match handle_response_result {
+ Ok(mut data) => {
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
}
- Err(err)
- },
- }?
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ };
+ data.connector_http_status_code =
+ connector_http_status_code;
+ // Add up multiple external latencies in case of multiple external calls within the same request.
+ data.external_latency = Some(
+ data.external_latency
+ .map_or(external_latency, |val| {
+ val + external_latency
+ }),
+ );
+ Ok(data)
+ }
+ Err(err) => {
+ connector_event
+ .set_error(json!({"error": err.to_string()}));
+
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
+ }
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ }
+ Err(err)
+ }
+ }?
}
Err(body) => {
router_data.connector_http_status_code = Some(body.status_code);
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 487cea88d15..bf76a7339a2 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -7,14 +7,13 @@ pub use api_models::admin::{
PaymentMethodsEnabled, PayoutRoutingAlgorithm, PayoutStraightThroughAlgorithm, ToggleKVRequest,
ToggleKVResponse, WebhookDetails,
};
-use common_utils::ext_traits::ValueExt;
+use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
use masking::Secret;
use crate::{
core::errors,
types::{domain, storage, transformers::ForeignTryFrom},
- utils::{self},
};
impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {
@@ -95,10 +94,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.webhook_details
.as_ref()
.map(|webhook_details| {
- common_utils::ext_traits::Encode::<WebhookDetails>::encode_to_value(webhook_details)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ webhook_details.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
field_name: "webhook details",
- })
+ },
+ )
})
.transpose()?;
@@ -110,12 +110,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
let payment_link_config_value = request
.payment_link_config
.map(|pl_config| {
- utils::Encode::<api_models::admin::BusinessPaymentLinkConfig>::encode_to_value(
- &pl_config,
+ pl_config.encode_to_value().change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config_value",
+ },
)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config_value",
- })
})
.transpose()?;
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 8d20dfe0f32..7efbafb662d 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -160,9 +160,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.apply_changeset(origin_diesel_intent.clone());
// Check for database presence as well Maybe use a read replica here ?
- let redis_value =
- Encode::<DieselPaymentIntent>::encode_to_string_of_json(&diesel_intent)
- .change_context(StorageError::SerializationFailed)?;
+ let redis_value = diesel_intent
+ .encode_to_string_of_json()
+ .change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
| 2024-02-16T13:05:34Z |
## Description
<!-- Describe your changes in detail -->
This PR simplifies the definition of the `common_utils::ext_traits::Encode` trait to simplify the invocation of the trait methods.
In addition, this PR addresses a clippy lint introduced in Rust 1.76.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #3685.
# | 783fa0b0dff1e157920d683a75fc579942cd9c06 |
The changes in this should work fine as long as the code compiles. However, sanity testing can be performed by running Postman collection(s). I have performed sanity testing locally by successfully creating a payment and refund via Postman.
| [
"add_connector.md",
"crates/api_models/src/payments.rs",
"crates/common_utils/src/ext_traits.rs",
"crates/redis_interface/src/commands.rs",
"crates/router/src/compatibility/stripe/webhooks.rs",
"crates/router/src/connector/adyen/transformers.rs",
"crates/router/src/connector/authorizedotnet/transformers... | |
juspay/hyperswitch | juspay__hyperswitch-3683 | Bug: Handle span closures after request completion or after consolidated log...
Currently some consolidated logs don't have the values propogated all the way to the top,
This seems to be a result of the way we handle the consolidated log & value propogation
In this case the consolidated log line is printed before the spans are closed resulting in values not being propogated at the top
<img width="1445" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/fdbd4858-e432-4347-9a28-c28046566f38">
| diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index f1a3275ab21..2cab332a677 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -143,7 +143,7 @@ where
Box::pin(
async move {
let response = response_fut.await;
- logger::info!(golden_log_line = true);
+ router_env::tracing::Span::current().record("golden_log_line", true);
response
}
.instrument(
@@ -153,7 +153,8 @@ where
merchant_id = Empty,
connector_name = Empty,
payment_method = Empty,
- flow = "UNKNOWN"
+ flow = "UNKNOWN",
+ golden_log_line = Empty
)
.or_current(),
),
diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs
index 664c0d508f5..09d285a8628 100644
--- a/crates/router_env/src/logger/config.rs
+++ b/crates/router_env/src/logger/config.rs
@@ -107,13 +107,15 @@ pub struct LogTelemetry {
/// Telemetry / tracing.
#[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)]
-#[serde(rename_all = "lowercase")]
+#[serde(rename_all = "snake_case")]
pub enum LogFormat {
/// Default pretty log format
Default,
/// JSON based structured logging
#[default]
Json,
+ /// JSON based structured logging with pretty print
+ PrettyJson,
}
impl Config {
diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs
index 4fd94c22163..472b917e746 100644
--- a/crates/router_env/src/logger/formatter.rs
+++ b/crates/router_env/src/logger/formatter.rs
@@ -10,7 +10,7 @@ use std::{
use once_cell::sync::Lazy;
use serde::ser::{SerializeMap, Serializer};
-use serde_json::Value;
+use serde_json::{ser::Formatter, Value};
// use time::format_description::well_known::Rfc3339;
use time::format_description::well_known::Iso8601;
use tracing::{Event, Metadata, Subscriber};
@@ -121,9 +121,10 @@ impl fmt::Display for RecordType {
/// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries.
///
#[derive(Debug)]
-pub struct FormattingLayer<W>
+pub struct FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
+ F: Formatter + Clone,
{
dst_writer: W,
pid: u32,
@@ -135,11 +136,13 @@ where
#[cfg(feature = "vergen")]
build: String,
default_fields: HashMap<String, Value>,
+ formatter: F,
}
-impl<W> FormattingLayer<W>
+impl<W, F> FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
+ F: Formatter + Clone,
{
///
/// Constructor of `FormattingLayer`.
@@ -149,11 +152,11 @@ where
///
/// ## Example
/// ```rust
- /// let formatting_layer = router_env::FormattingLayer::new(router_env::service_name!(),std::io::stdout);
+ /// let formatting_layer = router_env::FormattingLayer::new(router_env::service_name!(),std::io::stdout, CompactFormatter);
/// ```
///
- pub fn new(service: &str, dst_writer: W) -> Self {
- Self::new_with_implicit_entries(service, dst_writer, HashMap::new())
+ pub fn new(service: &str, dst_writer: W, formatter: F) -> Self {
+ Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter)
}
/// Construct of `FormattingLayer with implicit default entries.
@@ -161,6 +164,7 @@ where
service: &str,
dst_writer: W,
default_fields: HashMap<String, Value>,
+ formatter: F,
) -> Self {
let pid = std::process::id();
let hostname = gethostname::gethostname().to_string_lossy().into_owned();
@@ -182,6 +186,7 @@ where
#[cfg(feature = "vergen")]
build,
default_fields,
+ formatter,
}
}
@@ -287,7 +292,6 @@ where
}
/// Serialize entries of span.
- #[cfg(feature = "log_active_span_json")]
fn span_serialize<S>(
&self,
span: &SpanRef<'_, S>,
@@ -297,7 +301,8 @@ where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
- let mut serializer = serde_json::Serializer::new(&mut buffer);
+ let mut serializer =
+ serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
@@ -324,7 +329,8 @@ where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
- let mut serializer = serde_json::Serializer::new(&mut buffer);
+ let mut serializer =
+ serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let mut storage = Storage::default();
@@ -398,10 +404,11 @@ where
}
#[allow(clippy::expect_used)]
-impl<S, W> Layer<S> for FormattingLayer<W>
+impl<S, W, F> Layer<S> for FormattingLayer<W, F>
where
S: Subscriber + for<'a> LookupSpan<'a>,
W: for<'a> MakeWriter<'a> + 'static,
+ F: Formatter + Clone + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
// Event could have no span.
@@ -421,6 +428,16 @@ where
}
}
+ #[cfg(not(feature = "log_active_span_json"))]
+ fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
+ let span = ctx.span(&id).expect("No span");
+ if span.parent().is_none() {
+ if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
+ let _ = self.flush(serialized);
+ }
+ }
+ }
+
#[cfg(feature = "log_active_span_json")]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index 992de3e747e..af77991e804 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -16,6 +16,7 @@ use opentelemetry::{
KeyValue,
};
use opentelemetry_otlp::{TonicExporterBuilder, WithExportConfig};
+use serde_json::ser::{CompactFormatter, PrettyFormatter};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer};
@@ -69,7 +70,10 @@ pub fn setup(
);
println!("Using file logging filter: {file_filter}");
- Some(FormattingLayer::new(service_name, file_writer).with_filter(file_filter))
+ Some(
+ FormattingLayer::new(service_name, file_writer, CompactFormatter)
+ .with_filter(file_filter),
+ )
} else {
None
};
@@ -104,7 +108,15 @@ pub fn setup(
config::LogFormat::Json => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
let logging_layer =
- FormattingLayer::new(service_name, console_writer).with_filter(console_filter);
+ FormattingLayer::new(service_name, console_writer, CompactFormatter)
+ .with_filter(console_filter);
+ subscriber.with(logging_layer).init();
+ }
+ config::LogFormat::PrettyJson => {
+ error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
+ let logging_layer =
+ FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())
+ .with_filter(console_filter);
subscriber.with(logging_layer).init();
}
}
| 2024-02-16T11:10:32Z |
## Description
<!-- Describe your changes in detail -->
- Add `pretty_json` log format for console logs
- Add span end log for root span close as the default behaviour
- move consolidated log from event to span close
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | fb254b8924808e6a2b2a9a31dbed78749836e8d3 |
- running it locally check for the last log line after any request
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_st84Q3ucbQSWWnUbPwQXAyefTD2w5gJsRN8GEQ0shegg1ZomnwsseEdJU3KjVoAp' \
--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://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- It should contain every field in consolidated log
<img width="463" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/dc279a45-1b16-40d4-bb88-5433b458f0f3">
[grafana](https://grafana.staging.eu.juspay.net/explore?orgId=1&left=%7B%22datasource%22:%22x5WTfCG4k%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22expr%22:%22%7Bapp%3D%5C%22bach%5C%22,%20golden_log_line%3D%5C%22true%5C%22%7D%20%7C%3D%20%60%60%22,%22queryType%22:%22range%22,%22datasource%22:%7B%22type%22:%22loki%22,%22uid%22:%22x5WTfCG4k%22%7D,%22editorMode%22:%22builder%22%7D%5D,%22range%22:%7B%22from%22:%22now-1h%22,%22to%22:%22now%22%7D%7D)
```json
{
"message": "[ROOT_SPAN - END]",
"hostname": "sampraslopes-SERIAL.local",
"pid": 3422,
"env": "development",
"level": "INFO",
"target": "router::middleware",
"service": "router",
"line": 150,
"file": "crates/router/src/middleware.rs",
"fn": "ROOT_SPAN",
"full_name": "router::middleware::ROOT_SPAN",
"time": "2024-02-16T10:31:12.692105000Z",
"flow": "PaymentsConfirm",
"request_id": "018db178-5a8f-7a9d-ac46-218510ab655a",
"merchant_id": "merchant_1707203569",
"extra": {
"connector_name": "stripe",
"http.scheme": "http",
"http.user_agent": "PostmanRuntime/7.33.0",
"http.host": "localhost:8080",
"http.target": "/payments/pay_tIvDNoPTya0pP7SiTJAU/confirm",
"otel.name": "HTTP POST /payments/{payment_id}/confirm",
"trace_id": "00000000000000000000000000000000",
"payment_id": "pay_tIvDNoPTya0pP7SiTJAU",
"payment_method": "card",
"elapsed_milliseconds": 1443,
"http.flavor": "1.1",
"golden_log_line": true,
"http.route": "/payments/{payment_id}/confirm",
"http.method": "POST",
"otel.kind": "server",
"http.client_ip": "::1"
}
}
```
| [
"crates/router/src/middleware.rs",
"crates/router_env/src/logger/config.rs",
"crates/router_env/src/logger/formatter.rs",
"crates/router_env/src/logger/setup.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3765 | Bug: [FEATURE] : mask pii information in connector request and response for stripe, aci, adyen, airwallex and authorizedotnet
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index ed56fc5f524..fe621bccd05 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -3,7 +3,7 @@ use std::str::FromStr;
use api_models::enums::BankNames;
use common_utils::pii::Email;
use error_stack::report;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
@@ -382,7 +382,7 @@ pub struct Instruction {
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct BankDetails {
#[serde(rename = "bankAccount.holder")]
- pub account_holder: String,
+ pub account_holder: Secret<String>,
}
#[allow(dead_code)]
@@ -657,10 +657,11 @@ impl FromStr for AciPaymentStatus {
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
- registration_id: Option<String>,
+ registration_id: Option<Secret<String>>,
// ndc is an internal unique identifier for the request.
ndc: String,
timestamp: String,
+ // Number useful for support purposes.
build_number: String,
pub(super) result: ResultCode,
pub(super) redirect: Option<AciRedirectionData>,
@@ -734,7 +735,7 @@ impl<F, T>
.response
.registration_id
.map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
+ connector_mandate_id: Some(id.expose()),
payment_method_id: None,
});
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index c634d38c614..0c22b0413a3 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -7,6 +7,7 @@ use base64::Engine;
use common_utils::request::RequestContent;
use diesel_models::{enums as storage_enums, enums};
use error_stack::{IntoReport, ResultExt};
+use masking::ExposeInterface;
use ring::hmac;
use router_env::{instrument, tracing};
@@ -467,8 +468,10 @@ impl
.response
.parse_struct("AdyenCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -610,8 +613,10 @@ impl
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
let is_multiple_capture_sync = match data.request.sync_type {
types::SyncRequestType::MultipleCaptureSync(_) => true,
types::SyncRequestType::SinglePaymentSync => false,
@@ -1513,7 +1518,7 @@ impl api::IncomingWebhook for Adyen {
let notif_item = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
- let base64_signature = notif_item.additional_data.hmac_signature;
+ let base64_signature = notif_item.additional_data.hmac_signature.expose();
Ok(base64_signature.as_bytes().to_vec())
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 05c1a0ede97..8070a9ec325 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -4,7 +4,7 @@ use api_models::{enums, payments, webhooks};
use cards::CardNumber;
use common_utils::ext_traits::Encode;
use error_stack::ResultExt;
-use masking::PeekInterface;
+use masking::{ExposeInterface, PeekInterface};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime, PrimitiveDateTime};
@@ -95,10 +95,10 @@ pub struct AdditionalData {
pub recurring_processing_model: Option<AdyenRecurringModel>,
/// Enable recurring details in dashboard to receive this ID, https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#test-and-go-live
#[serde(rename = "recurring.recurringDetailReference")]
- recurring_detail_reference: Option<String>,
+ recurring_detail_reference: Option<Secret<String>>,
#[serde(rename = "recurring.shopperReference")]
recurring_shopper_reference: Option<String>,
- network_tx_reference: Option<String>,
+ network_tx_reference: Option<Secret<String>>,
#[cfg(feature = "payouts")]
payout_eligible: Option<PayoutEligibility>,
funds_availability: Option<String>,
@@ -553,7 +553,7 @@ pub struct JCSVoucherData {
first_name: Secret<String>,
last_name: Option<Secret<String>>,
shopper_email: Email,
- telephone_number: String,
+ telephone_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -604,14 +604,6 @@ pub struct BacsDirectDebitData {
holder_name: Secret<String>,
}
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct MandateData {
- #[serde(rename = "type")]
- payment_type: PaymentType,
- stored_payment_method_id: String,
-}
-
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BancontactCardData {
@@ -674,7 +666,7 @@ impl TryFrom<&Box<payments::JCSVoucherData>> for JCSVoucherData {
first_name: jcs_data.first_name.clone(),
last_name: jcs_data.last_name.clone(),
shopper_email: jcs_data.email.clone(),
- telephone_number: jcs_data.phone_number.clone(),
+ telephone_number: Secret::new(jcs_data.phone_number.clone()),
})
}
}
@@ -1031,7 +1023,7 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer {
pub struct BlikRedirectionData {
#[serde(rename = "type")]
payment_type: PaymentType,
- blik_code: String,
+ blik_code: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -1047,7 +1039,7 @@ pub struct BankRedirectionWithIssuer<'a> {
pub struct AdyenMandate {
#[serde(rename = "type")]
payment_type: PaymentType,
- stored_payment_method_id: String,
+ stored_payment_method_id: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -1060,7 +1052,7 @@ pub struct AdyenCard {
expiry_year: Secret<String>,
cvc: Option<Secret<String>>,
brand: Option<CardBrand>, //Mandatory for mandate using network_txns_id
- network_payment_reference: Option<String>,
+ network_payment_reference: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -1143,7 +1135,7 @@ pub struct AdyenRefundRequest {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRefundResponse {
- merchant_account: String,
+ merchant_account: Secret<String>,
psp_reference: String,
payment_psp_reference: String,
reference: String,
@@ -2131,11 +2123,11 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod
api_models::payments::BankRedirectData::Blik { blik_code } => {
Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData {
payment_type: PaymentType::Blik,
- blik_code: blik_code.clone().ok_or(
+ blik_code: Secret::new(blik_code.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "blik_code",
},
- )?,
+ )?),
})))
}
api_models::payments::BankRedirectData::Eps { bank_name, .. } => Ok(
@@ -2357,7 +2349,9 @@ impl<'a>
payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => {
let adyen_mandate = AdyenMandate {
payment_type: PaymentType::try_from(payment_method_type)?,
- stored_payment_method_id: connector_mandate_ids.get_connector_mandate_id()?,
+ stored_payment_method_id: Secret::new(
+ connector_mandate_ids.get_connector_mandate_id()?,
+ ),
};
Ok::<AdyenPaymentMethod<'_>, Self::Error>(AdyenPaymentMethod::Mandate(Box::new(
adyen_mandate,
@@ -2375,7 +2369,7 @@ impl<'a>
expiry_year: card.card_exp_year.clone(),
cvc: None,
brand: Some(brand),
- network_payment_reference: Some(network_mandate_id),
+ network_payment_reference: Some(Secret::new(network_mandate_id)),
};
Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card)))
}
@@ -3047,12 +3041,14 @@ pub fn get_adyen_response(
.as_ref()
.and_then(|data| data.recurring_detail_reference.to_owned())
.map(|mandate_id| types::MandateReference {
- connector_mandate_id: Some(mandate_id),
+ connector_mandate_id: Some(mandate_id.expose()),
payment_method_id: None,
});
- let network_txn_id = response
- .additional_data
- .and_then(|additional_data| additional_data.network_tx_reference);
+ let network_txn_id = response.additional_data.and_then(|additional_data| {
+ additional_data
+ .network_tx_reference
+ .map(|network_tx_id| network_tx_id.expose())
+ });
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference),
@@ -3314,7 +3310,7 @@ pub fn get_redirection_error_response(
pub fn get_qr_metadata(
response: &QrCodeResponseResponse,
) -> errors::CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
- let image_data = crate_utils::QrImage::new_from_data(response.action.qr_code_data.to_owned())
+ let image_data = crate_utils::QrImage::new_from_data(response.action.qr_code_data.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str()).ok();
@@ -3636,7 +3632,7 @@ impl TryFrom<&AdyenRouterData<&types::PaymentsCaptureRouterData>> for AdyenCaptu
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCaptureResponse {
- merchant_account: String,
+ merchant_account: Secret<String>,
payment_psp_reference: String,
psp_reference: String,
reference: String,
@@ -3789,7 +3785,7 @@ pub enum DisputeStatus {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAdditionalDataWH {
- pub hmac_signature: String,
+ pub hmac_signature: Secret<String>,
pub dispute_status: Option<DisputeStatus>,
pub chargeback_reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index a788a4a2ab0..defc6a339fb 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -522,8 +522,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("airwallex AirwallexPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::PaymentsSyncRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 692458715f7..767d1c8a6e0 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -1,5 +1,5 @@
use error_stack::{IntoReport, ResultExt};
-use masking::PeekInterface;
+use masking::{ExposeInterface, PeekInterface};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
@@ -416,10 +416,10 @@ pub enum AirwallexNextActionStage {
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexRedirectFormData {
#[serde(rename = "JWT")]
- jwt: Option<String>,
+ jwt: Option<Secret<String>>,
#[serde(rename = "threeDSMethodData")]
- three_ds_method_data: Option<String>,
- token: Option<String>,
+ three_ds_method_data: Option<Secret<String>>,
+ token: Option<Secret<String>>,
provider: Option<String>,
version: Option<String>,
}
@@ -439,7 +439,7 @@ pub struct AirwallexPaymentsResponse {
id: String,
amount: Option<f32>,
//ID of the PaymentConsent related to this PaymentIntent
- payment_consent_id: Option<String>,
+ payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexPaymentsNextAction>,
}
@@ -450,7 +450,7 @@ pub struct AirwallexPaymentsSyncResponse {
id: String,
amount: Option<f32>,
//ID of the PaymentConsent related to this PaymentIntent
- payment_consent_id: Option<String>,
+ payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexPaymentsNextAction>,
}
@@ -464,18 +464,27 @@ fn get_redirection_form(
//Some form fields might be empty based on the authentication type by the connector
(
"JWT".to_string(),
- response_url_data.data.jwt.unwrap_or_default(),
+ response_url_data
+ .data
+ .jwt
+ .map(|jwt| jwt.expose())
+ .unwrap_or_default(),
),
(
"threeDSMethodData".to_string(),
response_url_data
.data
.three_ds_method_data
+ .map(|three_ds_method_data| three_ds_method_data.expose())
.unwrap_or_default(),
),
(
"token".to_string(),
- response_url_data.data.token.unwrap_or_default(),
+ response_url_data
+ .data
+ .token
+ .map(|token: Secret<String>| token.expose())
+ .unwrap_or_default(),
),
(
"provider".to_string(),
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 04704a90919..ba232c01bbf 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -212,8 +212,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -353,7 +355,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
))?;
let connector_req =
authorizedotnet::CreateTransactionRequest::try_from(&connector_router_data)?;
-
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -400,8 +401,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index bc5bfe86ca1..eb5f13881fb 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -3,7 +3,7 @@ use common_utils::{
ext_traits::{Encode, ValueExt},
};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret, StrongSecret};
+use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use serde::{Deserialize, Serialize};
use crate::{
@@ -119,7 +119,7 @@ pub struct PayPalDetails {
#[serde(rename_all = "camelCase")]
pub struct WalletDetails {
pub data_descriptor: WalletMethod,
- pub data_value: String,
+ pub data_value: Secret<String>,
}
#[derive(Serialize, Debug, Deserialize)]
@@ -147,14 +147,12 @@ fn get_pm_and_subsequent_auth_detail(
.to_owned()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
- Some(api_models::payments::MandateReferenceId::NetworkMandateId(
- original_network_trans_id,
- )) => {
+ Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
let processing_options = Some(ProcessingOptions {
is_subsequent_auth: true,
});
let subseuent_auth_info = Some(SubsequentAuthInformation {
- original_network_trans_id,
+ original_network_trans_id: Secret::new(network_trans_id),
reason: Reason::Resubmission,
});
match item.router_data.request.payment_method_data {
@@ -225,7 +223,7 @@ pub struct ProcessingOptions {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsequentAuthInformation {
- original_network_trans_id: String,
+ original_network_trans_id: Secret<String>,
// original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions.
reason: Reason,
}
@@ -474,8 +472,8 @@ pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
#[serde(rename = "transId")]
transaction_id: String,
- network_trans_id: Option<String>,
- pub(super) account_number: Option<String>,
+ network_trans_id: Option<Secret<String>>,
+ pub(super) account_number: Option<Secret<String>>,
pub(super) errors: Option<Vec<ErrorMessage>>,
secure_acceptance: Option<SecureAcceptance>,
}
@@ -487,8 +485,8 @@ pub struct RefundResponse {
#[serde(rename = "transId")]
transaction_id: String,
#[allow(dead_code)]
- network_trans_id: Option<String>,
- pub account_number: Option<String>,
+ network_trans_id: Option<Secret<String>>,
+ pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
@@ -518,8 +516,8 @@ pub struct VoidResponse {
response_code: AuthorizedotnetVoidStatus,
#[serde(rename = "transId")]
transaction_id: String,
- network_trans_id: Option<String>,
- pub account_number: Option<String>,
+ network_trans_id: Option<Secret<String>>,
+ pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
@@ -581,7 +579,7 @@ impl<F, T>
.account_number
.as_ref()
.map(|acc_no| {
- construct_refund_payment_details(acc_no.clone()).encode_to_value()
+ construct_refund_payment_details(acc_no.clone().expose()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
@@ -604,7 +602,10 @@ impl<F, T>
redirection_data,
mandate_reference: None,
connector_metadata: metadata,
- network_txn_id: transaction_response.network_trans_id.clone(),
+ network_txn_id: transaction_response
+ .network_trans_id
+ .clone()
+ .map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
@@ -656,7 +657,7 @@ impl<F, T>
.account_number
.as_ref()
.map(|acc_no| {
- construct_refund_payment_details(acc_no.clone()).encode_to_value()
+ construct_refund_payment_details(acc_no.clone().expose()).encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
@@ -673,7 +674,10 @@ impl<F, T>
redirection_data: None,
mandate_reference: None,
connector_metadata: metadata,
- network_txn_id: transaction_response.network_trans_id.clone(),
+ network_txn_id: transaction_response
+ .network_trans_id
+ .clone()
+ .map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
@@ -1152,13 +1156,13 @@ fn get_wallet_data(
api_models::payments::WalletData::GooglePay(_) => {
Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
- data_value: wallet_data.get_encoded_wallet_token()?,
+ data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
}))
}
api_models::payments::WalletData::ApplePay(applepay_token) => {
Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
- data_value: applepay_token.payment_data.clone(),
+ data_value: Secret::new(applepay_token.payment_data.clone()),
}))
}
api_models::payments::WalletData::PaypalRedirect(_) => {
@@ -1215,7 +1219,7 @@ pub struct Paypal {
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalQueryParams {
#[serde(rename = "PayerID")]
- payer_id: String,
+ payer_id: Secret<String>,
}
impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
@@ -1232,12 +1236,11 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterD
.as_ref()
.and_then(|redirect_response| redirect_response.params.as_ref())
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
- let payer_id: Secret<String> = Secret::new(
+ let payer_id: Secret<String> =
serde_urlencoded::from_str::<PaypalQueryParams>(params.peek())
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
- .payer_id,
- );
+ .payer_id;
let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization,
_ => TransactionType::ContinueCapture,
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index b85725c249d..389e773da5e 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -1708,7 +1708,7 @@ impl
fn handle_response(
&self,
data: &types::RetrieveFileRouterData,
- _event_builder: Option<&mut ConnectorEvent>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
@@ -1719,7 +1719,10 @@ impl
errors::ConnectorError,
> {
let response = res.response;
- router_env::logger::info!(connector_response=?response);
+
+ event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code})));
+ router_env::logger::info!(connector_response_type=?"file");
+
Ok(types::RetrieveFileRouterData {
response: Ok(types::RetrieveFileResponse {
file_data: response.to_vec(),
@@ -1737,6 +1740,7 @@ impl
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 8c370317c62..a40abced13a 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -188,7 +188,7 @@ pub struct TokenRequest {
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeTokenResponse {
- pub id: String,
+ pub id: Secret<String>,
pub object: String,
}
@@ -198,7 +198,7 @@ pub struct CustomerRequest {
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
- pub source: Option<String>,
+ pub source: Option<Secret<String>>,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
@@ -324,7 +324,7 @@ pub struct StripeBlik {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[blik][code]")]
- pub code: String,
+ pub code: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
@@ -499,7 +499,7 @@ pub struct StripeApplePay {
pub pk_token: Secret<String>,
pub pk_token_instrument_name: String,
pub pk_token_payment_network: String,
- pub pk_token_transaction_id: String,
+ pub pk_token_transaction_id: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
@@ -547,7 +547,7 @@ pub enum WechatClient {
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct GooglepayPayment {
#[serde(rename = "payment_method_data[card][token]")]
- pub token: String,
+ pub token: Secret<String>,
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
@@ -1536,9 +1536,9 @@ impl TryFrom<(&payments::WalletData, Option<types::PaymentMethodToken>)>
.payment_method
.network
.to_owned(),
- pk_token_transaction_id: applepay_data
- .transaction_identifier
- .to_owned(),
+ pk_token_transaction_id: Secret::new(
+ applepay_data.transaction_identifier.to_owned(),
+ ),
})));
};
let pmd = apple_pay_decrypt_data
@@ -1611,11 +1611,11 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
payments::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect(
StripeBankRedirectData::StripeBlik(Box::new(StripeBlik {
payment_method_data_type,
- code: blik_code.clone().ok_or(
+ code: Secret::new(blik_code.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "blik_code",
},
- )?,
+ )?),
})),
)),
payments::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect(
@@ -2042,7 +2042,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest {
email: item.request.email.to_owned(),
phone: item.request.phone.to_owned(),
name: item.request.name.to_owned(),
- source: item.request.preprocessing_id.to_owned(),
+ source: item.request.preprocessing_id.to_owned().map(Secret::new),
})
}
}
@@ -2096,8 +2096,8 @@ pub struct PaymentIntentResponse {
pub status: StripePaymentStatus,
pub client_secret: Option<Secret<String>>,
pub created: i32,
- pub customer: Option<String>,
- pub payment_method: Option<String>,
+ pub customer: Option<Secret<String>>,
+ pub payment_method: Option<Secret<String>>,
pub description: Option<String>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
@@ -2206,7 +2206,7 @@ pub struct StripeCharge {
#[derive(Deserialize, Clone, Debug, Serialize)]
pub struct StripeBankRedirectDetails {
#[serde(rename = "generated_sepa_debit")]
- attached_payment_method: Option<String>,
+ attached_payment_method: Option<Secret<String>>,
}
impl Deref for PaymentIntentSyncResponse {
@@ -2308,7 +2308,7 @@ pub struct SetupIntentResponse {
pub object: String,
pub status: StripePaymentStatus, // Change to SetupStatus
pub client_secret: Secret<String>,
- pub customer: Option<String>,
+ pub customer: Option<Secret<String>>,
pub payment_method: Option<String>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
@@ -2327,7 +2327,7 @@ impl ForeignFrom<(Option<StripePaymentMethodOptions>, String)> for types::Mandat
connector_mandate_id: payment_method_options.and_then(|options| match options {
StripePaymentMethodOptions::Card {
mandate_options, ..
- } => mandate_options.map(|mandate_options| mandate_options.reference),
+ } => mandate_options.map(|mandate_options| mandate_options.reference.expose()),
StripePaymentMethodOptions::Klarna {}
| StripePaymentMethodOptions::Affirm {}
| StripePaymentMethodOptions::AfterpayClearpay {}
@@ -2369,7 +2369,10 @@ impl<F, T>
});
let mandate_reference = item.response.payment_method.map(|pm| {
- types::MandateReference::foreign_from((item.response.payment_method_options, pm))
+ types::MandateReference::foreign_from((
+ item.response.payment_method_options,
+ pm.expose(),
+ ))
});
//Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
@@ -2488,14 +2491,19 @@ impl<F, T>
Some(StripeChargeEnum::ChargeObject(charge)) => {
match charge.payment_method_details {
Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
- bancontact.attached_payment_method.unwrap_or(pm)
- }
- Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => {
- ideal.attached_payment_method.unwrap_or(pm)
- }
- Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => {
- sofort.attached_payment_method.unwrap_or(pm)
+ bancontact
+ .attached_payment_method
+ .map(|attached_payment_method| attached_payment_method.expose())
+ .unwrap_or(pm.expose())
}
+ Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
+ .attached_payment_method
+ .map(|attached_payment_method| attached_payment_method.expose())
+ .unwrap_or(pm.expose()),
+ Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort
+ .attached_payment_method
+ .map(|attached_payment_method| attached_payment_method.expose())
+ .unwrap_or(pm.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
@@ -2513,10 +2521,10 @@ impl<F, T>
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
- | None => pm,
+ | None => pm.expose(),
}
}
- Some(StripeChargeEnum::ChargeId(_)) | None => pm,
+ Some(StripeChargeEnum::ChargeId(_)) | None => pm.expose(),
},
))
});
@@ -2751,17 +2759,17 @@ pub struct StripeFinanicalInformation {
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SepaFinancialDetails {
- pub account_holder_name: String,
- pub bic: String,
- pub country: String,
- pub iban: String,
+ pub account_holder_name: Secret<String>,
+ pub bic: Secret<String>,
+ pub country: Secret<String>,
+ pub iban: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct BacsFinancialDetails {
- pub account_holder_name: String,
- pub account_number: String,
- pub sort_code: String,
+ pub account_holder_name: Secret<String>,
+ pub account_number: Secret<String>,
+ pub sort_code: Secret<String>,
}
// REFUND :
@@ -2962,7 +2970,7 @@ pub struct StripeBillingAddress {
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct StripeRedirectResponse {
pub payment_intent: Option<String>,
- pub payment_intent_client_secret: Option<String>,
+ pub payment_intent_client_secret: Option<Secret<String>>,
pub source_redirect_slug: Option<String>,
pub redirect_status: Option<StripePaymentStatus>,
pub source_type: Option<Secret<String>>,
@@ -3036,7 +3044,7 @@ pub struct LatestPaymentAttempt {
// pub struct Card
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
pub struct StripeMandateOptions {
- reference: String, // Extendable, But only important field to be captured
+ reference: Secret<String>, // Extendable, But only important field to be captured
}
/// Represents the capture request body for stripe connector.
#[derive(Debug, Serialize, Clone, Copy)]
@@ -3238,7 +3246,7 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PaymentsResponseData::TokenizationResponse {
- token: item.response.id,
+ token: item.response.id.expose(),
}),
..item.data
})
@@ -3619,7 +3627,7 @@ pub struct Evidence {
#[serde(rename = "evidence[access_activity_log]")]
pub access_activity_log: Option<String>,
#[serde(rename = "evidence[billing_address]")]
- pub billing_address: Option<String>,
+ pub billing_address: Option<Secret<String>>,
#[serde(rename = "evidence[cancellation_policy]")]
pub cancellation_policy: Option<String>,
#[serde(rename = "evidence[cancellation_policy_disclosure]")]
@@ -3629,17 +3637,17 @@ pub struct Evidence {
#[serde(rename = "evidence[customer_communication]")]
pub customer_communication: Option<String>,
#[serde(rename = "evidence[customer_email_address]")]
- pub customer_email_address: Option<String>,
+ pub customer_email_address: Option<Secret<String, pii::EmailStrategy>>,
#[serde(rename = "evidence[customer_name]")]
- pub customer_name: Option<String>,
+ pub customer_name: Option<Secret<String>>,
#[serde(rename = "evidence[customer_purchase_ip]")]
- pub customer_purchase_ip: Option<String>,
+ pub customer_purchase_ip: Option<Secret<String, pii::IpAddress>>,
#[serde(rename = "evidence[customer_signature]")]
- pub customer_signature: Option<String>,
+ pub customer_signature: Option<Secret<String>>,
#[serde(rename = "evidence[product_description]")]
pub product_description: Option<String>,
#[serde(rename = "evidence[receipt]")]
- pub receipt: Option<String>,
+ pub receipt: Option<Secret<String>>,
#[serde(rename = "evidence[refund_policy]")]
pub refund_policy: Option<String>,
#[serde(rename = "evidence[refund_policy_disclosure]")]
@@ -3651,15 +3659,15 @@ pub struct Evidence {
#[serde(rename = "evidence[service_documentation]")]
pub service_documentation: Option<String>,
#[serde(rename = "evidence[shipping_address]")]
- pub shipping_address: Option<String>,
+ pub shipping_address: Option<Secret<String>>,
#[serde(rename = "evidence[shipping_carrier]")]
pub shipping_carrier: Option<String>,
#[serde(rename = "evidence[shipping_date]")]
pub shipping_date: Option<String>,
#[serde(rename = "evidence[shipping_documentation]")]
- pub shipping_documentation: Option<String>,
+ pub shipping_documentation: Option<Secret<String>>,
#[serde(rename = "evidence[shipping_tracking_number]")]
- pub shipping_tracking_number: Option<String>,
+ pub shipping_tracking_number: Option<Secret<String>>,
#[serde(rename = "evidence[uncategorized_file]")]
pub uncategorized_file: Option<String>,
#[serde(rename = "evidence[uncategorized_text]")]
@@ -3708,31 +3716,46 @@ impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
access_activity_log: submit_evidence_request_data.access_activity_log,
- billing_address: submit_evidence_request_data.billing_address,
+ billing_address: submit_evidence_request_data
+ .billing_address
+ .map(Secret::new),
cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id,
cancellation_policy_disclosure: submit_evidence_request_data
.cancellation_policy_disclosure,
cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal,
customer_communication: submit_evidence_request_data
.customer_communication_provider_file_id,
- customer_email_address: submit_evidence_request_data.customer_email_address,
- customer_name: submit_evidence_request_data.customer_name,
- customer_purchase_ip: submit_evidence_request_data.customer_purchase_ip,
- customer_signature: submit_evidence_request_data.customer_signature_provider_file_id,
+ customer_email_address: submit_evidence_request_data
+ .customer_email_address
+ .map(Secret::new),
+ customer_name: submit_evidence_request_data.customer_name.map(Secret::new),
+ customer_purchase_ip: submit_evidence_request_data
+ .customer_purchase_ip
+ .map(Secret::new),
+ customer_signature: submit_evidence_request_data
+ .customer_signature_provider_file_id
+ .map(Secret::new),
product_description: submit_evidence_request_data.product_description,
- receipt: submit_evidence_request_data.receipt_provider_file_id,
+ receipt: submit_evidence_request_data
+ .receipt_provider_file_id
+ .map(Secret::new),
refund_policy: submit_evidence_request_data.refund_policy_provider_file_id,
refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure,
refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation,
service_date: submit_evidence_request_data.service_date,
service_documentation: submit_evidence_request_data
.service_documentation_provider_file_id,
- shipping_address: submit_evidence_request_data.shipping_address,
+ shipping_address: submit_evidence_request_data
+ .shipping_address
+ .map(Secret::new),
shipping_carrier: submit_evidence_request_data.shipping_carrier,
shipping_date: submit_evidence_request_data.shipping_date,
shipping_documentation: submit_evidence_request_data
- .shipping_documentation_provider_file_id,
- shipping_tracking_number: submit_evidence_request_data.shipping_tracking_number,
+ .shipping_documentation_provider_file_id
+ .map(Secret::new),
+ shipping_tracking_number: submit_evidence_request_data
+ .shipping_tracking_number
+ .map(Secret::new),
uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id,
uncategorized_text: submit_evidence_request_data.uncategorized_text,
submit: true,
| 2024-02-16T09:28:14Z |
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for stripe, aci, adyen, airwallex and authorizedotnet
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for all these connectors
1. Aci and Adyen payment create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {}' \
--data-raw '{
"amount": 10000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4917 6100 0000 0000",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Joseph Doe",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
,
"mandate_type": {
"multi_use": {
"amount": 799,
"currency": "USD"
}
}
}
}'
```
2.ACI mandate payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{}' \
--data '{
"amount": 700,
"currency": "USD",
"off_session": true,
"confirm": true,
"capture_method": "automatic",
"description": "Initiated by merchant",
"mandate_id": "man_Y214d8eLCfEpkyEmrN9s",
"customer_id": "StripeCustomer",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
}
}'
```
3. Airwallex 3Ds
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4012000300000088",
"card_exp_month": "10",
"card_exp_year": "2025",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
4. Stripe Apple pay
5. Authorize.dot Mandate Payment and refund
_Note: can't be tested, there is a known bug_
Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
1. Response for ACI - payment create
```
"masked_response\":\"{\\\"id\\\":\\\"8ac7a4a08de5447e018de582bb107592\\\",\\\"registrationId\\\":\\\"*** alloc::string::String ***\\\",\\\"ndc\\\":\\\"8ac7a4c97d044305017d053142b009ed_6c787329b2284b9689b010b7ee2ef803\\\",\\\"timestamp\\\":\\\"2024-02-26 13:02:46+0000\\\",\\\"buildNumber\\\":\\\"65a0c4e5cfd8d1606f555dfc25cfe3ab19688806@2024-02-23 04:43:28 +0000\\\",\\\"result\\\":{\\\"code\\\":\\\"000.100.110\\\",\\\"description\\\":\\\"Request successfully processed in 'Merchant in Integrator Test Mode'\\\",\\\"parameterErrors\\\":null}
```
3. Response for ACI - mandate payment
```
\"masked_response\":\"{\\\"id\\\":\\\"8ac7a49f8de5402f018de58580910358\\\",\\\"registrationId\\\":null,\\\"ndc\\\":\\\"8ac7a4c97d044305017d053142b009ed_0ba46b44820f4f81b7876e9e8efeccf0\\\",\\\"timestamp\\\":\\\"2024-02-26 13:05:48+0000\\\",\\\"buildNumber\\\":\\\"65a0c4e5cfd8d1606f555dfc25cfe3ab19688806@2024-02-23 04:43:28 +0000\\\",\\\"result\\\":{\\\"code\\\":\\\"000.100.110\\\",\\\"description\\\":\\\"Request successfully processed in 'Merchant in Integrator Test Mode'\\\",\\\"parameterErrors\\\":null},\\\"redirect\\\":null}
```
6. Response for Adyen - mandate payment
```
masked_response\":\"{\\\"pspReference\\\":\\\"N5SF6G38NXTQ7RT5\\\",\\\"resultCode\\\":\\\"Authorised\\\",\\\"amount\\\":{\\\"currency\\\":\\\"USD\\\",\\\"value\\\":10000},\\\"merchantReference\\\":\\\"pay_mf45Xy9Of4vVcMEIPqGj_1\\\",\\\"refusalReason\\\":null,\\\"refusalReasonCode\\\":null,\\\"additionalData\\\":{\\\"authorisationType\\\":null,\\\"manualCapture\\\":null,\\\"recurringProcessingModel\\\":\\\"UnscheduledCardOnFile\\\",\\\"recurring.recurringDetailReference\\\":\\\"*** alloc::string::String ***\\\",\\\"recurring.shopperReference\\\":\\\"merchant_1709011022_StripeCustomer\\\",\\\"networkTxReference\\\":\\\"*** alloc::string::String ***\\\",\\\"payoutEligible\\\":null,\\\"fundsAvailability\\\":null}
```
_Note: There is a known bug in adyen recurring mandate payment_
7.Response for Airwallex 3DS
```
{\\\"status\\\":\\\"REQUIRES_CUSTOMER_ACTION\\\",\\\"id\\\":\\\"int_hkdm5rvp6gtsl5v8q2w\\\",\\\"amount\\\":20.0,\\\"payment_consent_id\\\":null,\\\"next_action\\\":{\\\"url\\\":\\\"https://pci-api-demo.airwallex.com/pa/card3ds/hk/three-ds-method/redirect/start?key=1999b53e-ff3b-4b6e-aeaf-28ba23f4767b\\\",\\\"method\\\":\\\"POST\\\",\\\"data\\\":{\\\"JWT\\\":null,\\\"threeDSMethodData\\\":\\\"*** alloc::string::String ***\\\",\\\"token\\\":\\\"*** alloc::string::String ***\\\",\\\"provider\\\":null,\\\"version\\\":null},\\\"stage\\\":\\\"WAITING_DEVICE_DATA_COLLECTION\\\"}}
``` | df739a302b062277647afe5c3888015272fdc2cf | [
"crates/router/src/connector/aci/transformers.rs",
"crates/router/src/connector/adyen.rs",
"crates/router/src/connector/adyen/transformers.rs",
"crates/router/src/connector/airwallex.rs",
"crates/router/src/connector/airwallex/transformers.rs",
"crates/router/src/connector/authorizedotnet.rs",
"crates/r... | ||
juspay/hyperswitch | juspay__hyperswitch-3675 | Bug: [BUG]: [Noon] Payment not reaching terminal state
### Bug Description
If there is a timeout or some other unfortunate instance in the application the payment is put in `pending` state, when we sync the payment with Noon, in some cases it returns 4xx and we do not update the status. But for some status like `order_does_not_exist` in their system we should fail it immediately.
### Expected Behavior
for some status like `order_does_not_exist` in their system we should fail it immediately.
### Actual Behavior
in some cases it returns 4xx and we do not update the status.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs
index 6e1959b46d0..a055c2eac59 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -132,14 +132,22 @@ impl ConnectorCommon for Noon {
res.response.parse_struct("NoonErrorResponse");
match response {
- Ok(noon_error_response) => Ok(ErrorResponse {
- status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
- message: noon_error_response.class_description,
- reason: Some(noon_error_response.message),
- attempt_status: None,
- connector_transaction_id: None,
- }),
+ Ok(noon_error_response) => {
+ // Adding in case of timeouts, if psync gives 4xx with this code, fail the payment
+ let attempt_status = if noon_error_response.result_code == 19001 {
+ Some(enums::AttemptStatus::Failure)
+ } else {
+ None
+ };
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: noon_error_response.result_code.to_string(),
+ message: noon_error_response.class_description,
+ reason: Some(noon_error_response.message),
+ attempt_status,
+ connector_transaction_id: None,
+ })
+ }
Err(error_message) => {
logger::error!(deserialization_error =? error_message);
utils::handle_json_response_deserialization_failure(res, "noon".to_owned())
| 2024-02-16T08:44:56Z |
## Description
<!-- Describe your changes in detail -->
Currently in Psync if 4xx or 5xx comes the payment_status is not changed for all the error_codes, for specific error_codes like order does not exist should be failed immediately.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
#3675
# | 682f4ede8e957021bf0c01849406d1acd6bc17bb |
- Create a sync with noon for payment that was not registered with noon, it should fail rather than stuck in pending state.
<img width="1124" alt="Screenshot 2024-02-16 at 2 02 08 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/133a10ae-73bd-4fac-a73e-d00775ecad97">
<img width="1115" alt="Screenshot 2024-02-16 at 2 02 01 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/bb3aff72-759b-43f4-b63c-b5b2bf298203">
| [
"crates/router/src/connector/noon.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3302 | Bug: [REFACTOR] Incorporate `hyperswitch_interface` into router
Refactor router to incorporate the newly added crate `hyperswitch_interface` for secrets decryption | diff --git a/config/config.example.toml b/config/config.example.toml
index 1a132933433..abe3f6b4e08 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -115,12 +115,9 @@ route_to_trace = ["*/confirm"]
# This section provides some secret values.
[secrets]
master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long.
-admin_api_key = "test_admin" # admin API key for admin authentication. Only applicable when KMS is disabled.
-kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled.
-jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled.
-kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled.
-recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. Only applicable when KMS is disabled.
-kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the recon_admin_api_key. Only applicable when KMS is enabled
+admin_api_key = "test_admin" # admin API key for admin authentication.
+jwt_secret = "secret" # JWT secret used for user authentication.
+recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication.
# Locker settings contain details for accessing a card locker, a
# PCI Compliant storage entity which stores payment method information
@@ -156,8 +153,6 @@ outgoing_enabled = true
validity = 1
[api_keys]
-# Base64-encoded (KMS encrypted) ciphertext of the API key hashing key
-kms_encrypted_hash_key = ""
# Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating hashes of API keys
hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
@@ -322,11 +317,6 @@ paypal = { currency = "USD,INR", country = "US" }
# ^------------------------------- any valid payment method type (can be multiple) (for cards this should be card_network)
# If either currency or country isn't provided then, all possible values are accepted
-# AWS KMS configuration. Only applicable when the `aws_kms` feature flag is enabled.
-[kms]
-key_id = "" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "" # The AWS region used by the KMS SDK for decrypting data.
-
[cors]
max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
origins = "http://localhost:8080" # List of origins that are allowed to make requests.
@@ -568,3 +558,17 @@ file_storage_backend = "aws_s3" # File storage backend to be used
[file_storage.aws_s3]
region = "us-east-1" # The AWS region used by the AWS S3 for file storage
bucket_name = "bucket1" # The AWS S3 bucket name for file storage
+
+[secrets_management]
+secrets_manager = "aws_kms" # Secrets manager client to be used
+
+[secrets_management.aws_kms]
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+
+[encryption_management]
+encryption_manager = "aws_kms" # Encryption manager client to be used
+
+[encryption_management.aws_kms]
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 39bf7060b66..c8c118d9827 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -21,8 +21,7 @@ connection_timeout = 10 # Timeout for database connection in seconds
queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client
[api_keys]
-kms_encrypted_hash_key = "base64_encoded_ciphertext" # Base64-encoded (KMS encrypted) ciphertext of the API key hashing key
-hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key. Only applicable when KMS is disabled.
+hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key.
[applepay_decrypt_keys]
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate
@@ -99,11 +98,6 @@ vault_encryption_key = "" # public key in pem format, corresponding privat
rust_locker_encryption_key = "" # public key in pem format, corresponding private key in rust locker
vault_private_key = "" # private key in pem format, corresponding public key in rust locker
-# KMS configuration. Only applicable when the `kms` feature flag is enabled.
-[kms]
-key_id = "" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "" # The AWS region used by the KMS SDK for decrypting data.
-
# Locker settings contain details for accessing a card locker, a
# PCI Compliant storage entity which stores payment method information
# like card details
@@ -201,12 +195,9 @@ region = "report_download_config_region" # Region of the buc
# This section provides some secret values.
[secrets]
master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long.
-admin_api_key = "test_admin" # admin API key for admin authentication. Only applicable when KMS is disabled.
-kms_encrypted_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the admin_api_key. Only applicable when KMS is enabled.
-jwt_secret = "secret" # JWT secret used for user authentication. Only applicable when KMS is disabled.
-kms_encrypted_jwt_secret = "" # Base64-encoded (KMS encrypted) ciphertext of the jwt_secret. Only applicable when KMS is enabled.
-recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication. Only applicable when KMS is disabled.
-kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) ciphertext of the recon_admin_api_key. Only applicable when KMS is enabled
+admin_api_key = "test_admin" # admin API key for admin authentication.
+jwt_secret = "secret" # JWT secret used for user authentication.
+recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authentication.
# Server configuration
[server]
@@ -219,3 +210,17 @@ host = "127.0.0.1"
shutdown_timeout = 30
# HTTP Request body limit. Defaults to 32kB
request_body_limit = 32_768
+
+[secrets_management]
+secrets_manager = "aws_kms" # Secrets manager client to be used
+
+[secrets_management.aws_kms]
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+
+[encryption_management]
+encryption_manager = "aws_kms" # Encryption manager client to be used
+
+[encryption_management.aws_kms]
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index 725c6a123f1..2eea5b513cc 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -8,9 +8,7 @@ readme = "README.md"
license.workspace = true
[features]
-release = ["aws_kms", "vergen"]
-aws_kms = ["external_services/aws_kms"]
-hashicorp-vault = ["external_services/hashicorp-vault"]
+release = ["vergen", "external_services/aws_kms"]
vergen = ["router_env/vergen"]
[dependencies]
diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs
index 377fdcd1569..64e66619d74 100644
--- a/crates/drainer/src/main.rs
+++ b/crates/drainer/src/main.rs
@@ -17,8 +17,7 @@ async fn main() -> DrainerResult<()> {
let state = settings::AppState::new(conf.clone()).await;
- let store = services::Store::new(&state.conf, false).await;
- let store = std::sync::Arc::new(store);
+ let store = std::sync::Arc::new(services::Store::new(&state.conf, false).await);
#[cfg(feature = "vergen")]
println!("Starting drainer (Version: {})", router_env::git_tag!());
diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rs
index c0447725a79..4ffb584a152 100644
--- a/crates/drainer/src/secrets_transformers.rs
+++ b/crates/drainer/src/secrets_transformers.rs
@@ -11,7 +11,7 @@ use crate::settings::{Database, Settings};
impl SecretsHandler for Database {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
- secret_management_client: Box<dyn SecretManagementInterface>,
+ secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secured_db_config = value.get_inner();
let raw_db_password = secret_management_client
@@ -28,10 +28,9 @@ impl SecretsHandler for Database {
/// # Panics
///
/// Will panic even if fetching raw secret fails for at least one config value
-#[allow(clippy::unwrap_used)]
pub async fn fetch_raw_secrets(
conf: Settings<SecuredSecret>,
- secret_management_client: Box<dyn SecretManagementInterface>,
+ secret_management_client: &dyn SecretManagementInterface,
) -> Settings<RawSecret> {
#[allow(clippy::expect_used)]
let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client)
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index ec24c472af2..e68ede9e8b2 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -47,7 +47,7 @@ impl AppState {
.expect("Failed to create secret management client");
let raw_conf =
- secrets_transformers::fetch_raw_secrets(conf, secret_management_client).await;
+ secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await;
#[allow(clippy::expect_used)]
let encryption_client = raw_conf
diff --git a/crates/external_services/src/aws_kms.rs b/crates/external_services/src/aws_kms.rs
index 3e5353fd9e3..a01062f26e8 100644
--- a/crates/external_services/src/aws_kms.rs
+++ b/crates/external_services/src/aws_kms.rs
@@ -2,6 +2,4 @@
pub mod core;
-pub mod decrypt;
-
pub mod implementers;
diff --git a/crates/external_services/src/aws_kms/core.rs b/crates/external_services/src/aws_kms/core.rs
index c01bcbfb094..d211f1def9b 100644
--- a/crates/external_services/src/aws_kms/core.rs
+++ b/crates/external_services/src/aws_kms/core.rs
@@ -7,23 +7,9 @@ use aws_sdk_kms::{config::Region, primitives::Blob, Client};
use base64::Engine;
use common_utils::errors::CustomResult;
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
use router_env::logger;
-#[cfg(feature = "hashicorp-vault")]
-use crate::hashicorp_vault;
-use crate::{aws_kms::decrypt::AwsKmsDecrypt, consts, metrics};
-
-pub(crate) static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> =
- tokio::sync::OnceCell::const_new();
-
-/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized.
-#[inline]
-pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient {
- AWS_KMS_CLIENT
- .get_or_init(|| AwsKmsClient::new(config))
- .await
-}
+use crate::{consts, metrics};
/// Configuration parameters required for constructing a [`AwsKmsClient`].
#[derive(Clone, Debug, Default, serde::Deserialize)]
@@ -188,69 +174,6 @@ impl AwsKmsConfig {
}
}
-/// A wrapper around a AWS KMS value that can be decrypted.
-#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)]
-#[serde(transparent)]
-pub struct AwsKmsValue(Secret<String>);
-
-impl common_utils::ext_traits::ConfigExt for AwsKmsValue {
- fn is_empty_after_trim(&self) -> bool {
- self.0.peek().is_empty_after_trim()
- }
-}
-
-impl From<String> for AwsKmsValue {
- fn from(value: String) -> Self {
- Self(Secret::new(value))
- }
-}
-
-impl From<Secret<String>> for AwsKmsValue {
- fn from(value: Secret<String>) -> Self {
- Self(value)
- }
-}
-
-#[cfg(feature = "hashicorp-vault")]
-#[async_trait::async_trait]
-impl hashicorp_vault::decrypt::VaultFetch for AwsKmsValue {
- async fn fetch_inner<En>(
- self,
- client: &hashicorp_vault::core::HashiCorpVault,
- ) -> error_stack::Result<Self, hashicorp_vault::core::HashiCorpError>
- where
- for<'a> En: hashicorp_vault::core::Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<
- String,
- hashicorp_vault::core::HashiCorpError,
- >,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- self.0.fetch_inner::<En>(client).await.map(AwsKmsValue)
- }
-}
-
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for &AwsKmsValue {
- type Output = String;
- async fn decrypt_inner(
- self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- aws_kms_client
- .decrypt(self.0.peek())
- .await
- .attach_printable("Failed to decrypt AWS KMS value")
- }
-}
-
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs
deleted file mode 100644
index 47edb8f958f..00000000000
--- a/crates/external_services/src/aws_kms/decrypt.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-//! Decrypting data using the AWS KMS SDK.
-use common_utils::errors::CustomResult;
-
-use crate::aws_kms::core::{AwsKmsClient, AwsKmsError, AWS_KMS_CLIENT};
-
-#[async_trait::async_trait]
-/// This trait performs in place decryption of the structure on which this is implemented
-pub trait AwsKmsDecrypt {
- /// The output type of the decryption
- type Output;
- /// Decrypts the structure given a AWS KMS client
- async fn decrypt_inner(
- self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError>
- where
- Self: Sized;
-
- /// Tries to use the Singleton client to decrypt the structure
- async fn try_decrypt_inner(self) -> CustomResult<Self::Output, AwsKmsError>
- where
- Self: Sized,
- {
- let client = AWS_KMS_CLIENT
- .get()
- .ok_or(AwsKmsError::AwsKmsClientNotInitialized)?;
- self.decrypt_inner(client).await
- }
-}
diff --git a/crates/external_services/src/hashicorp_vault.rs b/crates/external_services/src/hashicorp_vault.rs
index 5a3ba539689..6bf234ff420 100644
--- a/crates/external_services/src/hashicorp_vault.rs
+++ b/crates/external_services/src/hashicorp_vault.rs
@@ -2,6 +2,4 @@
pub mod core;
-pub mod decrypt;
-
pub mod implementers;
diff --git a/crates/external_services/src/hashicorp_vault/decrypt.rs b/crates/external_services/src/hashicorp_vault/decrypt.rs
deleted file mode 100644
index 650b219841f..00000000000
--- a/crates/external_services/src/hashicorp_vault/decrypt.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-//! Utilities for supporting decryption of data
-
-use std::{future::Future, pin::Pin};
-
-use masking::ExposeInterface;
-
-use crate::hashicorp_vault::core::{Engine, HashiCorpError, HashiCorpVault};
-
-/// A trait for types that can be asynchronously fetched and decrypted from HashiCorp Vault.
-#[async_trait::async_trait]
-pub trait VaultFetch: Sized {
- /// Asynchronously decrypts the inner content of the type.
- ///
- /// # Returns
- ///
- /// An `Result<Self, super::HashiCorpError>` representing the decrypted instance if successful,
- /// or an `super::HashiCorpError` with details about the encountered error.
- ///
- async fn fetch_inner<En>(
- self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = Pin<
- Box<
- dyn Future<Output = error_stack::Result<String, HashiCorpError>>
- + Send
- + 'a,
- >,
- >,
- > + 'a;
-}
-
-#[async_trait::async_trait]
-impl VaultFetch for masking::Secret<String> {
- async fn fetch_inner<En>(
- self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = Pin<
- Box<
- dyn Future<Output = error_stack::Result<String, HashiCorpError>>
- + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- client.fetch::<En, Self>(self.expose()).await
- }
-}
diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
index a0915b8de69..d823eba8700 100644
--- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
+++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
@@ -16,6 +16,6 @@ where
/// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret`
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
- kms_client: Box<dyn SecretManagementInterface>,
+ kms_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>;
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index c511947cd1e..5dbeb1bb199 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -10,13 +10,10 @@ license.workspace = true
[features]
default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"]
-aws_s3 = ["external_services/aws_s3"]
-aws_kms = ["external_services/aws_kms"]
-hashicorp-vault = ["external_services/hashicorp-vault"]
email = ["external_services/email", "scheduler/email", "olap"]
frm = []
stripe = ["dep:serde_qs"]
-release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"]
+release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3"]
olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
oltp = ["storage_impl/oltp"]
kv_store = ["scheduler/kv_store"]
diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs
index d069c89b82e..f7514a312a4 100644
--- a/crates/router/src/configs.rs
+++ b/crates/router/src/configs.rs
@@ -1,7 +1,8 @@
-#[cfg(feature = "aws_kms")]
-pub mod aws_kms;
+use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
+
mod defaults;
-#[cfg(feature = "hashicorp-vault")]
-pub mod hc_vault;
+pub mod secrets_transformers;
pub mod settings;
mod validations;
+
+pub type Settings = settings::Settings<RawSecret>;
diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs
deleted file mode 100644
index 9bb5fcc6f20..00000000000
--- a/crates/router/src/configs/aws_kms.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-use common_utils::errors::CustomResult;
-use external_services::aws_kms::{
- core::{AwsKmsClient, AwsKmsError},
- decrypt::AwsKmsDecrypt,
-};
-use masking::ExposeInterface;
-
-use crate::configs::settings;
-
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for settings::Jwekey {
- type Output = Self;
-
- async fn decrypt_inner(
- mut self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- (
- self.vault_encryption_key,
- self.rust_locker_encryption_key,
- self.vault_private_key,
- self.tunnel_private_key,
- ) = tokio::try_join!(
- aws_kms_client.decrypt(self.vault_encryption_key),
- aws_kms_client.decrypt(self.rust_locker_encryption_key),
- aws_kms_client.decrypt(self.vault_private_key),
- aws_kms_client.decrypt(self.tunnel_private_key),
- )?;
- Ok(self)
- }
-}
-
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for settings::ActiveKmsSecrets {
- type Output = Self;
- async fn decrypt_inner(
- mut self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- self.jwekey = self
- .jwekey
- .expose()
- .decrypt_inner(aws_kms_client)
- .await?
- .into();
- Ok(self)
- }
-}
-
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for settings::Database {
- type Output = storage_impl::config::Database;
-
- async fn decrypt_inner(
- mut self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- Ok(storage_impl::config::Database {
- host: self.host,
- port: self.port,
- dbname: self.dbname,
- username: self.username,
- password: self.password.decrypt_inner(aws_kms_client).await?.into(),
- pool_size: self.pool_size,
- connection_timeout: self.connection_timeout,
- queue_strategy: self.queue_strategy,
- min_idle: self.min_idle,
- max_lifetime: self.max_lifetime,
- })
- }
-}
-
-#[cfg(feature = "olap")]
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for settings::PayPalOnboarding {
- type Output = Self;
-
- async fn decrypt_inner(
- mut self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- self.client_id = aws_kms_client
- .decrypt(self.client_id.expose())
- .await?
- .into();
- self.client_secret = aws_kms_client
- .decrypt(self.client_secret.expose())
- .await?
- .into();
- self.partner_id = aws_kms_client
- .decrypt(self.partner_id.expose())
- .await?
- .into();
- Ok(self)
- }
-}
-
-#[cfg(feature = "olap")]
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for settings::ConnectorOnboarding {
- type Output = Self;
-
- async fn decrypt_inner(
- mut self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- self.paypal = self.paypal.decrypt_inner(aws_kms_client).await?;
- Ok(self)
- }
-}
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index e56acde78c2..5c2d62b40b8 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -1,10 +1,8 @@
use std::collections::{HashMap, HashSet};
use api_models::{enums, payment_methods::RequiredFieldInfo};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::core::AwsKmsValue;
-use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal};
+use super::settings::{ConnectorFields, PaymentMethodType, RequiredFieldFinal};
impl Default for super::settings::Server {
fn default() -> Self {
@@ -37,7 +35,7 @@ impl Default for super::settings::Database {
fn default() -> Self {
Self {
username: String::new(),
- password: Password::default(),
+ password: String::new().into(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
@@ -6518,13 +6516,9 @@ impl Default for super::settings::RequiredFields {
impl Default for super::settings::ApiKeys {
fn default() -> Self {
Self {
- #[cfg(feature = "aws_kms")]
- kms_encrypted_hash_key: AwsKmsValue::default(),
-
// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
// hashes of API keys
- #[cfg(not(feature = "aws_kms"))]
- hash_key: String::new(),
+ hash_key: String::new().into(),
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
diff --git a/crates/router/src/configs/hc_vault.rs b/crates/router/src/configs/hc_vault.rs
deleted file mode 100644
index fa6596f7494..00000000000
--- a/crates/router/src/configs/hc_vault.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-use external_services::hashicorp_vault::{
- core::{Engine, HashiCorpError, HashiCorpVault},
- decrypt::VaultFetch,
-};
-use masking::ExposeInterface;
-
-use crate::configs::settings;
-
-#[async_trait::async_trait]
-impl VaultFetch for settings::Jwekey {
- async fn fetch_inner<En>(
- mut self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<String, HashiCorpError>,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- (
- self.vault_encryption_key,
- self.rust_locker_encryption_key,
- self.vault_private_key,
- self.tunnel_private_key,
- ) = (
- masking::Secret::new(self.vault_encryption_key)
- .fetch_inner::<En>(client)
- .await?
- .expose(),
- masking::Secret::new(self.rust_locker_encryption_key)
- .fetch_inner::<En>(client)
- .await?
- .expose(),
- masking::Secret::new(self.vault_private_key)
- .fetch_inner::<En>(client)
- .await?
- .expose(),
- masking::Secret::new(self.tunnel_private_key)
- .fetch_inner::<En>(client)
- .await?
- .expose(),
- );
- Ok(self)
- }
-}
-
-#[async_trait::async_trait]
-impl VaultFetch for settings::Database {
- async fn fetch_inner<En>(
- mut self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<String, HashiCorpError>,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- Ok(Self {
- host: self.host,
- port: self.port,
- dbname: self.dbname,
- username: self.username,
- password: self.password.fetch_inner::<En>(client).await?,
- pool_size: self.pool_size,
- connection_timeout: self.connection_timeout,
- queue_strategy: self.queue_strategy,
- min_idle: self.min_idle,
- max_lifetime: self.max_lifetime,
- })
- }
-}
-
-#[cfg(feature = "olap")]
-#[async_trait::async_trait]
-impl VaultFetch for settings::PayPalOnboarding {
- async fn fetch_inner<En>(
- mut self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<String, HashiCorpError>,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- self.client_id = self.client_id.fetch_inner::<En>(client).await?;
- self.client_secret = self.client_secret.fetch_inner::<En>(client).await?;
- self.partner_id = self.partner_id.fetch_inner::<En>(client).await?;
- Ok(self)
- }
-}
-
-#[cfg(feature = "olap")]
-#[async_trait::async_trait]
-impl VaultFetch for settings::ConnectorOnboarding {
- async fn fetch_inner<En>(
- mut self,
- client: &HashiCorpVault,
- ) -> error_stack::Result<Self, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<String, HashiCorpError>,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- self.paypal = self.paypal.fetch_inner::<En>(client).await?;
- Ok(self)
- }
-}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
new file mode 100644
index 00000000000..1306cdd80bb
--- /dev/null
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -0,0 +1,357 @@
+use common_utils::errors::CustomResult;
+use hyperswitch_interfaces::secrets_interface::{
+ secret_handler::SecretsHandler,
+ secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
+ SecretManagementInterface, SecretsManagementError,
+};
+
+use crate::settings::{self, Settings};
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::Database {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let db = value.get_inner();
+ let db_password = secret_management_client
+ .get_secret(db.password.clone())
+ .await?;
+
+ Ok(value.transition_state(|db| Self {
+ password: db_password,
+ ..db
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::Jwekey {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let jwekey = value.get_inner();
+ let (
+ vault_encryption_key,
+ rust_locker_encryption_key,
+ vault_private_key,
+ tunnel_private_key,
+ ) = tokio::try_join!(
+ secret_management_client.get_secret(jwekey.vault_encryption_key.clone()),
+ secret_management_client.get_secret(jwekey.rust_locker_encryption_key.clone()),
+ secret_management_client.get_secret(jwekey.vault_private_key.clone()),
+ secret_management_client.get_secret(jwekey.tunnel_private_key.clone())
+ )?;
+ Ok(value.transition_state(|_| Self {
+ vault_encryption_key,
+ rust_locker_encryption_key,
+ vault_private_key,
+ tunnel_private_key,
+ }))
+ }
+}
+
+#[cfg(feature = "olap")]
+#[async_trait::async_trait]
+impl SecretsHandler for settings::ConnectorOnboarding {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let onboarding_config = &value.get_inner().paypal;
+
+ let (client_id, client_secret, partner_id) = tokio::try_join!(
+ secret_management_client.get_secret(onboarding_config.client_id.clone()),
+ secret_management_client.get_secret(onboarding_config.client_secret.clone()),
+ secret_management_client.get_secret(onboarding_config.partner_id.clone())
+ )?;
+
+ Ok(value.transition_state(|onboarding_config| Self {
+ paypal: settings::PayPalOnboarding {
+ client_id,
+ client_secret,
+ partner_id,
+ ..onboarding_config.paypal
+ },
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::ForexApi {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let forex_api = value.get_inner();
+
+ let (api_key, fallback_api_key) = tokio::try_join!(
+ secret_management_client.get_secret(forex_api.api_key.clone()),
+ secret_management_client.get_secret(forex_api.fallback_api_key.clone()),
+ )?;
+
+ Ok(value.transition_state(|forex_api| Self {
+ api_key,
+ fallback_api_key,
+ ..forex_api
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::ApiKeys {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let api_keys = value.get_inner();
+
+ let hash_key = secret_management_client
+ .get_secret(api_keys.hash_key.clone())
+ .await?;
+
+ #[cfg(feature = "email")]
+ let expiry_reminder_days = api_keys.expiry_reminder_days.clone();
+
+ Ok(value.transition_state(|_| Self {
+ hash_key,
+ #[cfg(feature = "email")]
+ expiry_reminder_days,
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::ApplePayDecryptConifg {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let applepay_decrypt_keys = value.get_inner();
+
+ let (
+ apple_pay_ppc,
+ apple_pay_ppc_key,
+ apple_pay_merchant_cert,
+ apple_pay_merchant_cert_key,
+ ) = tokio::try_join!(
+ secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc.clone()),
+ secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc_key.clone()),
+ secret_management_client
+ .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert.clone()),
+ secret_management_client
+ .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert_key.clone()),
+ )?;
+
+ Ok(value.transition_state(|_| Self {
+ apple_pay_ppc,
+ apple_pay_ppc_key,
+ apple_pay_merchant_cert,
+ apple_pay_merchant_cert_key,
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::ApplepayMerchantConfigs {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let applepay_merchant_configs = value.get_inner();
+
+ let (merchant_cert, merchant_cert_key, common_merchant_identifier) = tokio::try_join!(
+ secret_management_client.get_secret(applepay_merchant_configs.merchant_cert.clone()),
+ secret_management_client
+ .get_secret(applepay_merchant_configs.merchant_cert_key.clone()),
+ secret_management_client
+ .get_secret(applepay_merchant_configs.common_merchant_identifier.clone()),
+ )?;
+
+ Ok(value.transition_state(|applepay_merchant_configs| Self {
+ merchant_cert,
+ merchant_cert_key,
+ common_merchant_identifier,
+ ..applepay_merchant_configs
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::PaymentMethodAuth {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let payment_method_auth = value.get_inner();
+
+ let pm_auth_key = secret_management_client
+ .get_secret(payment_method_auth.pm_auth_key.clone())
+ .await?;
+
+ Ok(value.transition_state(|payment_method_auth| Self {
+ pm_auth_key,
+ ..payment_method_auth
+ }))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretsHandler for settings::Secrets {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let secrets = value.get_inner();
+ let (jwt_secret, admin_api_key, recon_admin_api_key, master_enc_key) = tokio::try_join!(
+ secret_management_client.get_secret(secrets.jwt_secret.clone()),
+ secret_management_client.get_secret(secrets.admin_api_key.clone()),
+ secret_management_client.get_secret(secrets.recon_admin_api_key.clone()),
+ secret_management_client.get_secret(secrets.master_enc_key.clone())
+ )?;
+
+ Ok(value.transition_state(|_| Self {
+ jwt_secret,
+ admin_api_key,
+ recon_admin_api_key,
+ master_enc_key,
+ }))
+ }
+}
+
+/// # Panics
+///
+/// Will panic even if kms decryption fails for at least one field
+pub(crate) async fn fetch_raw_secrets(
+ conf: Settings<SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+) -> Settings<RawSecret> {
+ #[allow(clippy::expect_used)]
+ let master_database =
+ settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client)
+ .await
+ .expect("Failed to decrypt master database configuration");
+
+ #[cfg(feature = "olap")]
+ #[allow(clippy::expect_used)]
+ let replica_database =
+ settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client)
+ .await
+ .expect("Failed to decrypt replica database configuration");
+
+ #[allow(clippy::expect_used)]
+ let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client)
+ .await
+ .expect("Failed to decrypt secrets");
+
+ #[allow(clippy::expect_used)]
+ let forex_api =
+ settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client)
+ .await
+ .expect("Failed to decrypt forex api configs");
+
+ #[allow(clippy::expect_used)]
+ let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client)
+ .await
+ .expect("Failed to decrypt jwekey configs");
+
+ #[allow(clippy::expect_used)]
+ let api_keys =
+ settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client)
+ .await
+ .expect("Failed to decrypt api_keys configs");
+
+ #[cfg(feature = "olap")]
+ #[allow(clippy::expect_used)]
+ let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret(
+ conf.connector_onboarding,
+ secret_management_client,
+ )
+ .await
+ .expect("Failed to decrypt connector_onboarding configs");
+
+ #[allow(clippy::expect_used)]
+ let applepay_decrypt_keys = settings::ApplePayDecryptConifg::convert_to_raw_secret(
+ conf.applepay_decrypt_keys,
+ secret_management_client,
+ )
+ .await
+ .expect("Failed to decrypt applepay decrypt configs");
+
+ #[allow(clippy::expect_used)]
+ let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret(
+ conf.applepay_merchant_configs,
+ secret_management_client,
+ )
+ .await
+ .expect("Failed to decrypt applepay merchant configs");
+
+ #[allow(clippy::expect_used)]
+ let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret(
+ conf.payment_method_auth,
+ secret_management_client,
+ )
+ .await
+ .expect("Failed to decrypt payment method auth configs");
+
+ Settings {
+ server: conf.server,
+ master_database,
+ redis: conf.redis,
+ log: conf.log,
+ #[cfg(feature = "kv_store")]
+ drainer: conf.drainer,
+ encryption_management: conf.encryption_management,
+ secrets_management: conf.secrets_management,
+ proxy: conf.proxy,
+ env: conf.env,
+ #[cfg(feature = "olap")]
+ replica_database,
+ secrets,
+ locker: conf.locker,
+ connectors: conf.connectors,
+ forex_api,
+ refund: conf.refund,
+ eph_key: conf.eph_key,
+ scheduler: conf.scheduler,
+ jwekey,
+ webhooks: conf.webhooks,
+ pm_filters: conf.pm_filters,
+ bank_config: conf.bank_config,
+ api_keys,
+ file_storage: conf.file_storage,
+ tokenization: conf.tokenization,
+ connector_customer: conf.connector_customer,
+ #[cfg(feature = "dummy_connector")]
+ dummy_connector: conf.dummy_connector,
+ #[cfg(feature = "email")]
+ email: conf.email,
+ mandates: conf.mandates,
+ required_fields: conf.required_fields,
+ delayed_session_response: conf.delayed_session_response,
+ webhook_source_verification_call: conf.webhook_source_verification_call,
+ payment_method_auth,
+ connector_request_reference_id_config: conf.connector_request_reference_id_config,
+ #[cfg(feature = "payouts")]
+ payouts: conf.payouts,
+ applepay_decrypt_keys,
+ multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors,
+ applepay_merchant_configs,
+ lock_settings: conf.lock_settings,
+ temp_locker_enable_config: conf.temp_locker_enable_config,
+ payment_link: conf.payment_link,
+ #[cfg(feature = "olap")]
+ analytics: conf.analytics,
+ #[cfg(feature = "kv_store")]
+ kv_config: conf.kv_config,
+ #[cfg(feature = "frm")]
+ frm: conf.frm,
+ #[cfg(feature = "olap")]
+ report_download_config: conf.report_download_config,
+ events: conf.events,
+ #[cfg(feature = "olap")]
+ connector_onboarding,
+ cors: conf.cors,
+ }
+}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 8ed2daef5f3..8fb55491fe4 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -8,12 +8,8 @@ use analytics::ReportConfig;
use api_models::{enums, payment_methods::RequiredFieldInfo};
use common_utils::ext_traits::ConfigExt;
use config::{Environment, File};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
#[cfg(feature = "email")]
use external_services::email::EmailSettings;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault;
use external_services::{
file_storage::FileStorageConfig,
managers::{
@@ -21,6 +17,10 @@ use external_services::{
secrets_management::SecretsManagementConfig,
},
};
+use hyperswitch_interfaces::secrets_interface::secret_state::{
+ SecretState, SecretStateContainer, SecuredSecret,
+};
+use masking::Secret;
use redis_interface::RedisSettings;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use rust_decimal::Decimal;
@@ -35,10 +35,6 @@ use crate::{
env::{self, logger, Env},
events::EventsConfig,
};
-#[cfg(feature = "aws_kms")]
-pub type Password = aws_kms::core::AwsKmsValue;
-#[cfg(not(feature = "aws_kms"))]
-pub type Password = masking::Secret<String>;
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
@@ -59,48 +55,34 @@ pub enum Subcommand {
GenerateOpenapiSpec,
}
-#[cfg(feature = "aws_kms")]
-/// Store the decrypted aws kms secret values for active use in the application
-/// Currently using `StrongSecret` won't have any effect as this struct have smart pointers to heap
-/// allocations.
-/// note: we can consider adding such behaviour in the future with custom implementation
-#[derive(Clone)]
-pub struct ActiveKmsSecrets {
- pub jwekey: masking::Secret<Jwekey>,
-}
-
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
-pub struct Settings {
+pub struct Settings<S: SecretState> {
pub server: Server,
pub proxy: Proxy,
pub env: Env,
- pub master_database: Database,
+ pub master_database: SecretStateContainer<Database, S>,
#[cfg(feature = "olap")]
- pub replica_database: Database,
+ pub replica_database: SecretStateContainer<Database, S>,
pub redis: RedisSettings,
pub log: Log,
- pub secrets: Secrets,
+ pub secrets: SecretStateContainer<Secrets, S>,
pub locker: Locker,
pub connectors: Connectors,
- pub forex_api: ForexApi,
+ pub forex_api: SecretStateContainer<ForexApi, S>,
pub refund: Refund,
pub eph_key: EphemeralConfig,
pub scheduler: Option<SchedulerSettings>,
#[cfg(feature = "kv_store")]
pub drainer: DrainerSettings,
- pub jwekey: Jwekey,
+ pub jwekey: SecretStateContainer<Jwekey, S>,
pub webhooks: WebhooksSettings,
pub pm_filters: ConnectorFilters,
pub bank_config: BankRedirectConfig,
- pub api_keys: ApiKeys,
- #[cfg(feature = "aws_kms")]
- pub kms: aws_kms::core::AwsKmsConfig,
+ pub api_keys: SecretStateContainer<ApiKeys, S>,
pub file_storage: FileStorageConfig,
pub encryption_management: EncryptionManagementConfig,
pub secrets_management: SecretsManagementConfig,
- #[cfg(feature = "hashicorp-vault")]
- pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
pub tokenization: TokenizationConfig,
pub connector_customer: ConnectorCustomer,
#[cfg(feature = "dummy_connector")]
@@ -112,13 +94,13 @@ pub struct Settings {
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
- pub payment_method_auth: PaymentMethodAuth,
+ pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>,
pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig,
#[cfg(feature = "payouts")]
pub payouts: Payouts,
- pub applepay_decrypt_keys: ApplePayDecryptConifg,
+ pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConifg, S>,
pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,
- pub applepay_merchant_configs: ApplepayMerchantConfigs,
+ pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>,
pub lock_settings: LockSettings,
pub temp_locker_enable_config: TempLockerEnableConfig,
pub payment_link: PaymentLink,
@@ -132,7 +114,7 @@ pub struct Settings {
pub report_download_config: ReportConfig,
pub events: EventsConfig,
#[cfg(feature = "olap")]
- pub connector_onboarding: ConnectorOnboarding,
+ pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
}
#[cfg(feature = "frm")]
@@ -155,8 +137,8 @@ pub struct PaymentLink {
#[serde(default)]
pub struct ForexApi {
pub local_fetch_retry_count: u64,
- pub api_key: masking::Secret<String>,
- pub fallback_api_key: masking::Secret<String>,
+ pub api_key: Secret<String>,
+ pub fallback_api_key: Secret<String>,
/// in ms
pub call_delay: i64,
/// in ms
@@ -170,7 +152,7 @@ pub struct ForexApi {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PaymentMethodAuth {
pub redis_expiry: i64,
- pub pm_auth_key: String,
+ pub pm_auth_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -191,9 +173,9 @@ pub struct Conversion {
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct ApplepayMerchantConfigs {
- pub merchant_cert: String,
- pub merchant_cert_key: String,
- pub common_merchant_identifier: String,
+ pub merchant_cert: Secret<String>,
+ pub merchant_cert_key: Secret<String>,
+ pub common_merchant_identifier: Secret<String>,
pub applepay_endpoint: String,
}
@@ -380,19 +362,10 @@ pub struct RequiredFieldFinal {
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct Secrets {
- #[cfg(not(feature = "aws_kms"))]
- pub jwt_secret: String,
- #[cfg(not(feature = "aws_kms"))]
- pub admin_api_key: String,
- #[cfg(not(feature = "aws_kms"))]
- pub recon_admin_api_key: String,
- pub master_enc_key: Password,
- #[cfg(feature = "aws_kms")]
- pub kms_encrypted_jwt_secret: aws_kms::core::AwsKmsValue,
- #[cfg(feature = "aws_kms")]
- pub kms_encrypted_admin_api_key: aws_kms::core::AwsKmsValue,
- #[cfg(feature = "aws_kms")]
- pub kms_encrypted_recon_admin_api_key: aws_kms::core::AwsKmsValue,
+ pub jwt_secret: Secret<String>,
+ pub admin_api_key: Secret<String>,
+ pub recon_admin_api_key: Secret<String>,
+ pub master_enc_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
@@ -422,10 +395,10 @@ pub struct EphemeralConfig {
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Jwekey {
- pub vault_encryption_key: String,
- pub rust_locker_encryption_key: String,
- pub vault_private_key: String,
- pub tunnel_private_key: String,
+ pub vault_encryption_key: Secret<String>,
+ pub rust_locker_encryption_key: Secret<String>,
+ pub vault_private_key: Secret<String>,
+ pub tunnel_private_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone)]
@@ -451,7 +424,7 @@ pub struct Server {
#[serde(default)]
pub struct Database {
pub username: String,
- pub password: Password,
+ pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
@@ -462,7 +435,6 @@ pub struct Database {
pub max_lifetime: Option<u64>,
}
-#[cfg(not(feature = "aws_kms"))]
impl From<Database> for storage_impl::config::Database {
fn from(val: Database) -> Self {
Self {
@@ -615,15 +587,9 @@ pub struct WebhookIgnoreErrorSettings {
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct ApiKeys {
- /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API
- /// keys
- #[cfg(feature = "aws_kms")]
- pub kms_encrypted_hash_key: aws_kms::core::AwsKmsValue,
-
/// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
/// hashes of API keys
- #[cfg(not(feature = "aws_kms"))]
- pub hash_key: String,
+ pub hash_key: Secret<String>,
// Specifies the number of days before API key expiry when email reminders should be sent
#[cfg(feature = "email")]
@@ -644,10 +610,10 @@ pub struct WebhookSourceVerificationCall {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ApplePayDecryptConifg {
- pub apple_pay_ppc: String,
- pub apple_pay_ppc_key: String,
- pub apple_pay_merchant_cert: String,
- pub apple_pay_merchant_cert_key: String,
+ pub apple_pay_ppc: Secret<String>,
+ pub apple_pay_ppc_key: Secret<String>,
+ pub apple_pay_merchant_cert: Secret<String>,
+ pub apple_pay_merchant_cert_key: Secret<String>,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -655,7 +621,7 @@ pub struct ConnectorRequestReferenceIdConfig {
pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>,
}
-impl Settings {
+impl Settings<SecuredSecret> {
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
@@ -702,9 +668,9 @@ impl Settings {
pub fn validate(&self) -> ApplicationResult<()> {
self.server.validate()?;
- self.master_database.validate()?;
+ self.master_database.get_inner().validate()?;
#[cfg(feature = "olap")]
- self.replica_database.validate()?;
+ self.replica_database.get_inner().validate()?;
self.redis.validate().map_err(|error| {
println!("{error}");
ApplicationError::InvalidConfigurationValueError("Redis configuration".into())
@@ -722,7 +688,7 @@ impl Settings {
));
}
}
- self.secrets.validate()?;
+ self.secrets.get_inner().validate()?;
self.locker.validate()?;
self.connectors.validate("connectors")?;
@@ -734,11 +700,7 @@ impl Settings {
.transpose()?;
#[cfg(feature = "kv_store")]
self.drainer.validate()?;
- self.api_keys.validate()?;
- #[cfg(feature = "aws_kms")]
- self.kms
- .validate()
- .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?;
+ self.api_keys.get_inner().validate()?;
self.file_storage
.validate()
@@ -802,9 +764,9 @@ pub struct ConnectorOnboarding {
#[cfg(feature = "olap")]
#[derive(Debug, Deserialize, Clone, Default)]
pub struct PayPalOnboarding {
- pub client_id: masking::Secret<String>,
- pub client_secret: masking::Secret<String>,
- pub partner_id: masking::Secret<String>,
+ pub client_id: Secret<String>,
+ pub client_secret: Secret<String>,
+ pub partner_id: Secret<String>,
pub enabled: bool,
}
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 851b7ba7571..f3118cf840e 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -1,42 +1,23 @@
use common_utils::ext_traits::ConfigExt;
+use masking::PeekInterface;
use storage_impl::errors::ApplicationError;
impl super::settings::Secrets {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
- #[cfg(not(feature = "aws_kms"))]
- {
- when(self.jwt_secret.is_default_or_empty(), || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "JWT secret must not be empty".into(),
- ))
- })?;
+ when(self.jwt_secret.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "JWT secret must not be empty".into(),
+ ))
+ })?;
- when(self.admin_api_key.is_default_or_empty(), || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "admin API key must not be empty".into(),
- ))
- })?;
- }
+ when(self.admin_api_key.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "admin API key must not be empty".into(),
+ ))
+ })?;
- #[cfg(feature = "aws_kms")]
- {
- when(self.kms_encrypted_jwt_secret.is_default_or_empty(), || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "KMS encrypted JWT secret must not be empty".into(),
- ))
- })?;
-
- when(
- self.kms_encrypted_admin_api_key.is_default_or_empty(),
- || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "KMS encrypted admin API key must not be empty".into(),
- ))
- },
- )?;
- }
when(self.master_enc_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Master encryption key must not be empty".into(),
@@ -155,15 +136,7 @@ impl super::settings::ApiKeys {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
- #[cfg(feature = "aws_kms")]
- when(self.kms_encrypted_hash_key.is_default_or_empty(), || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "API key hashing key must not be empty when KMS feature is enabled".into(),
- ))
- })?;
-
- #[cfg(not(feature = "aws_kms"))]
- when(self.hash_key.is_empty(), || {
+ when(self.hash_key.peek().is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"API key hashing key must not be empty".into(),
))
diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs
index 1a48b6e0e2c..6c10f95ea79 100644
--- a/crates/router/src/connection.rs
+++ b/crates/router/src/connection.rs
@@ -15,7 +15,7 @@ pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
/// Panics if failed to create a redis pool
#[allow(clippy::expect_used)]
pub async fn redis_connection(
- conf: &crate::configs::settings::Settings,
+ conf: &crate::configs::Settings,
) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 58f95e1371e..50bae175f64 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -35,7 +35,7 @@ pub mod user;
#[cfg(feature = "olap")]
pub mod user_role;
pub mod utils;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index b3f8931cde5..7d2069618d5 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -2,12 +2,6 @@ use common_utils::date_time;
#[cfg(feature = "email")]
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
use error_stack::{report, IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
-#[cfg(not(feature = "aws_kms"))]
-use masking::ExposeInterface;
use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
@@ -29,49 +23,16 @@ const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY";
const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner =
diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow;
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::decrypt::AwsKmsDecrypt;
-
-static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> =
- tokio::sync::OnceCell::const_new();
-
-pub async fn get_hash_key(
- api_key_config: &settings::ApiKeys,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
-) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> {
- HASH_KEY
- .get_or_try_init(|| async {
- let hash_key = {
- #[cfg(feature = "aws_kms")]
- {
- api_key_config.kms_encrypted_hash_key.clone()
- }
- #[cfg(not(feature = "aws_kms"))]
- {
- masking::Secret::<_, masking::WithType>::new(api_key_config.hash_key.clone())
- }
- };
-
- #[cfg(feature = "hashicorp-vault")]
- let hash_key = hash_key
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- #[cfg(feature = "aws_kms")]
- let hash_key = hash_key
- .decrypt_inner(aws_kms_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to AWS KMS decrypt API key hashing key")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let hash_key = hash_key.expose();
+static HASH_KEY: once_cell::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> =
+ once_cell::sync::OnceCell::new();
+impl settings::ApiKeys {
+ pub fn get_hash_key(
+ &self,
+ ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> {
+ HASH_KEY.get_or_try_init(|| {
<[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from(
- hex::decode(hash_key)
+ hex::decode(self.hash_key.peek())
.into_report()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("API key hash key has invalid hexadecimal data")?
@@ -82,7 +43,7 @@ pub async fn get_hash_key(
.attach_printable("The API hashing key has incorrect length")
.map(StrongSecret::new)
})
- .await
+ }
}
// Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility
@@ -152,13 +113,10 @@ impl PlaintextApiKey {
#[instrument(skip_all)]
pub async fn create_api_key(
state: AppState,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
api_key: api::CreateApiKeyRequest,
merchant_id: String,
) -> RouterResponse<api::CreateApiKeyResponse> {
- let api_key_config = &state.conf.api_keys;
+ let api_key_config = state.conf.api_keys.get_inner();
let store = state.store.as_ref();
// We are not fetching merchant account as the merchant key store is needed to search for a
// merchant account.
@@ -172,14 +130,7 @@ pub async fn create_api_key(
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
- let hash_key = get_hash_key(
- api_key_config,
- #[cfg(feature = "aws_kms")]
- aws_kms_client,
- #[cfg(feature = "hashicorp-vault")]
- hc_client,
- )
- .await?;
+ let hash_key = api_key_config.get_hash_key()?;
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
let api_key = storage::ApiKeyNew {
key_id: PlaintextApiKey::new_key_id(),
@@ -210,7 +161,7 @@ pub async fn create_api_key(
#[cfg(feature = "email")]
{
if api_key.expires_at.is_some() {
- let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone();
+ let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
add_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
@@ -330,7 +281,7 @@ pub async fn update_api_key(
#[cfg(feature = "email")]
{
- let expiry_reminder_days = state.conf.api_keys.expiry_reminder_days.clone();
+ let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id);
// In order to determine how to update the existing process in the process_tracker table,
@@ -575,17 +526,7 @@ mod tests {
let settings = settings::Settings::new().expect("invalid settings");
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
- let hash_key = get_hash_key(
- &settings.api_keys,
- #[cfg(feature = "aws_kms")]
- external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await,
- #[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::core::get_hashicorp_client(&settings.hc_vault)
- .await
- .unwrap(),
- )
- .await
- .unwrap();
+ let hash_key = settings.api_keys.get_inner().get_hash_key().unwrap();
let hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek());
assert_ne!(
diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs
index f4122a6a651..6d6834f0b6c 100644
--- a/crates/router/src/core/blocklist/transformers.rs
+++ b/crates/router/src/core/blocklist/transformers.rs
@@ -5,9 +5,7 @@ use common_utils::{
};
use error_stack::ResultExt;
use josekit::jwe;
-#[cfg(feature = "aws_kms")]
-use masking::PeekInterface;
-use masking::StrongSecret;
+use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
use crate::{
@@ -35,8 +33,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {
}
async fn generate_fingerprint_request<'a>(
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &blocklist::GenerateFingerprintRequest,
locker_choice: api_enums::LockerChoice,
@@ -45,11 +42,7 @@ async fn generate_fingerprint_request<'a>(
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
@@ -67,8 +60,7 @@ async fn generate_fingerprint_request<'a>(
}
async fn generate_jwe_payload_for_request(
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
@@ -89,18 +81,12 @@ async fn generate_jwe_payload_for_request(
.encode_to_vec()
.change_context(errors::VaultError::GenerateFingerprintFailed)?;
- #[cfg(feature = "aws_kms")]
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
- jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ jwekey.vault_encryption_key.peek().as_bytes()
}
};
- #[cfg(not(feature = "aws_kms"))]
- let public_key = match locker_choice {
- api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
- };
-
let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key)
.await
.change_context(errors::VaultError::SaveCardFailed)
@@ -148,10 +134,7 @@ async fn call_to_locker_for_fingerprint(
locker_choice: api_enums::LockerChoice,
) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> {
let locker = &state.conf.locker;
- #[cfg(not(feature = "aws_kms"))]
- let jwekey = &state.conf.jwekey;
- #[cfg(feature = "aws_kms")]
- let jwekey = &state.kms_secrets;
+ let jwekey = state.conf.jwekey.get_inner();
let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?;
let response = services::call_connector_api(state, request)
@@ -175,30 +158,20 @@ async fn call_to_locker_for_fingerprint(
}
async fn decrypt_generate_fingerprint_response_payload(
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwekey: &settings::Jwekey,
+
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
- #[cfg(feature = "aws_kms")]
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
- jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ jwekey.vault_encryption_key.peek().as_bytes()
}
};
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let public_key = match target_locker {
- api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
- };
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = payment_methods::get_dotted_jwe(jwe_body);
let alg = jwe::RSA_OAEP;
diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs
index e6c1fc9d378..21377d0ba0b 100644
--- a/crates/router/src/core/connector_onboarding.rs
+++ b/crates/router/src/core/connector_onboarding.rs
@@ -24,8 +24,8 @@ pub async fn get_action_url(
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
- let connector_onboarding_conf = state.conf.connector_onboarding.clone();
- let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf);
+ let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
+ let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
@@ -58,8 +58,8 @@ pub async fn sync_onboarding_status(
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
- let connector_onboarding_conf = state.conf.connector_onboarding.clone();
- let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf);
+ let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
+ let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
@@ -75,10 +75,10 @@ pub async fn sync_onboarding_status(
ref paypal_onboarding_data,
)) = status
{
- let connector_onboarding_conf = state.conf.connector_onboarding.clone();
+ let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let auth_details = oss_types::ConnectorAuthType::SignatureKey {
- api_key: connector_onboarding_conf.paypal.client_secret,
- key1: connector_onboarding_conf.paypal.client_id,
+ api_key: connector_onboarding_conf.paypal.client_secret.clone(),
+ key1: connector_onboarding_conf.paypal.client_id.clone(),
api_secret: Secret::new(paypal_onboarding_data.payer_id.clone()),
};
let update_mca_data = paypal::update_mca(
diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs
index 644a2220aee..4c1f16e9135 100644
--- a/crates/router/src/core/connector_onboarding/paypal.rs
+++ b/crates/router/src/core/connector_onboarding/paypal.rs
@@ -63,7 +63,13 @@ pub async fn get_action_url_from_paypal(
}
fn merchant_onboarding_status_url(state: AppState, tracking_id: String) -> String {
- let partner_id = state.conf.connector_onboarding.paypal.partner_id.to_owned();
+ let partner_id = state
+ .conf
+ .connector_onboarding
+ .get_inner()
+ .paypal
+ .partner_id
+ .to_owned();
format!(
"{}v1/customer/partners/{}/merchant-integrations?tracking_id={}",
state.conf.connectors.paypal.base_url,
diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs
index b0d06f9fd65..f2791deb7b6 100644
--- a/crates/router/src/core/currency.rs
+++ b/crates/router/src/core/currency.rs
@@ -11,16 +11,13 @@ use crate::{
pub async fn retrieve_forex(
state: AppState,
) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> {
+ let forex_api = state.conf.forex_api.get_inner();
Ok(ApplicationResponse::Json(
get_forex_rates(
&state,
- state.conf.forex_api.call_delay,
- state.conf.forex_api.local_fetch_retry_delay,
- state.conf.forex_api.local_fetch_retry_count,
- #[cfg(feature = "aws_kms")]
- &state.conf.kms,
- #[cfg(feature = "hashicorp-vault")]
- &state.conf.hc_vault,
+ forex_api.call_delay,
+ forex_api.local_fetch_retry_delay,
+ forex_api.local_fetch_retry_count,
)
.await
.change_context(ApiErrorResponse::GenericNotFoundError {
@@ -44,10 +41,6 @@ pub async fn convert_forex(
amount,
to_currency,
from_currency,
- #[cfg(feature = "aws_kms")]
- &state.conf.kms,
- #[cfg(feature = "hashicorp-vault")]
- &state.conf.hc_vault,
))
.await
.change_context(ApiErrorResponse::InternalServerError)?,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 9ebcc61fce3..882d384edd4 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -653,10 +653,7 @@ pub async fn get_payment_method_from_hs_locker<'a>(
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let locker = &state.conf.locker;
- #[cfg(not(feature = "aws_kms"))]
- let jwekey = &state.conf.jwekey;
- #[cfg(feature = "aws_kms")]
- let jwekey = &state.kms_secrets;
+ let jwekey = state.conf.jwekey.get_inner();
let payment_method_data = if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
@@ -716,10 +713,7 @@ pub async fn call_to_locker_hs<'a>(
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
let locker = &state.conf.locker;
- #[cfg(not(feature = "aws_kms"))]
- let jwekey = &state.conf.jwekey;
- #[cfg(feature = "aws_kms")]
- let jwekey = &state.kms_secrets;
+ let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
let request =
@@ -777,10 +771,7 @@ pub async fn get_card_from_hs_locker<'a>(
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::Card, errors::VaultError> {
let locker = &state.conf.locker;
- #[cfg(not(feature = "aws_kms"))]
- let jwekey = &state.conf.jwekey;
- #[cfg(feature = "aws_kms")]
- let jwekey = &state.kms_secrets;
+ let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
@@ -832,10 +823,7 @@ pub async fn delete_card_from_hs_locker<'a>(
card_reference: &'a str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
let locker = &state.conf.locker;
- #[cfg(not(feature = "aws_kms"))]
- let jwekey = &state.conf.jwekey;
- #[cfg(feature = "aws_kms")]
- let jwekey = &state.kms_secrets;
+ let jwekey = &state.conf.jwekey.get_inner();
let request = payment_methods::mk_delete_card_request_hs(
jwekey,
@@ -1445,7 +1433,7 @@ pub async fn list_payment_methods(
}
let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id);
- let redis_expiry = state.conf.payment_method_auth.redis_expiry;
+ let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry;
if let Some(rc) = redis_conn {
rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry)
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 57e46bc9769..ea25c73499e 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -197,30 +197,19 @@ pub fn get_dotted_jws(jws: encryption::JwsBody) -> String {
}
pub async fn get_decrypted_response_payload(
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
- #[cfg(feature = "aws_kms")]
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
- jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ jwekey.vault_encryption_key.peek().as_bytes()
}
};
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let public_key = match target_locker {
- api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
- };
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = jwe::RSA_OAEP;
@@ -246,8 +235,7 @@ pub async fn get_decrypted_response_payload(
}
pub async fn mk_basilisk_req(
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
@@ -267,18 +255,12 @@ pub async fn mk_basilisk_req(
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
- #[cfg(feature = "aws_kms")]
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
- jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ jwekey.vault_encryption_key.peek().as_bytes()
}
};
- #[cfg(not(feature = "aws_kms"))]
- let public_key = match locker_choice {
- api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
- };
-
let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key)
.await
.change_context(errors::VaultError::SaveCardFailed)
@@ -301,8 +283,7 @@ pub async fn mk_basilisk_req(
}
pub async fn mk_add_locker_request_hs<'a>(
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &StoreLockerReq<'a>,
locker_choice: api_enums::LockerChoice,
@@ -311,11 +292,7 @@ pub async fn mk_add_locker_request_hs<'a>(
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
@@ -471,8 +448,7 @@ pub fn mk_add_card_request(
}
pub async fn mk_get_card_request_hs(
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &str,
merchant_id: &str,
@@ -489,11 +465,7 @@ pub async fn mk_get_card_request_hs(
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
@@ -548,8 +520,7 @@ pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card>
}
pub async fn mk_delete_card_request_hs(
- #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
- #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &str,
merchant_id: &str,
@@ -565,11 +536,7 @@ pub async fn mk_delete_card_request_hs(
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
- #[cfg(feature = "aws_kms")]
- let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
-
- #[cfg(not(feature = "aws_kms"))]
- let private_key = jwekey.vault_private_key.as_bytes();
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 479a0685a97..e29b66ea0ca 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -2,13 +2,6 @@ use api_models::payments as payment_types;
use async_trait::async_trait;
use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
use error_stack::{IntoReport, Report, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
-#[cfg(feature = "hashicorp-vault")]
use masking::ExposeInterface;
use super::{ConstructFlowSpecificData, Feature};
@@ -183,130 +176,40 @@ async fn create_applepay_session_token(
payment_request_data,
session_token_data,
} => {
- let (
- apple_pay_merchant_cert,
- apple_pay_merchant_cert_key,
- common_merchant_identifier,
- ) = async {
- #[cfg(feature = "hashicorp-vault")]
- let client =
- external_services::hashicorp_vault::core::get_hashicorp_client(
- &state.conf.hc_vault,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while building hashicorp client")?;
-
- #[cfg(feature = "hashicorp-vault")]
- {
- Ok::<_, Report<errors::ApiErrorResponse>>((
- masking::Secret::new(
- state
- .conf
- .applepay_decrypt_keys
- .apple_pay_merchant_cert
- .clone(),
- )
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .expose(),
- masking::Secret::new(
- state
- .conf
- .applepay_decrypt_keys
- .apple_pay_merchant_cert_key
- .clone(),
- )
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .expose(),
- masking::Secret::new(
- state
- .conf
- .applepay_merchant_configs
- .common_merchant_identifier
- .clone(),
- )
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .expose(),
- ))
- }
-
- #[cfg(not(feature = "hashicorp-vault"))]
- {
- Ok::<_, Report<errors::ApiErrorResponse>>((
- state
- .conf
- .applepay_decrypt_keys
- .apple_pay_merchant_cert
- .clone(),
- state
- .conf
- .applepay_decrypt_keys
- .apple_pay_merchant_cert_key
- .clone(),
- state
- .conf
- .applepay_merchant_configs
- .common_merchant_identifier
- .clone(),
- ))
- }
- }
- .await?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_apple_pay_merchant_cert =
- aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(apple_pay_merchant_cert)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Apple pay merchant certificate decryption failed")?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_apple_pay_merchant_cert_key =
- aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(apple_pay_merchant_cert_key)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Apple pay merchant certificate key decryption failed",
- )?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_merchant_identifier =
- aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(common_merchant_identifier)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Apple pay merchant identifier decryption failed")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_merchant_identifier = common_merchant_identifier;
+ let merchant_identifier = state
+ .conf
+ .applepay_merchant_configs
+ .get_inner()
+ .common_merchant_identifier
+ .clone()
+ .expose();
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
- decrypted_merchant_identifier.to_string(),
+ merchant_identifier,
session_token_data,
);
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_apple_pay_merchant_cert = apple_pay_merchant_cert;
-
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_apple_pay_merchant_cert_key = apple_pay_merchant_cert_key;
+ let apple_pay_merchant_cert = state
+ .conf
+ .applepay_decrypt_keys
+ .get_inner()
+ .apple_pay_merchant_cert
+ .clone()
+ .expose();
+
+ let apple_pay_merchant_cert_key = state
+ .conf
+ .applepay_decrypt_keys
+ .get_inner()
+ .apple_pay_merchant_cert_key
+ .clone()
+ .expose();
(
payment_request_data,
apple_pay_session_request,
- decrypted_apple_pay_merchant_cert.to_owned(),
- decrypted_apple_pay_merchant_cert_key.to_owned(),
+ apple_pay_merchant_cert,
+ apple_pay_merchant_cert_key,
)
}
payment_types::ApplePayCombinedMetadata::Manual {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b6e28faa4eb..0eaf3c07ee6 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -13,12 +13,6 @@ use data_models::{
use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
use josekit::jwe;
use masking::{ExposeInterface, PeekInterface};
use openssl::{
@@ -2903,17 +2897,14 @@ pub async fn get_merchant_connector_account(
},
)?;
- #[cfg(feature = "aws_kms")]
let private_key = state
- .kms_secrets
+ .conf
.jwekey
- .peek()
+ .get_inner()
.tunnel_private_key
+ .peek()
.as_bytes();
- #[cfg(not(feature = "aws_kms"))]
- let private_key = state.conf.jwekey.tunnel_private_key.as_bytes();
-
let decrypted_mca = services::decrypt_jwe(mca_config.config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256)
.await
.change_context(errors::ApiErrorResponse::UnprocessableEntity{
@@ -3550,39 +3541,13 @@ impl ApplePayData {
&self,
state: &AppState,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
- let apple_pay_ppc = async {
- #[cfg(feature = "hashicorp-vault")]
- let client = external_services::hashicorp_vault::core::get_hashicorp_client(
- &state.conf.hc_vault,
- )
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
- .attach_printable("Failed while creating client")?;
-
- #[cfg(feature = "hashicorp-vault")]
- let output =
- masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc.clone())
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?
- .expose();
-
- #[cfg(not(feature = "hashicorp-vault"))]
- let output = state.conf.applepay_decrypt_keys.apple_pay_ppc.clone();
-
- Ok::<_, error_stack::Report<errors::ApplePayDecryptionError>>(output)
- }
- .await?;
-
- #[cfg(feature = "aws_kms")]
- let cert_data = aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(&apple_pay_ppc)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
-
- #[cfg(not(feature = "aws_kms"))]
- let cert_data = &apple_pay_ppc;
+ let cert_data = state
+ .conf
+ .applepay_decrypt_keys
+ .get_inner()
+ .apple_pay_ppc
+ .clone()
+ .expose();
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
@@ -3634,40 +3599,14 @@ impl ApplePayData {
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
- let apple_pay_ppc_key = async {
- #[cfg(feature = "hashicorp-vault")]
- let client = external_services::hashicorp_vault::core::get_hashicorp_client(
- &state.conf.hc_vault,
- )
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
- .attach_printable("Failed while creating client")?;
-
- #[cfg(feature = "hashicorp-vault")]
- let output =
- masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone())
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
- .attach_printable("Failed while creating client")?
- .expose();
-
- #[cfg(not(feature = "hashicorp-vault"))]
- let output = state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone();
-
- Ok::<_, error_stack::Report<errors::ApplePayDecryptionError>>(output)
- }
- .await?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_apple_pay_ppc_key = aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(&apple_pay_ppc_key)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
+ let decrypted_apple_pay_ppc_key = state
+ .conf
+ .applepay_decrypt_keys
+ .get_inner()
+ .apple_pay_ppc_key
+ .clone()
+ .expose();
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_apple_pay_ppc_key = &apple_pay_ppc_key;
// Create PKey objects from EcKey
let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes())
.into_report()
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index f00c452f3ea..982ed9cae94 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -5,8 +5,6 @@ use api_models::{
payment_methods::{self, BankAccountAccessCreds},
payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData},
};
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::{self, decrypt::VaultFetch};
use hex;
pub mod helpers;
pub mod transformers;
@@ -19,8 +17,6 @@ use common_utils::{
};
use data_models::payments::PaymentIntent;
use error_stack::{IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-pub use external_services::aws_kms;
use helpers::PaymentAuthConnectorDataExt;
use masking::{ExposeInterface, PeekInterface};
use pm_auth::{
@@ -347,34 +343,13 @@ async fn store_bank_details_in_payment_methods(
}
}
- let pm_auth_key = async {
- #[cfg(feature = "hashicorp-vault")]
- let client =
- external_services::hashicorp_vault::core::get_hashicorp_client(&state.conf.hc_vault)
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while creating client")?;
-
- #[cfg(feature = "hashicorp-vault")]
- let output = masking::Secret::new(state.conf.payment_method_auth.pm_auth_key.clone())
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(ApiErrorResponse::InternalServerError)?
- .expose();
-
- #[cfg(not(feature = "hashicorp-vault"))]
- let output = state.conf.payment_method_auth.pm_auth_key.clone();
-
- Ok::<_, error_stack::Report<ApiErrorResponse>>(output)
- }
- .await?;
-
- #[cfg(feature = "aws_kms")]
- let pm_auth_key = aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(pm_auth_key)
- .await
- .change_context(ApiErrorResponse::InternalServerError)?;
+ let pm_auth_key = state
+ .conf
+ .payment_method_auth
+ .get_inner()
+ .pm_auth_key
+ .clone()
+ .expose();
let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> =
Vec::new();
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index ff51668ec57..d749163aa28 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -15,7 +15,7 @@ use super::payouts::PayoutData;
#[cfg(feature = "payouts")]
use crate::core::payments;
use crate::{
- configs::settings,
+ configs::Settings,
consts,
core::errors::{self, RouterResult, StorageErrorExt},
db::StorageInterface,
@@ -942,7 +942,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
}
pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
- conf: &settings::Settings,
+ conf: &Settings,
merchant_id: &str,
) -> bool {
let config_map = &conf
@@ -952,7 +952,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
}
pub fn get_connector_request_reference_id(
- conf: &settings::Settings,
+ conf: &Settings,
merchant_id: &str,
payment_attempt: &data_models::payments::payment_attempt::PaymentAttempt,
) -> String {
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index 79513bfb308..04ccdc32f2c 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -2,8 +2,7 @@ pub mod utils;
use api_models::verifications::{self, ApplepayMerchantResponse};
use common_utils::{errors::CustomResult, request::RequestContent};
use error_stack::ResultExt;
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
+use masking::ExposeInterface;
use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services};
@@ -11,44 +10,26 @@ const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant";
pub async fn verify_merchant_creds_for_applepay(
state: AppState,
- _req: &actix_web::HttpRequest,
body: verifications::ApplepayMerchantVerificationRequest,
- kms_config: &aws_kms::core::AwsKmsConfig,
merchant_id: String,
) -> CustomResult<
services::ApplicationResponse<ApplepayMerchantResponse>,
api_error_response::ApiErrorResponse,
> {
- let encrypted_merchant_identifier = &state
- .conf
- .applepay_merchant_configs
- .common_merchant_identifier;
- let encrypted_cert = &state.conf.applepay_merchant_configs.merchant_cert;
- let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key;
- let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint;
+ let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
- let applepay_internal_merchant_identifier = aws_kms::core::get_aws_kms_client(kms_config)
- .await
- .decrypt(encrypted_merchant_identifier)
- .await
- .change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
-
- let cert_data = aws_kms::core::get_aws_kms_client(kms_config)
- .await
- .decrypt(encrypted_cert)
- .await
- .change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
-
- let key_data = aws_kms::core::get_aws_kms_client(kms_config)
- .await
- .decrypt(encrypted_key)
- .await
- .change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
+ let applepay_internal_merchant_identifier = applepay_merchant_configs
+ .common_merchant_identifier
+ .clone()
+ .expose();
+ let cert_data = applepay_merchant_configs.merchant_cert.clone().expose();
+ let key_data = applepay_merchant_configs.merchant_cert_key.clone().expose();
+ let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint;
let request_body = verifications::ApplepayMerchantVerificationConfigs {
domain_names: body.domain_names.clone(),
- encrypt_to: applepay_internal_merchant_identifier.to_string(),
- partner_internal_merchant_identifier: applepay_internal_merchant_identifier.to_string(),
+ encrypt_to: applepay_internal_merchant_identifier.clone(),
+ partner_internal_merchant_identifier: applepay_internal_merchant_identifier,
partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(),
};
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 5b5bc414d2c..97d981c68eb 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -30,6 +30,7 @@ use actix_web::{
middleware::ErrorHandlers,
};
use http::StatusCode;
+use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret;
use routes::AppState;
use storage_impl::errors::ApplicationResult;
use tokio::sync::{mpsc, oneshot};
@@ -141,7 +142,7 @@ pub fn mk_app(
.service(routes::ConnectorOnboarding::server(state.clone()))
}
- #[cfg(all(feature = "olap", feature = "aws_kms"))]
+ #[cfg(feature = "olap")]
{
server_app = server_app.service(routes::Verify::server(state.clone()));
}
@@ -174,7 +175,7 @@ pub fn mk_app(
///
/// Unwrap used because without the value we can't start the server
#[allow(clippy::expect_used, clippy::unwrap_used)]
-pub async fn start_server(conf: settings::Settings) -> ApplicationResult<Server> {
+pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> {
logger::debug!(startup_config=?conf);
let server = conf.server.clone();
let (tx, rx) = oneshot::channel();
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 51c938b0971..0d7c903b06f 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -37,7 +37,7 @@ pub mod routing;
pub mod user;
#[cfg(feature = "olap")]
pub mod user_role;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
@@ -57,7 +57,7 @@ pub use self::app::Forex;
pub use self::app::Payouts;
#[cfg(all(feature = "olap", feature = "recon"))]
pub use self::app::Recon;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
pub use self::app::Verify;
pub use self::app::{
ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers,
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index cf0f009a0b1..2e95fd536cf 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -1,6 +1,4 @@
use actix_web::{web, HttpRequest, Responder};
-#[cfg(feature = "hashicorp-vault")]
-use error_stack::ResultExt;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -44,27 +42,7 @@ pub async fn api_key_create(
&req,
payload,
|state, _, payload| async {
- #[cfg(feature = "aws_kms")]
- let aws_kms_client =
- external_services::aws_kms::core::get_aws_kms_client(&state.clone().conf.kms).await;
-
- #[cfg(feature = "hashicorp-vault")]
- let hc_client = external_services::hashicorp_vault::core::get_hashicorp_client(
- &state.clone().conf.hc_vault,
- )
- .await
- .change_context(crate::core::errors::ApiErrorResponse::InternalServerError)?;
-
- api_keys::create_api_key(
- state,
- #[cfg(feature = "aws_kms")]
- aws_kms_client,
- #[cfg(feature = "hashicorp-vault")]
- hc_client,
- payload,
- merchant_id.clone(),
- )
- .await
+ api_keys::create_api_key(state, payload, merchant_id.clone()).await
},
auth::auth_type(
&auth::AdminApiAuth,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index e204ef3b9e0..73558c78d7b 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1,25 +1,17 @@
use std::sync::Arc;
use actix_web::{web, Scope};
-#[cfg(all(
- feature = "olap",
- any(feature = "hashicorp-vault", feature = "aws_kms")
-))]
-use analytics::AnalyticsConfig;
#[cfg(all(feature = "business_profile_routing", feature = "olap"))]
use api_models::routing::RoutingRetrieveQuery;
#[cfg(feature = "olap")]
use common_enums::TransactionType;
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt};
#[cfg(feature = "email")]
use external_services::email::{ses::AwsSes, EmailService};
use external_services::file_storage::FileStorageInterface;
-#[cfg(all(feature = "olap", feature = "hashicorp-vault"))]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
-use hyperswitch_interfaces::encryption_interface::EncryptionManagementInterface;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
-use masking::PeekInterface;
+use hyperswitch_interfaces::{
+ encryption_interface::EncryptionManagementInterface,
+ secrets_interface::secret_state::{RawSecret, SecuredSecret},
+};
use router_env::tracing_actix_web::RequestId;
use scheduler::SchedulerInterface;
use storage_impl::MockDb;
@@ -37,7 +29,7 @@ use super::payouts::*;
use super::pm_auth;
#[cfg(feature = "olap")]
use super::routing as cloud_routing;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "olap")]
use super::{
@@ -49,6 +41,7 @@ use super::{cache::*, health::*};
use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*};
#[cfg(feature = "oltp")]
use super::{ephemeral_key::*, payment_methods::*, webhooks::*};
+use crate::configs::secrets_transformers;
#[cfg(all(feature = "frm", feature = "oltp"))]
use crate::routes::fraud_check as frm_routes;
#[cfg(all(feature = "recon", feature = "olap"))]
@@ -68,12 +61,10 @@ pub use crate::{
pub struct AppState {
pub flow_name: String,
pub store: Box<dyn StorageInterface>,
- pub conf: Arc<settings::Settings>,
+ pub conf: Arc<settings::Settings<RawSecret>>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<dyn EmailService>,
- #[cfg(feature = "aws_kms")]
- pub kms_secrets: Arc<settings::ActiveKmsSecrets>,
pub api_client: Box<dyn crate::services::ApiClient>,
#[cfg(feature = "olap")]
pub pool: crate::analytics::AnalyticsProvider,
@@ -89,7 +80,7 @@ impl scheduler::SchedulerAppState for AppState {
}
pub trait AppStateInfo {
- fn conf(&self) -> settings::Settings;
+ fn conf(&self) -> settings::Settings<RawSecret>;
fn store(&self) -> Box<dyn StorageInterface>;
fn event_handler(&self) -> EventsHandler;
#[cfg(feature = "email")]
@@ -101,7 +92,7 @@ pub trait AppStateInfo {
}
impl AppStateInfo for AppState {
- fn conf(&self) -> settings::Settings {
+ fn conf(&self) -> settings::Settings<RawSecret> {
self.conf.as_ref().to_owned()
}
fn store(&self) -> Box<dyn StorageInterface> {
@@ -138,7 +129,7 @@ impl AsRef<Self> for AppState {
}
#[cfg(feature = "email")]
-pub async fn create_email_client(settings: &settings::Settings) -> impl EmailService {
+pub async fn create_email_client(settings: &settings::Settings<RawSecret>) -> impl EmailService {
match settings.email.active_email_client {
external_services::email::AvailableEmailClients::SES => {
AwsSes::create(&settings.email, settings.proxy.https_url.to_owned()).await
@@ -151,12 +142,20 @@ impl AppState {
///
/// Panics if Store can't be created or JWE decryption fails
pub async fn with_storage(
- #[cfg_attr(not(all(feature = "olap", feature = "aws_kms")), allow(unused_mut))]
- mut conf: settings::Settings,
+ conf: settings::Settings<SecuredSecret>,
storage_impl: StorageImpl,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
+ #[allow(clippy::expect_used)]
+ let secret_management_client = conf
+ .secrets_management
+ .get_secret_management_client()
+ .await
+ .expect("Failed to create secret management client");
+
+ let conf = secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await;
+
#[allow(clippy::expect_used)]
let encryption_client = conf
.encryption_management
@@ -165,14 +164,6 @@ impl AppState {
.expect("Failed to create encryption client");
Box::pin(async move {
- #[cfg(feature = "aws_kms")]
- let aws_kms_client = aws_kms::core::get_aws_kms_client(&conf.kms).await;
- #[cfg(all(feature = "hashicorp-vault", feature = "olap"))]
- #[allow(clippy::expect_used)]
- let hc_client =
- external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault)
- .await
- .expect("Failed while creating hashicorp_client");
let testable = storage_impl == StorageImpl::PostgresqlTest;
#[allow(clippy::expect_used)]
let event_handler = conf
@@ -208,80 +199,9 @@ impl AppState {
),
};
- #[cfg(all(feature = "hashicorp-vault", feature = "olap"))]
- #[allow(clippy::expect_used)]
- match conf.analytics {
- AnalyticsConfig::Clickhouse { .. } => {}
- AnalyticsConfig::Sqlx { ref mut sqlx }
- | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. }
- | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => {
- sqlx.password = sqlx
- .password
- .clone()
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .expect("Failed while fetching from hashicorp vault");
- }
- };
-
- #[cfg(all(feature = "aws_kms", feature = "olap"))]
- #[allow(clippy::expect_used)]
- match conf.analytics {
- AnalyticsConfig::Clickhouse { .. } => {}
- AnalyticsConfig::Sqlx { ref mut sqlx }
- | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. }
- | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => {
- sqlx.password = aws_kms_client
- .decrypt(&sqlx.password.peek())
- .await
- .expect("Failed to decrypt password")
- .into();
- }
- };
-
- #[cfg(all(feature = "hashicorp-vault", feature = "olap"))]
- #[allow(clippy::expect_used)]
- {
- conf.connector_onboarding = conf
- .connector_onboarding
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .expect("Failed to decrypt connector onboarding credentials");
- }
-
- #[cfg(all(feature = "aws_kms", feature = "olap"))]
- #[allow(clippy::expect_used)]
- {
- conf.connector_onboarding = conf
- .connector_onboarding
- .decrypt_inner(aws_kms_client)
- .await
- .expect("Failed to decrypt connector onboarding credentials");
- }
-
#[cfg(feature = "olap")]
let pool = crate::analytics::AnalyticsProvider::from_conf(&conf.analytics).await;
- #[cfg(all(feature = "hashicorp-vault", feature = "olap"))]
- #[allow(clippy::expect_used)]
- {
- conf.jwekey = conf
- .jwekey
- .clone()
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .expect("Failed to decrypt connector onboarding credentials");
- }
-
- #[cfg(feature = "aws_kms")]
- #[allow(clippy::expect_used)]
- let kms_secrets = settings::ActiveKmsSecrets {
- jwekey: conf.jwekey.clone().into(),
- }
- .decrypt_inner(aws_kms_client)
- .await
- .expect("Failed while performing AWS KMS decryption");
-
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
@@ -293,8 +213,6 @@ impl AppState {
conf: Arc::new(conf),
#[cfg(feature = "email")]
email_client,
- #[cfg(feature = "aws_kms")]
- kms_secrets: Arc::new(kms_secrets),
api_client,
event_handler,
#[cfg(feature = "olap")]
@@ -308,7 +226,7 @@ impl AppState {
}
pub async fn new(
- conf: settings::Settings,
+ conf: settings::Settings<SecuredSecret>,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
@@ -1114,10 +1032,10 @@ impl Gsm {
}
}
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
pub struct Verify;
-#[cfg(all(feature = "olap", feature = "aws_kms"))]
+#[cfg(feature = "olap")]
impl Verify {
pub fn server(state: AppState) -> Scope {
web::scope("/verify")
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 770ae9aafcc..f667479ceaa 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -5,10 +5,6 @@ global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits
counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses
-#[cfg(feature = "aws_kms")]
-counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures
-#[cfg(feature = "aws_kms")]
-counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures
// API Level Metrics
counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index 4bcbacdf991..91fd204ba2f 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -17,7 +17,6 @@ pub async fn apple_pay_merchant_registration(
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
- let kms_conf = &state.clone().conf.kms;
Box::pin(api::server_wrap(
flow,
state,
@@ -26,9 +25,7 @@ pub async fn apple_pay_merchant_registration(
|state, _, body| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
- &req,
body,
- kms_conf,
merchant_id.clone(),
)
},
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index dc7bf14fecf..617b9df7122 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -13,22 +13,16 @@ pub mod recon;
#[cfg(feature = "email")]
pub mod email;
-#[cfg(any(feature = "aws_kms", feature = "hashicorp-vault"))]
-use data_models::errors::StorageError;
use data_models::errors::StorageResult;
use error_stack::{IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt};
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
-use masking::{PeekInterface, StrongSecret};
+use masking::{ExposeInterface, StrongSecret};
#[cfg(feature = "kv_store")]
use storage_impl::KVRouterStore;
use storage_impl::RouterStore;
use tokio::sync::oneshot;
pub use self::{api::*, encryption::*};
-use crate::{configs::settings, consts, core::errors};
+use crate::{configs::Settings, consts, core::errors};
#[cfg(not(feature = "olap"))]
pub type StoreType = storage_impl::database::store::Store;
@@ -40,61 +34,25 @@ pub type Store = RouterStore<StoreType>;
#[cfg(feature = "kv_store")]
pub type Store = KVRouterStore<StoreType>;
+/// # Panics
+///
+/// Will panic if hex decode of master key fails
+#[allow(clippy::expect_used)]
pub async fn get_store(
- config: &settings::Settings,
+ config: &Settings,
shut_down_signal: oneshot::Sender<()>,
test_transaction: bool,
) -> StorageResult<Store> {
- #[cfg(feature = "aws_kms")]
- let aws_kms_client = aws_kms::core::get_aws_kms_client(&config.kms).await;
-
- #[cfg(feature = "hashicorp-vault")]
- let hc_client =
- external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
- .await
- .change_context(StorageError::InitializationError)?;
-
- let master_config = config.master_database.clone();
-
- #[cfg(feature = "hashicorp-vault")]
- let master_config = master_config
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .change_context(StorageError::InitializationError)
- .attach_printable("Failed to fetch data from hashicorp vault")?;
-
- #[cfg(feature = "aws_kms")]
- let master_config = master_config
- .decrypt_inner(aws_kms_client)
- .await
- .change_context(StorageError::InitializationError)
- .attach_printable("Failed to decrypt master database config")?;
+ let master_config = config.master_database.clone().into_inner();
#[cfg(feature = "olap")]
- let replica_config = config.replica_database.clone();
-
- #[cfg(all(feature = "olap", feature = "hashicorp-vault"))]
- let replica_config = replica_config
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .change_context(StorageError::InitializationError)
- .attach_printable("Failed to fetch data from hashicorp vault")?;
+ let replica_config = config.replica_database.clone().into_inner();
- #[cfg(all(feature = "olap", feature = "aws_kms"))]
- let replica_config = replica_config
- .decrypt_inner(aws_kms_client)
- .await
- .change_context(StorageError::InitializationError)
- .attach_printable("Failed to decrypt replica database config")?;
+ #[allow(clippy::expect_used)]
+ let master_enc_key = hex::decode(config.secrets.get_inner().master_enc_key.clone().expose())
+ .map(StrongSecret::new)
+ .expect("Failed to decode master key from hex");
- let master_enc_key = get_master_enc_key(
- config,
- #[cfg(feature = "aws_kms")]
- aws_kms_client,
- #[cfg(feature = "hashicorp-vault")]
- hc_client,
- )
- .await;
#[cfg(not(feature = "olap"))]
let conf = master_config.into();
#[cfg(feature = "olap")]
@@ -126,34 +84,6 @@ pub async fn get_store(
Ok(store)
}
-#[allow(clippy::expect_used)]
-async fn get_master_enc_key(
- conf: &crate::configs::settings::Settings,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
-) -> StrongSecret<Vec<u8>> {
- let master_enc_key = conf.secrets.master_enc_key.clone();
-
- #[cfg(feature = "hashicorp-vault")]
- let master_enc_key = master_enc_key
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .expect("Failed to fetch master enc key");
-
- #[cfg(feature = "aws_kms")]
- let master_enc_key = masking::Secret::<_, masking::WithType>::new(
- master_enc_key
- .decrypt_inner(aws_kms_client)
- .await
- .expect("Failed to decrypt master enc key"),
- );
-
- let master_enc_key = hex::decode(master_enc_key.peek()).expect("Failed to decode from hex");
-
- StrongSecret::new(master_enc_key)
-}
-
#[inline]
pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> {
use ring::rand::SecureRandom;
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 1c4d1810c88..738f57e9d70 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -29,7 +29,7 @@ use tera::{Context, Tera};
use self::request::{HeaderExt, RequestBuilderExt};
use super::authentication::AuthenticateAndFetch;
use crate::{
- configs::settings::{Connectors, Settings},
+ configs::{settings::Connectors, Settings},
consts,
core::{
api_locking,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 455dc97d03e..7cf1855b441 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -3,14 +3,8 @@ use api_models::{payment_methods::PaymentMethodListRequest, payments};
use async_trait::async_trait;
use common_utils::date_time;
use error_stack::{report, IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt};
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::decrypt::VaultFetch;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
-#[cfg(feature = "hashicorp-vault")]
-use masking::ExposeInterface;
-use masking::{PeekInterface, StrongSecret};
+use masking::PeekInterface;
use serde::Serialize;
use self::blacklist::BlackList;
@@ -20,13 +14,14 @@ use super::jwt;
#[cfg(feature = "recon")]
use super::recon::ReconToken;
#[cfg(feature = "olap")]
+use crate::configs::Settings;
+#[cfg(feature = "olap")]
use crate::consts;
#[cfg(feature = "olap")]
use crate::core::errors::UserResult;
#[cfg(feature = "recon")]
use crate::routes::AppState;
use crate::{
- configs::settings,
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
@@ -108,7 +103,7 @@ pub struct UserAuthToken {
#[cfg(feature = "olap")]
impl UserAuthToken {
- pub async fn new_token(user_id: String, settings: &settings::Settings) -> UserResult<String> {
+ pub async fn new_token(user_id: String, settings: &Settings) -> 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 token_payload = Self { user_id, exp };
@@ -131,7 +126,7 @@ impl AuthToken {
user_id: String,
merchant_id: String,
role_id: String,
- settings: &settings::Settings,
+ settings: &Settings,
org_id: String,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
@@ -224,16 +219,7 @@ where
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
- api_keys::get_hash_key(
- &config.api_keys,
- #[cfg(feature = "aws_kms")]
- aws_kms::core::get_aws_kms_client(&config.kms).await,
- #[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- )
- .await?
+ config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
@@ -285,41 +271,6 @@ where
}
}
-static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> =
- tokio::sync::OnceCell::const_new();
-
-pub async fn get_admin_api_key(
- secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
-) -> RouterResult<&'static StrongSecret<String>> {
- ADMIN_API_KEY
- .get_or_try_init(|| async {
- #[cfg(not(feature = "aws_kms"))]
- let admin_api_key = secrets.admin_api_key.clone();
-
- #[cfg(feature = "aws_kms")]
- let admin_api_key = secrets
- .kms_encrypted_admin_api_key
- .decrypt_inner(aws_kms_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to AWS KMS decrypt admin API key")?;
-
- #[cfg(feature = "hashicorp-vault")]
- let admin_api_key = masking::Secret::new(admin_api_key)
- .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to KMS decrypt admin API key")?
- .expose();
-
- Ok(StrongSecret::new(admin_api_key))
- })
- .await
-}
-
#[derive(Debug)]
pub struct UserWithoutMerchantJWTAuth;
@@ -367,17 +318,7 @@ where
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
- let admin_api_key = get_admin_api_key(
- &conf.secrets,
- #[cfg(feature = "aws_kms")]
- aws_kms::core::get_aws_kms_client(&conf.kms).await,
- #[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting admin api key")?,
- )
- .await?;
+ let admin_api_key = &conf.secrets.get_inner().admin_api_key;
if request_admin_api_key != admin_api_key.peek() {
Err(report!(errors::ApiErrorResponse::Unauthorized)
@@ -912,43 +853,12 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool {
headers.get(crate::headers::AUTHORIZATION).is_some()
}
-static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::OnceCell::const_new();
-
-pub async fn get_jwt_secret(
- secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
-) -> RouterResult<&'static StrongSecret<String>> {
- JWT_SECRET
- .get_or_try_init(|| async {
- #[cfg(feature = "aws_kms")]
- let jwt_secret = secrets
- .kms_encrypted_jwt_secret
- .decrypt_inner(aws_kms_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to AWS KMS decrypt JWT secret")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let jwt_secret = secrets.jwt_secret.clone();
-
- Ok(StrongSecret::new(jwt_secret))
- })
- .await
-}
-
pub async fn decode_jwt<T>(token: &str, state: &impl AppStateInfo) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
{
let conf = state.conf();
- let secret = get_jwt_secret(
- &conf.secrets,
- #[cfg(feature = "aws_kms")]
- aws_kms::core::get_aws_kms_client(&conf.kms).await,
- )
- .await?
- .peek()
- .as_bytes();
+ let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes();
let key = DecodingKey::from_secret(secret);
decode::<T>(token, &key, &Validation::new(Algorithm::HS256))
@@ -1008,33 +918,6 @@ where
default_auth
}
-#[cfg(feature = "recon")]
-static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> =
- tokio::sync::OnceCell::const_new();
-
-#[cfg(feature = "recon")]
-pub async fn get_recon_admin_api_key(
- secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] kms_client: &aws_kms::core::AwsKmsClient,
-) -> RouterResult<&'static StrongSecret<String>> {
- RECON_API_KEY
- .get_or_try_init(|| async {
- #[cfg(feature = "aws_kms")]
- let recon_admin_api_key = secrets
- .kms_encrypted_recon_admin_api_key
- .decrypt_inner(kms_client)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to KMS decrypt recon admin API key")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let recon_admin_api_key = secrets.recon_admin_api_key.clone();
-
- Ok(StrongSecret::new(recon_admin_api_key))
- })
- .await
-}
-
#[cfg(feature = "recon")]
pub struct ReconAdmin;
@@ -1053,14 +936,9 @@ where
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let conf = state.conf();
- let admin_api_key = get_recon_admin_api_key(
- &conf.secrets,
- #[cfg(feature = "aws_kms")]
- aws_kms::core::get_aws_kms_client(&conf.kms).await,
- )
- .await?;
+ let admin_api_key = conf.secrets.get_inner().recon_admin_api_key.peek();
- if request_admin_api_key != admin_api_key.peek() {
+ if request_admin_api_key != admin_api_key {
Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Recon Admin Authentication Failure"))?;
}
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 46cfad08783..fa1eecbaab8 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -147,7 +147,7 @@ impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
merchant_id: Option<String>,
- settings: &configs::settings::Settings,
+ settings: &configs::Settings,
) -> CustomResult<String, UserErrors> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
@@ -178,7 +178,7 @@ pub fn get_link_with_token(
pub struct VerifyEmail {
pub recipient_email: domain::UserEmail,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -208,7 +208,7 @@ impl EmailData for VerifyEmail {
pub struct ResetPassword {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -238,7 +238,7 @@ impl EmailData for ResetPassword {
pub struct MagicLink {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -268,7 +268,7 @@ impl EmailData for MagicLink {
pub struct InviteUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
pub merchant_id: String,
}
@@ -302,7 +302,7 @@ impl EmailData for InviteUser {
pub struct InviteRegisteredUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
pub merchant_id: String,
}
@@ -339,7 +339,7 @@ impl EmailData for InviteRegisteredUser {
pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -365,7 +365,7 @@ pub struct BizEmailProd {
pub legal_business_name: String,
pub business_location: String,
pub business_website: String,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -413,7 +413,7 @@ pub struct ProFeatureRequest {
pub feature_name: String,
pub merchant_id: String,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub settings: std::sync::Arc<configs::Settings>,
pub subject: String,
}
diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs
index 05de1b4e11e..6a78e2232a9 100644
--- a/crates/router/src/services/jwt.rs
+++ b/crates/router/src/services/jwt.rs
@@ -3,8 +3,7 @@ use error_stack::{IntoReport, ResultExt};
use jsonwebtoken::{encode, EncodingKey, Header};
use masking::PeekInterface;
-use super::authentication;
-use crate::{configs::settings::Settings, core::errors::UserErrors};
+use crate::{configs::Settings, core::errors::UserErrors};
pub fn generate_exp(
exp_duration: std::time::Duration,
@@ -24,14 +23,7 @@ pub async fn generate_jwt<T>(
where
T: serde::ser::Serialize,
{
- let jwt_secret = authentication::get_jwt_secret(
- &settings.secrets,
- #[cfg(feature = "aws_kms")]
- external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to obtain JWT secret")?;
+ let jwt_secret = &settings.secrets.get_inner().jwt_secret;
encode(
&Header::default(),
claims_data,
diff --git a/crates/router/src/services/recon.rs b/crates/router/src/services/recon.rs
index d5a2151a487..cc10fb7c7f5 100644
--- a/crates/router/src/services/recon.rs
+++ b/crates/router/src/services/recon.rs
@@ -3,9 +3,9 @@ use masking::Secret;
use super::jwt;
use crate::{
+ configs::Settings,
consts,
core::{self, errors::RouterResult},
- routes::app::settings::Settings,
};
#[derive(serde::Serialize, serde::Deserialize)]
diff --git a/crates/router/src/utils/connector_onboarding/paypal.rs b/crates/router/src/utils/connector_onboarding/paypal.rs
index 6d7f2692be7..ff9b5ab59e7 100644
--- a/crates/router/src/utils/connector_onboarding/paypal.rs
+++ b/crates/router/src/utils/connector_onboarding/paypal.rs
@@ -20,7 +20,8 @@ pub async fn generate_access_token(state: AppState) -> RouterResult<types::Acces
&state.conf.connectors,
connector.to_string().as_str(),
)?;
- let connector_auth = super::get_connector_auth(connector, &state.conf.connector_onboarding)?;
+ let connector_auth =
+ super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?;
connector::Paypal::get_access_token(
&state,
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs
index 30ac4815efb..3ba395c95a3 100644
--- a/crates/router/src/utils/currency.rs
+++ b/crates/router/src/utils/currency.rs
@@ -4,10 +4,6 @@ use api_models::enums;
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use currency_conversion::types::{CurrencyFactors, ExchangeRates};
use error_stack::{IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::{self, decrypt::VaultFetch};
use masking::PeekInterface;
use once_cell::sync::Lazy;
use redis_interface::DelReply;
@@ -128,9 +124,6 @@ async fn waited_fetch_and_update_caches(
state: &AppState,
local_fetch_retry_delay: u64,
local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
for _n in 1..local_fetch_retry_count {
sleep(Duration::from_millis(local_fetch_retry_delay)).await;
@@ -148,15 +141,7 @@ async fn waited_fetch_and_update_caches(
}
}
//acquire lock one last time and try to fetch and update local & redis
- successive_fetch_and_save_forex(
- state,
- None,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
+ successive_fetch_and_save_forex(state, None).await
}
impl TryFrom<DefaultExchangeRates> for ExchangeRates {
@@ -192,23 +177,11 @@ pub async fn get_forex_rates(
call_delay: i64,
local_fetch_retry_delay: u64,
local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
if let Some(local_rates) = retrieve_forex_from_local().await {
if local_rates.is_expired(call_delay) {
// expired local data
- handler_local_expired(
- state,
- call_delay,
- local_rates,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
+ handler_local_expired(state, call_delay, local_rates).await
} else {
// Valid data present in local
Ok(local_rates)
@@ -220,10 +193,6 @@ pub async fn get_forex_rates(
call_delay,
local_fetch_retry_delay,
local_fetch_retry_count,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
)
.await
}
@@ -234,46 +203,16 @@ async fn handler_local_no_data(
call_delay: i64,
_local_fetch_retry_delay: u64,
_local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match retrieve_forex_from_redis(state).await {
- Ok(Some(data)) => {
- fallback_forex_redis_check(
- state,
- data,
- call_delay,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
- }
+ Ok(Some(data)) => fallback_forex_redis_check(state, data, call_delay).await,
Ok(None) => {
// No data in local as well as redis
- Ok(successive_fetch_and_save_forex(
- state,
- None,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await?)
+ Ok(successive_fetch_and_save_forex(state, None).await?)
}
Err(err) => {
logger::error!(?err);
- Ok(successive_fetch_and_save_forex(
- state,
- None,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await?)
+ Ok(successive_fetch_and_save_forex(state, None).await?)
}
}
}
@@ -281,36 +220,19 @@ async fn handler_local_no_data(
async fn successive_fetch_and_save_forex(
state: &AppState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match acquire_redis_lock(state).await {
Ok(lock_acquired) => {
if !lock_acquired {
return stale_redis_data.ok_or(ForexCacheError::CouldNotAcquireLock.into());
}
- let api_rates = fetch_forex_rates(
- state,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await;
+ let api_rates = fetch_forex_rates(state).await;
match api_rates {
Ok(rates) => successive_save_data_to_redis_local(state, rates).await,
Err(err) => {
// API not able to fetch data call secondary service
logger::error!(?err);
- let secondary_api_rates = fallback_fetch_forex_rates(
- state,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await;
+ let secondary_api_rates = fallback_fetch_forex_rates(state).await;
match secondary_api_rates {
Ok(rates) => Ok(successive_save_data_to_redis_local(state, rates).await?),
Err(err) => stale_redis_data.ok_or({
@@ -351,9 +273,6 @@ async fn fallback_forex_redis_check(
state: &AppState,
redis_data: FxExchangeRatesCacheEntry,
call_delay: i64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await {
Some(redis_forex) => {
@@ -364,15 +283,7 @@ async fn fallback_forex_redis_check(
}
None => {
// redis expired
- successive_fetch_and_save_forex(
- state,
- Some(redis_data),
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
+ successive_fetch_and_save_forex(state, Some(redis_data)).await
}
}
}
@@ -381,9 +292,6 @@ async fn handler_local_expired(
state: &AppState,
call_delay: i64,
local_rates: FxExchangeRatesCacheEntry,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match retrieve_forex_from_redis(state).await {
Ok(redis_data) => {
@@ -397,71 +305,22 @@ async fn handler_local_expired(
}
None => {
// Redis is expired going for API request
- successive_fetch_and_save_forex(
- state,
- Some(local_rates),
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
+ successive_fetch_and_save_forex(state, Some(local_rates)).await
}
}
}
Err(e) => {
// data not present in redis waited fetch
logger::error!(?e);
- successive_fetch_and_save_forex(
- state,
- Some(local_rates),
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
- )
- .await
+ successive_fetch_and_save_forex(state, Some(local_rates)).await
}
}
}
async fn fetch_forex_rates(
state: &AppState,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
-
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> {
- let forex_api_key = async {
- #[cfg(feature = "hashicorp-vault")]
- let client = hashicorp_vault::core::get_hashicorp_client(hc_config)
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- #[cfg(not(feature = "hashicorp-vault"))]
- let output = state.conf.forex_api.api_key.clone();
- #[cfg(feature = "hashicorp-vault")]
- let output = state
- .conf
- .forex_api
- .api_key
- .clone()
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- Ok::<_, error_stack::Report<ForexCacheError>>(output)
- }
- .await?;
- #[cfg(feature = "aws_kms")]
- let forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config)
- .await
- .decrypt(forex_api_key.peek())
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- #[cfg(not(feature = "aws_kms"))]
- let forex_api_key = forex_api_key.peek();
+ let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY);
let forex_request = services::RequestBuilder::new()
@@ -516,40 +375,8 @@ async fn fetch_forex_rates(
pub async fn fallback_fetch_forex_rates(
state: &AppState,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
- let fallback_api_key = async {
- #[cfg(feature = "hashicorp-vault")]
- let client = hashicorp_vault::core::get_hashicorp_client(hc_config)
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- #[cfg(not(feature = "hashicorp-vault"))]
- let output = state.conf.forex_api.fallback_api_key.clone();
- #[cfg(feature = "hashicorp-vault")]
- let output = state
- .conf
- .forex_api
- .fallback_api_key
- .clone()
- .fetch_inner::<hashicorp_vault::core::Kv2>(client)
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- Ok::<_, error_stack::Report<ForexCacheError>>(output)
- }
- .await?;
- #[cfg(feature = "aws_kms")]
- let fallback_forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config)
- .await
- .decrypt(fallback_api_key.peek())
- .await
- .change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
-
- #[cfg(not(feature = "aws_kms"))]
- let fallback_forex_api_key = fallback_api_key.peek();
+ let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek();
let fallback_forex_url: String =
format!("{}{}", FALLBACK_FOREX_BASE_URL, fallback_forex_api_key,);
@@ -627,6 +454,7 @@ async fn release_redis_lock(
}
async fn acquire_redis_lock(app_state: &AppState) -> CustomResult<bool, ForexCacheError> {
+ let forex_api = app_state.conf.forex_api.get_inner();
app_state
.store
.get_redis_conn()
@@ -635,9 +463,8 @@ async fn acquire_redis_lock(app_state: &AppState) -> CustomResult<bool, ForexCac
REDIX_FOREX_CACHE_KEY,
"",
Some(
- (app_state.conf.forex_api.local_fetch_retry_count
- * app_state.conf.forex_api.local_fetch_retry_delay
- + app_state.conf.forex_api.api_timeout)
+ (forex_api.local_fetch_retry_count * forex_api.local_fetch_retry_delay
+ + forex_api.api_timeout)
.try_into()
.into_report()
.change_context(ForexCacheError::ConversionError)?,
@@ -691,19 +518,13 @@ pub async fn convert_currency(
amount: i64,
to_currency: String,
from_currency: String,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> {
+ let forex_api = state.conf.forex_api.get_inner();
let rates = get_forex_rates(
&state,
- state.conf.forex_api.call_delay,
- state.conf.forex_api.local_fetch_retry_delay,
- state.conf.forex_api.local_fetch_retry_count,
- #[cfg(feature = "aws_kms")]
- aws_kms_config,
- #[cfg(feature = "hashicorp-vault")]
- hc_config,
+ forex_api.call_delay,
+ forex_api.local_fetch_retry_delay,
+ forex_api.local_fetch_retry_count,
)
.await
.change_context(ForexCacheError::ApiError)?;
| 2024-02-15T19:07:44Z |
## Description
<!-- Describe your changes in detail -->
This PR incorporates the `hyperswitch_interface` crate into the router crate. Secondly, all secrets(configs) decryption now happens during application startup, eliminating runtime decryption. Lastly, the addition of an encryption_client in the AppState enables easy runtime encryption and decryption processes.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 75c633fc7c37341177597041ccbcdfc3cf9e236f |
This PR refactors the way decryption of secrets work in router. So all flows should work fine wherever secrets are being used.
Flows that has secrets decryption involved and requires testing -
* `merchant account` creation
* `api key` creation
* Hit `/health/ready` - Everything should be fine
* `Add card` `Retrieve card` `Delete card`
* `Currency conversion` flows
* `Apple pay flow` - payment request with the decrypted apple pay token
* Verify flow for applepay merchant verification
* Payment method auth flow (Plaid)
* connector onboarding flow
| [
"config/config.example.toml",
"config/deployments/env_specific.toml",
"crates/drainer/Cargo.toml",
"crates/drainer/src/main.rs",
"crates/drainer/src/secrets_transformers.rs",
"crates/drainer/src/settings.rs",
"crates/external_services/src/aws_kms.rs",
"crates/external_services/src/aws_kms/core.rs",
... | |
juspay/hyperswitch | juspay__hyperswitch-3667 | Bug: Add migration for IsChangePasswordRequired enum
Add migration for force password reset enum, `IsChangePasswordRequired` | diff --git a/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql
new file mode 100644
index 00000000000..c7c9cbeb401
--- /dev/null
+++ b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/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-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql
new file mode 100644
index 00000000000..6c9269ef2e1
--- /dev/null
+++ b/migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'is_change_password_required';
\ No newline at end of file
| 2024-02-15T15:45:34Z |
## Description
Add migration for force password enum(`IsChangePasswordRequired`).
## Motivation and Context
For force password enum `isChangePasswordRequired` migration is not present.
# | 9f385008106e1cfca8ded40009b364f97ecf69f2 | Tested locally, for the invite flow, after migration its working fine and value of enum is getting updated correctly.
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "cdc@gmail.com",
"name": "test3",
"role_id": "merchant_admin"
}
'
```
| [
"migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/down.sql",
"migrations/2024-02-15-153757_add_dashboard_metadata_enum_is_change_password_required/up.sql"
] | |
juspay/hyperswitch | juspay__hyperswitch-3664 | Bug: Add Toml file changes for dashboard origin
| diff --git a/config/development.toml b/config/development.toml
index ad5944c34c3..3a3540da5b6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -235,7 +235,7 @@ workers = 1
[cors]
max_age = 30
-origins = "http://localhost:8080"
+origins = "http://localhost:8080,http://localhost:9000"
allowed_methods = "GET,POST,PUT,DELETE"
wildcard_origin = false
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 4f1f34d1bed..9728497aaf6 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -83,7 +83,7 @@ max_feed_count = 200
[cors]
max_age = 30
-origins = "http://localhost:8080"
+origins = "http://localhost:8080,http://localhost:9000"
allowed_methods = "GET,POST,PUT,DELETE"
wildcard_origin = false
| 2024-02-15T13:08:31Z |
## Description
For localhost testing added Dashboard Origin in the Toml files.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 0666d814af93045ff23c85d8fd796da08cd5749b | Nothing to test.
| [
"config/development.toml",
"config/docker_compose.toml"
] | |
juspay/hyperswitch | juspay__hyperswitch-3660 | Bug: [REFACTOR]: include api key expiry workflow into process tracker
Currently, `ApiKeyExpiryWorkflow` is not part of the workflows being run in scheduler. Refactor to include it, as well as update the email sending section to the latest email refactor logic | diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs
index 6608d4ed2fd..1875fc4dc51 100644
--- a/crates/diesel_models/src/api_keys.rs
+++ b/crates/diesel_models/src/api_keys.rs
@@ -138,7 +138,7 @@ mod diesel_impl {
// Tracking data by process_tracker
#[derive(Default, Debug, Deserialize, Serialize, Clone)]
-pub struct ApiKeyExpiryWorkflow {
+pub struct ApiKeyExpiryTrackingData {
pub key_id: String,
pub merchant_id: String,
pub api_key_expiry: Option<PrimitiveDateTime>,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 2f3dfa82831..88e9c88b4fc 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -13,7 +13,7 @@ default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "acc
aws_s3 = ["external_services/aws_s3"]
aws_kms = ["external_services/aws_kms"]
hashicorp-vault = ["external_services/hashicorp-vault"]
-email = ["external_services/email", "olap"]
+email = ["external_services/email", "scheduler/email", "olap"]
frm = []
stripe = ["dep:serde_qs"]
release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"]
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 59a108ef5e6..caa69ea1394 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -216,6 +216,8 @@ pub enum PTRunner {
PaymentsSyncWorkflow,
RefundWorkflowRouter,
DeleteTokenizeDataWorkflow,
+ #[cfg(feature = "email")]
+ ApiKeyExpiryWorkflow,
}
#[derive(Debug, Copy, Clone)]
@@ -240,6 +242,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner {
Some(PTRunner::DeleteTokenizeDataWorkflow) => {
Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow)
}
+ #[cfg(feature = "email")]
+ Some(PTRunner::ApiKeyExpiryWorkflow) => {
+ Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow)
+ }
_ => Err(ProcessTrackerError::UnexpectedFlow)?,
};
let app_state = &state.clone();
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index b694d1291a8..39212ab3814 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -253,7 +253,7 @@ pub async fn add_api_key_expiry_task(
}
}
- let api_key_expiry_tracker = &storage::ApiKeyExpiryWorkflow {
+ let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
// We need API key expiry too, because we need to decide on the schedule_time in
@@ -427,7 +427,7 @@ pub async fn update_api_key_expiry_task(
let task_ids = vec![task_id.clone()];
- let updated_tracking_data = &storage::ApiKeyExpiryWorkflow {
+ let updated_tracking_data = &storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
api_key_expiry: api_key.expires_at,
diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
new file mode 100644
index 00000000000..1865ae38141
--- /dev/null
+++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
@@ -0,0 +1,203 @@
+<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
+<title>API Key Expiry Notice</title>
+<body style="background-color: #ececec">
+ <style>
+ .apple-footer a {{
+ text-decoration: none !important;
+ color: #999 !important;
+ border: none !important;
+ }}
+ .apple-email a {{
+ text-decoration: none !important;
+ color: #448bff !important;
+ border: none !important;
+ }}
+ </style>
+ <div
+ id="wrapper"
+ style="
+ background-color: none;
+ margin: 0 auto;
+ text-align: center;
+ width: 60%;
+ -premailer-height: 200;
+ "
+ >
+ <table
+ align="center"
+ class="main-table"
+ style="
+ -premailer-cellpadding: 0;
+ -premailer-cellspacing: 0;
+ background-color: #fff;
+ border: 0;
+ border-top: 5px solid #0165ef;
+ margin: 0 auto;
+ mso-table-lspace: 0;
+ mso-table-rspace: 0;
+ padding: 0 40;
+ text-align: center;
+ width: 100%;
+ "
+ bgcolor="#ffffff"
+ cellpadding="0"
+ cellspacing="0"
+ >
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="75"
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="25"
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="50"
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="headline"
+ style="
+ color: #444;
+ font-family: Roboto, Helvetica, Arial, san-serif;
+ font-size: 30px;
+ font-weight: 100;
+ line-height: 36px;
+ margin: 0 auto;
+ padding: 0;
+ text-align: center;
+ "
+ align="center"
+ >
+ <p style="font-size: 18px">Dear Merchant,</p>
+ <span style="font-size: 18px">
+ It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted
+ access to our platform and continued smooth operation of your services, we kindly request that you take the
+ necessary actions as soon as possible.
+ </span>
+ </td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-sm"
+ style="
+ -premailer-height: 20;
+ -premailer-width: 80%;
+ line-height: 10px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ width="100%"
+ ></td>
+ </tr>
+
+ <tr>
+ <td
+ class="spacer-sm"
+ style="
+ -premailer-height: 20;
+ -premailer-width: 100%;
+ line-height: 10px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="20"
+ width="100%"
+ ></td>
+ </tr>
+
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="75"
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="headline"
+ style="
+ color: #444;
+ font-family: Roboto, Helvetica, Arial, san-serif;
+ font-size: 18px;
+ font-weight: 100;
+ line-height: 36px;
+ margin: 0 auto;
+ padding: 0;
+ text-align: center;
+ "
+ align="center"
+ >
+ Thanks,<br />
+ Team Hyperswitch
+ </td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="75"
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="75"
+ width="100%"
+ ></td>
+ </tr>
+ </table>
+ </div>
+</body>
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 6ad1a0eb99a..389979d5723 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -44,6 +44,9 @@ pub enum EmailBody {
user_name: String,
user_email: String,
},
+ ApiKeyExpiryReminder {
+ expires_in: u8,
+ },
}
pub mod html {
@@ -113,6 +116,10 @@ Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
),
+ EmailBody::ApiKeyExpiryReminder { expires_in } => format!(
+ include_str!("assets/api_key_expiry_reminder.html"),
+ expires_in = expires_in,
+ ),
}
}
}
@@ -381,3 +388,26 @@ impl EmailData for ProFeatureRequest {
})
}
}
+
+pub struct ApiKeyExpiryReminder {
+ pub recipient_email: domain::UserEmail,
+ pub subject: &'static str,
+ pub expires_in: u8,
+}
+
+#[async_trait::async_trait]
+impl EmailData for ApiKeyExpiryReminder {
+ async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
+ let recipient = self.recipient_email.clone().into_inner();
+
+ let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder {
+ expires_in: self.expires_in,
+ });
+
+ Ok(EmailContents {
+ subject: self.subject.to_string(),
+ body: external_services::email::IntermediateString::new(body),
+ recipient,
+ })
+ }
+}
diff --git a/crates/router/src/types/storage/api_keys.rs b/crates/router/src/types/storage/api_keys.rs
index 74c503d3c76..b1051c3d19c 100644
--- a/crates/router/src/types/storage/api_keys.rs
+++ b/crates/router/src/types/storage/api_keys.rs
@@ -1,3 +1,3 @@
#[cfg(feature = "email")]
-pub use diesel_models::api_keys::ApiKeyExpiryWorkflow;
+pub use diesel_models::api_keys::ApiKeyExpiryTrackingData;
pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey};
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index b036193bb27..deb5bf785fa 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "email")]
+pub mod api_key_expiry;
pub mod payment_sync;
pub mod refund_router;
pub mod tokenized_data;
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index eb3c1d9c1ce..b9830c4ebc5 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -1,30 +1,35 @@
-use common_utils::ext_traits::ValueExt;
-use diesel_models::enums::{self as storage_enums};
+use common_utils::{errors::ValidationError, ext_traits::ValueExt};
+use diesel_models::{enums as storage_enums, ApiKeyExpiryTrackingData};
+use router_env::logger;
+use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerAppState};
-use super::{ApiKeyExpiryWorkflow, ProcessTrackerWorkflow};
use crate::{
errors,
logger::error,
- routes::AppState,
+ routes::{metrics, AppState},
+ services::email::types::ApiKeyExpiryReminder,
types::{
api,
+ domain::UserEmail,
storage::{self, ProcessTrackerExt},
},
utils::OptionExt,
};
+pub struct ApiKeyExpiryWorkflow;
+
#[async_trait::async_trait]
-impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow {
+impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow {
async fn execute_workflow<'a>(
&'a self,
state: &'a AppState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
- let tracking_data: storage::ApiKeyExpiryWorkflow = process
+ let tracking_data: ApiKeyExpiryTrackingData = process
.tracking_data
.clone()
- .parse_value("ApiKeyExpiryWorkflow")?;
+ .parse_value("ApiKeyExpiryTrackingData")?;
let key_store = state
.store
@@ -41,7 +46,13 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow {
let email_id = merchant_account
.merchant_details
.parse_value::<api::MerchantDetails>("MerchantDetails")?
- .primary_email;
+ .primary_email
+ .ok_or(errors::ProcessTrackerError::EValidationError(
+ ValidationError::MissingRequiredField {
+ field_name: "email".to_string(),
+ }
+ .into(),
+ ))?;
let task_id = process.id.clone();
@@ -53,28 +64,26 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow {
usize::try_from(retry_count)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?,
)
- .ok_or(errors::ProcessTrackerError::EApiErrorResponse(
- errors::ApiErrorResponse::InvalidDataValue {
- field_name: "index",
- }
- .into(),
- ))?;
+ .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
+
+ let email_contents = ApiKeyExpiryReminder {
+ recipient_email: UserEmail::from_pii_email(email_id).map_err(|err| {
+ logger::error!(%err,"Failed to convert recipient's email to UserEmail from pii::Email");
+ errors::ProcessTrackerError::EApiErrorResponse
+ })?,
+ subject: "API Key Expiry Notice",
+ expires_in: *expires_in,
+ };
state
.email_client
.clone()
- .send_email(
- email_id.ok_or_else(|| errors::ProcessTrackerError::MissingRequiredField)?,
- "API Key Expiry Notice".to_string(),
- format!("Dear Merchant,\n
-It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted access to our platform and continued smooth operation of your services, we kindly request that you take the necessary actions as soon as possible.\n\n
-Thanks,\n
-Team Hyperswitch"),
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
)
.await
- .map_err(|_| errors::ProcessTrackerError::FlowExecutionError {
- flow: "ApiKeyExpiryWorkflow",
- })?;
+ .map_err(errors::ProcessTrackerError::EEmailError)?;
// If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector
if retry_count
@@ -82,7 +91,7 @@ Team Hyperswitch"),
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?
{
process
- .finish_with_status(db, format!("COMPLETED_BY_PT_{task_id}"))
+ .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string())
.await?
}
// If tasks are remaining that has to be scheduled
@@ -93,12 +102,7 @@ Team Hyperswitch"),
usize::try_from(retry_count + 1)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?,
)
- .ok_or(errors::ProcessTrackerError::EApiErrorResponse(
- errors::ApiErrorResponse::InvalidDataValue {
- field_name: "index",
- }
- .into(),
- ))?;
+ .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| {
api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml
index b281bc862a2..72eaea3be06 100644
--- a/crates/scheduler/Cargo.toml
+++ b/crates/scheduler/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2021"
default = ["kv_store", "olap"]
olap = ["storage_impl/olap"]
kv_store = []
+email = ["external_services/email"]
[dependencies]
# Third party crates
diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs
index 481fae07937..78a0bdee624 100644
--- a/crates/scheduler/src/errors.rs
+++ b/crates/scheduler/src/errors.rs
@@ -1,4 +1,6 @@
pub use common_utils::errors::{ParsingError, ValidationError};
+#[cfg(feature = "email")]
+use external_services::email::EmailError;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
use storage_impl::errors::StorageError;
@@ -51,6 +53,9 @@ pub enum ProcessTrackerError {
EParsingError(error_stack::Report<ParsingError>),
#[error("Validation Error Received: {0}")]
EValidationError(error_stack::Report<ValidationError>),
+ #[cfg(feature = "email")]
+ #[error("Received Error EmailError: {0}")]
+ EEmailError(error_stack::Report<EmailError>),
#[error("Type Conversion error")]
TypeConversionError,
}
@@ -111,3 +116,9 @@ error_to_process_tracker_error!(
error_stack::Report<ValidationError>,
ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>)
);
+
+#[cfg(feature = "email")]
+error_to_process_tracker_error!(
+ error_stack::Report<EmailError>,
+ ProcessTrackerError::EEmailError(error_stack::Report<EmailError>)
+);
| 2024-02-15T12:37:59Z |
## Description
<!-- Describe your changes in detail -->
Currently, `ApiKeyExpiryWorkflow` is not part of the workflows being run in scheduler. This PR refactors that workflow to be included in the existing workflow list, as well as update the email sending section to the latest email refactor logic.
Includes changes for sending an html page in email as opposed to plain text
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Re-enables api key expiry reminder workflow
# | 0666d814af93045ff23c85d8fd796da08cd5749b |
1. Locally set up email config
2. Created a merchant
3. Created an api key with some expiry (Locally changed the schedule time to be 3 minutes before the expiry)

Since the email is triggered 7 days before expiry, complete flow cannot be tested in sandbox. However, api_key can be created with expiry set, then check the process tracker table whether an entry has been created in the table for this api_key with schedule time being 7 days prior to expiry.
Query -
```
select * from process_tracker where runner = 'API_KEY_EXPIRY_WORKFLOW' order by created_at desc;
```
Check the `id` field of the latest entry in the table which has to be something like `API_KEY_EXPIRY_WORKFLOW_API_KEY_EXPIRY_{YOUR_KEY_ID}` and `schedule_time` being 7 days prior to expiry
| [
"crates/diesel_models/src/api_keys.rs",
"crates/router/Cargo.toml",
"crates/router/src/bin/scheduler.rs",
"crates/router/src/core/api_keys.rs",
"crates/router/src/services/email/assets/api_key_expiry_reminder.html",
"crates/router/src/services/email/types.rs",
"crates/router/src/types/storage/api_keys.r... | |
juspay/hyperswitch | juspay__hyperswitch-3658 | Bug: feat: Email blacklist
| diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 002452a8a35..54fbecc64f3 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -311,6 +311,10 @@ pub async fn change_password(
.await
.change_context(UserErrors::InternalServerError)?;
+ let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id())
+ .await
+ .map_err(|e| logger::error!(?e));
+
#[cfg(not(feature = "email"))]
{
state
@@ -372,10 +376,12 @@ pub async fn reset_password(
state: AppState,
request: user_api::ResetPasswordRequest,
) -> UserResponse<()> {
- let token =
- auth::decode_jwt::<email_types::EmailToken>(request.token.expose().as_str(), &state)
- .await
- .change_context(UserErrors::LinkInvalid)?;
+ let token = request.token.expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
+ .await
+ .change_context(UserErrors::LinkInvalid)?;
+
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
let password = domain::UserPassword::new(request.password)?;
@@ -384,7 +390,7 @@ pub async fn reset_password(
let user = state
.store
.update_user_by_email(
- token.get_email(),
+ email_token.get_email(),
storage_user::UserUpdate::AccountUpdate {
name: None,
password: Some(hash_password),
@@ -395,7 +401,7 @@ pub async fn reset_password(
.await
.change_context(UserErrors::InternalServerError)?;
- if let Some(inviter_merchant_id) = token.get_merchant_id() {
+ if let Some(inviter_merchant_id) = email_token.get_merchant_id() {
let update_status_result = state
.store
.update_user_role_by_user_id_merchant_id(
@@ -403,13 +409,20 @@ pub async fn reset_password(
inviter_merchant_id,
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
- modified_by: user.user_id,
+ modified_by: user.user_id.clone(),
},
)
.await;
logger::info!(?update_status_result);
}
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+ let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
+ .await
+ .map_err(|e| logger::error!(?e));
+
Ok(ApplicationResponse::StatusOk)
}
@@ -454,7 +467,13 @@ pub async fn invite_user(
merchant_id: user_from_token.merchant_id,
role_id: request.role_id,
org_id: user_from_token.org_id,
- status: UserStatus::Active,
+ status: {
+ if cfg!(feature = "email") {
+ UserStatus::InvitationSent
+ } else {
+ UserStatus::Active
+ }
+ },
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
@@ -1050,12 +1069,14 @@ pub async fn verify_email_without_invite_checks(
state: AppState,
req: user_api::VerifyEmailRequest,
) -> UserResponse<user_api::DashboardEntryResponse> {
- let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state)
+ let token = req.token.clone().expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
.await
.change_context(UserErrors::LinkInvalid)?;
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
let user = state
.store
- .find_user_by_email(token.get_email())
+ .find_user_by_email(email_token.get_email())
.await
.change_context(UserErrors::InternalServerError)?;
let user = state
@@ -1065,6 +1086,9 @@ pub async fn verify_email_without_invite_checks(
.change_context(UserErrors::InternalServerError)?;
let user_from_db: domain::UserFromStorage = user.into();
let user_role = user_from_db.get_role_from_db(state.clone()).await?;
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
Ok(ApplicationResponse::Json(
@@ -1077,13 +1101,16 @@ pub async fn verify_email(
state: AppState,
req: user_api::VerifyEmailRequest,
) -> UserResponse<user_api::SignInResponse> {
- let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state)
+ let token = req.token.clone().expose();
+ let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
.await
.change_context(UserErrors::LinkInvalid)?;
+ auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
+
let user = state
.store
- .find_user_by_email(token.get_email())
+ .find_user_by_email(email_token.get_email())
.await
.change_context(UserErrors::InternalServerError)?;
@@ -1115,6 +1142,10 @@ pub async fn verify_email(
.await?
};
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+
Ok(ApplicationResponse::Json(
signin_strategy.get_signin_response(&state).await?,
))
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 6fab28433b4..325ef29bad3 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,6 +5,8 @@ use common_utils::date_time;
use error_stack::{IntoReport, ResultExt};
use redis_interface::RedisConnectionPool;
+#[cfg(feature = "email")]
+use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
@@ -47,6 +49,33 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>(
.map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
+#[cfg(feature = "email")]
+pub async fn insert_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> {
+ let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
+ let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX);
+ let expiry =
+ expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
+ redis_conn
+ .set_key_with_expiry(blacklist_key.as_str(), true, expiry)
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
+#[cfg(feature = "email")]
+pub async fn check_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> {
+ let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
+ let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX);
+ let key_exists = redis_conn
+ .exists::<()>(blacklist_key.as_str())
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ if key_exists {
+ return Err(UserErrors::LinkInvalid.into());
+ }
+ Ok(())
+}
+
fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
| 2024-02-15T12:21:20Z |
## Description
- Adding blacklisting for email tokens, this will prevent use of same email token to be used twice.
- Change Password & Reset Password logs out user from all open dashboard sessions.
<!-- Describe your changes in detail -->
## Motivation and Context
Prevention of use of same email link to be used twice.
Forcing Users to re-enter password if password is changed.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 0666d814af93045ff23c85d8fd796da08cd5749b | With Dashboard Frontend.
Following links should not work twice:
- Magic Link
To generate magic link email use dashboard frontend or below curl.
```sh
curl --location --request POST '<URL>/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": ""
}'
```
- Reset Password
To generate reset password email use dashboard frontend or below curl.
```sh
curl --location --request POST '<URL>/user/forgot_password' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": ""
}'
```
All sessions should be logged out after change password or reset password.
Expected error response for the use of email token twice
```json
{
"error": {
"type": "invalid_request",
"message": "Invalid or expired link",
"code": "UR_04"
}
}
```
| [
"crates/router/src/core/user.rs",
"crates/router/src/services/authentication/blacklist.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3654 | Bug: [FIX] cors throwing unallowed headers
| diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs
index 9baa4484ee4..21293301b95 100644
--- a/crates/router/src/cors.rs
+++ b/crates/router/src/cors.rs
@@ -7,6 +7,7 @@ pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors {
let mut cors = actix_cors::Cors::default()
.allowed_methods(allowed_methods)
+ .allow_any_header()
.max_age(config.max_age);
if config.wildcard_origin {
@@ -15,6 +16,8 @@ pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors {
for origin in &config.origins {
cors = cors.allowed_origin(origin);
}
+ // Only allow this in case if it's not wildcard origins. ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
+ cors = cors.supports_credentials();
}
cors
| 2024-02-15T07:56:03Z |
## Description
<!-- Describe your changes in detail -->
Allow all headers on CORS
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 fixes CORS error on headers not being allowed
# | 2d4f6b3fa004a3f03beaa604e2dbfe95fcbe22a6 |
- Do a preflight request to `/user/role`
```bash
curl --location --request OPTIONS 'http://localhost:8080/user/role' \
--header 'authority: sandbox.hyperswitch.io' \
--header 'accept: */*' \
--header 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'access-control-request-headers: api-key,authorization,content-type' \
--header 'access-control-request-method: GET' \
--header 'cache-control: no-cache' \
--header 'origin: https://app.hyperswitch.io' \
--header 'pragma: no-cache' \
--header 'referer: https://app.hyperswitch.io/' \
--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/120.0.0.0 Safari/537.36'
```
Should send a 200 OK response
| [
"crates/router/src/cors.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3647 | Bug: [FIX] create a CORS rule for hyperswitch
| diff --git a/config/config.example.toml b/config/config.example.toml
index 9551fe4f7a2..2b189ea4022 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -327,6 +327,12 @@ paypal = { currency = "USD,INR", country = "US" }
key_id = "" # The AWS key ID used by the KMS SDK for decrypting data.
region = "" # The AWS region used by the KMS SDK for decrypting data.
+[cors]
+max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
+origins = "http://localhost:8080" # List of origins that are allowed to make requests.
+allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed
+wildcard_origin = false # If true, allows any origin to make requests
+
# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
[email]
sender_email = "example@example.com" # Sender email
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 04831376050..39bf7060b66 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -45,6 +45,12 @@ partner_id = "paypal_partner_id"
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = ["merchant_id_1", "merchant_id_2", "etc.,"]
+[cors]
+max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
+origins = "http://localhost:8080" # List of origins that are allowed to make requests.
+allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed
+wildcard_origin = false # If true, allows any origin to make requests
+
# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
[email]
sender_email = "example@example.com" # Sender email
diff --git a/config/development.toml b/config/development.toml
index 1bff54d8f43..d3b94f1e7e6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -233,6 +233,12 @@ port = 3000
host = "127.0.0.1"
workers = 1
+[cors]
+max_age = 30
+origins = "http://localhost:8080"
+allowed_methods = "GET,POST,PUT,DELETE"
+wildcard_origin = false
+
[email]
sender_email = "example@example.com"
aws_region = ""
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 7aabf3bb56e..90c9aa94fb7 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -81,6 +81,11 @@ max_in_flight_commands = 5000
default_command_timeout = 0
max_feed_count = 200
+[cors]
+max_age = 30
+origins = "http://localhost:8080"
+allowed_methods = "GET,POST,PUT,DELETE"
+wildcard_origin = false
[refund]
max_attempts = 10
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index e9b4de40d27..a7e36921961 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -19,6 +19,20 @@ impl Default for super::settings::Server {
}
}
+impl Default for super::settings::CorsSettings {
+ fn default() -> Self {
+ Self {
+ origins: HashSet::from_iter(["http://localhost:8080".to_string()]),
+ allowed_methods: HashSet::from_iter(
+ ["GET", "PUT", "POST", "DELETE"]
+ .into_iter()
+ .map(ToString::to_string),
+ ),
+ wildcard_origin: false,
+ max_age: 30,
+ }
+ }
+}
impl Default for super::settings::Database {
fn default() -> Self {
Self {
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 13c3ba23e1d..8ed2daef5f3 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -107,6 +107,7 @@ pub struct Settings {
pub dummy_connector: DummyConnector,
#[cfg(feature = "email")]
pub email: EmailSettings,
+ pub cors: CorsSettings,
pub mandates: Mandates,
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
@@ -242,6 +243,17 @@ pub struct DummyConnector {
pub discord_invite_url: String,
}
+#[derive(Debug, Deserialize, Clone)]
+pub struct CorsSettings {
+ #[serde(default, deserialize_with = "deserialize_hashset")]
+ pub origins: HashSet<String>,
+ #[serde(default)]
+ pub wildcard_origin: bool,
+ pub max_age: usize,
+ #[serde(deserialize_with = "deserialize_hashset")]
+ pub allowed_methods: HashSet<String>,
+}
+
#[derive(Debug, Deserialize, Clone)]
pub struct Mandates {
pub supported_payment_methods: SupportedPaymentMethodsForMandate,
@@ -714,6 +726,8 @@ impl Settings {
self.locker.validate()?;
self.connectors.validate("connectors")?;
+ self.cors.validate()?;
+
self.scheduler
.as_ref()
.map(|scheduler_settings| scheduler_settings.validate())
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 655dca33384..21ef4037d81 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -124,6 +124,22 @@ impl super::settings::SupportedConnectors {
}
}
+impl super::settings::CorsSettings {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Allowed Origins must be empty when wildcard origin is true".to_string(),
+ ))
+ })?;
+
+ common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(),
+ ))
+ })
+ }
+}
+
#[cfg(feature = "kv_store")]
impl super::settings::DrainerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs
index 07e12b0d3fd..9baa4484ee4 100644
--- a/crates/router/src/cors.rs
+++ b/crates/router/src/cors.rs
@@ -1,19 +1,21 @@
// use actix_web::http::header;
-pub fn cors() -> actix_cors::Cors {
- actix_cors::Cors::permissive() // FIXME : Never use in production
+use crate::configs::settings;
- /*
- .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
- .allowed_headers(vec![header::AUTHORIZATION, header::CONTENT_TYPE]);
- if CONFIG.profile == "debug" { // --------->>> FIXME: It should be conditional
- cors.allowed_origin_fn(|origin, _req_head| {
- origin.as_bytes().starts_with(b"http://localhost")
- })
- } else {
+pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors {
+ let allowed_methods = config.allowed_methods.iter().map(|s| s.as_str());
+
+ let mut cors = actix_cors::Cors::default()
+ .allowed_methods(allowed_methods)
+ .max_age(config.max_age);
- FIXME : I don't know what to put here
- .allowed_origin_fn(|origin, _req_head| origin.as_bytes().starts_with(b"http://localhost"))
+ if config.wildcard_origin {
+ cors = cors.allow_any_origin()
+ } else {
+ for origin in &config.origins {
+ cors = cors.allowed_origin(origin);
+ }
}
- */
+
+ cors
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index ed443c9e418..19bd28b8dbc 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -91,7 +91,7 @@ pub fn mk_app(
InitError = (),
>,
> {
- let mut server_app = get_application_builder(request_body_limit);
+ let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone());
#[cfg(feature = "dummy_connector")]
{
@@ -231,6 +231,7 @@ impl Stop for mpsc::Sender<()> {
pub fn get_application_builder(
request_body_limit: usize,
+ cors: settings::CorsSettings,
) -> actix_web::App<
impl ServiceFactory<
ServiceRequest,
@@ -257,7 +258,7 @@ pub fn get_application_builder(
))
.wrap(middleware::default_response_headers())
.wrap(middleware::RequestId)
- .wrap(cors::cors())
+ .wrap(cors::cors(cors))
// this middleware works only for Http1.1 requests
.wrap(middleware::Http400RequestDetailsLogger)
.wrap(middleware::LogSpanInitializer)
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 85dfec5232e..85cf404ed2e 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -254,6 +254,12 @@ bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.giropay = {connector_list = "adyen,globalpay"}
+[cors]
+max_age = 30
+origins = "http://localhost:8080"
+allowed_methods = "GET,POST,PUT,DELETE"
+wildcard_origin = false
+
[mandates.update_mandate_supported]
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
| 2024-02-13T19:42:10Z |
## Description
<!-- Describe your changes in detail -->
Adds cors rules to actix
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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
# | 774a0322aa4b36d87b122e47cd893383e262de12 |
- Configure allowed origins in `ROUTER__CORS__ORIGINS`.
- Add `Origin` header to that configured to your config and the request should return 200
```bash
curl --location 'http://localhost:8080/health' \
--header 'Origin: http://localhost:8080'
```
- And configure origin header to something else like `google.com`. It should return `Bad Request` with Response
`Origin is not allowed to make this request`
```bash
curl --location 'http://localhost:8080/health' \
--header 'Origin: https://google.com'
```
| [
"config/config.example.toml",
"config/deployments/env_specific.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/router/src/configs/defaults.rs",
"crates/router/src/configs/settings.rs",
"crates/router/src/configs/validations.rs",
"crates/router/src/cors.rs",
"crates/router/src... | |
juspay/hyperswitch | juspay__hyperswitch-3643 | Bug: [BUG] Update Iatapay config URL to use sandbox URl instead of production URL
### Bug Description
It bugs out when you try to do a payment with Iatapay and it throws Unauthorized error in Sandbox environment
### Expected Behavior
It should do the payment.
### Actual Behavior
Throws an error
### Steps To Reproduce
1. Do a Payment through Iatapay
### Context For The Bug
Error. Unauthorized error.
### Environment
Are you using hyperswitch hosted version? Yes
Sandbox
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 42588cb7345..564a2d9e984 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -43,7 +43,7 @@ globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
gocardless.base_url = "https://api-sandbox.gocardless.com"
helcim.base_url = "https://api.helcim.com/"
-iatapay.base_url = "https://iata-pay.iata.org/api/v1"
+iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
@@ -121,7 +121,6 @@ bank_redirect.ideal.connector_list = "stripe,adyen,globalpay"
bank_redirect.sofort.connector_list = "stripe,adyen,globalpay"
bank_redirect.giropay.connector_list = "adyen,globalpay"
-
[mandates.update_mandate_supported]
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
| 2024-02-13T09:39:17Z |
## Description
<!-- Describe your changes in detail -->
This PR updates Iatapay to use Sandbox URL instead of Production URL in Sandbox environment.
Closes #3643
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Everytime, we need to manually do another deployment manually to see whether the connector is working as expected. With this PR, if they want to test, we'll do manual deployment with production URL going forward.
#
#### Create - Payment
```curl
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"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://pixincreate.dev",
"payment_method": "upi",
"payment_method_type": "upi_collect",
"payment_method_data": {
"upi": {
"vpa_id": "successtest@iata"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "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": "IN",
"first_name": "joseph",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```json
{
"payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ",
"merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q",
"created": "2024-02-13T09:33:44.649Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": "upi",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": 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"
}
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://pixincreate.dev/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "https://sandbox.hyperswitch.io/payments/redirect/pay_4vM0FY3dKVl0yTKS2dJJ/postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896/pay_4vM0FY3dKVl0yTKS2dJJ_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1707816824,
"expires": 1707820424,
"secret": "epk_124b752c19a14485ae02906c800475a1"
},
"manual_retry_allowed": null,
"connector_transaction_id": "PHK6FODTMD0IO",
"frm_message": null,
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1",
"payment_link": null,
"profile_id": "pro_uKrcYw3NgIA71P3M1DAW",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-13T09:48:44.649Z",
"fingerprint": null
}
```
#### Retrieve - Payment
```curl
curl --location 'https://sandbox.hyperswitch.io/payments/pay_4vM0FY3dKVl0yTKS2dJJ' \
--header 'Accept: application/json' \
--header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR'
```
```json
{
"payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ",
"merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "iatapay",
"client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q",
"created": "2024-02-13T09:33:44.649Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": "upi",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": 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"
}
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://pixincreate.dev/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "PHK6FODTMD0IO",
"frm_message": null,
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1",
"payment_link": null,
"profile_id": "pro_uKrcYw3NgIA71P3M1DAW",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-13T09:48:44.649Z",
"fingerprint": null
}
``` | 6e103cef50fea31d2508880985f80f0fd65cd536 |
Iataoay payments in Sandbox environments should work now:
#### Create - Payment
```curl
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"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://pixincreate.dev",
"payment_method": "upi",
"payment_method_type": "upi_collect",
"payment_method_data": {
"upi": {
"vpa_id": "successtest@iata"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "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": "IN",
"first_name": "joseph",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```json
{
"payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ",
"merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q",
"created": "2024-02-13T09:33:44.649Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": "upi",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": 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"
}
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://pixincreate.dev/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "https://sandbox.hyperswitch.io/payments/redirect/pay_4vM0FY3dKVl0yTKS2dJJ/postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896/pay_4vM0FY3dKVl0yTKS2dJJ_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1707816824,
"expires": 1707820424,
"secret": "epk_124b752c19a14485ae02906c800475a1"
},
"manual_retry_allowed": null,
"connector_transaction_id": "PHK6FODTMD0IO",
"frm_message": null,
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1",
"payment_link": null,
"profile_id": "pro_uKrcYw3NgIA71P3M1DAW",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-13T09:48:44.649Z",
"fingerprint": null
}
```
#### Retrieve - Payment
```curl
curl --location 'https://sandbox.hyperswitch.io/payments/pay_4vM0FY3dKVl0yTKS2dJJ' \
--header 'Accept: application/json' \
--header 'api-key: snd_oJVcvSxV6aBs3qzsG8en6nVUOMYcczuNBSCaIRToSiHhreVNNOYVmCj9gccgXuhR'
```
```json
{
"payment_id": "pay_4vM0FY3dKVl0yTKS2dJJ",
"merchant_id": "postman_merchant_GHAction_329d9d3f-e66f-4b01-a085-da6baa0d7896",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "iatapay",
"client_secret": "pay_4vM0FY3dKVl0yTKS2dJJ_secret_OEMfrIA3fJuUi8R67p6Q",
"created": "2024-02-13T09:33:44.649Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": "upi",
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": 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"
}
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://pixincreate.dev/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "PHK6FODTMD0IO",
"frm_message": null,
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_4vM0FY3dKVl0yTKS2dJJ_1",
"payment_link": null,
"profile_id": "pro_uKrcYw3NgIA71P3M1DAW",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3Q8AZBbrkmL6x0Mxfko3",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-13T09:48:44.649Z",
"fingerprint": null
}
```
| [
"config/deployments/sandbox.toml"
] | |
juspay/hyperswitch | juspay__hyperswitch-3642 | Bug: docs(connector): Add wasm docs in connector integration docs
Add connector.md file doesn't have information about connector configs where we add connector to control center from backend configs. Documentation for where to add configs in wasm should be mentioned in add_connector.md | diff --git a/add_connector.md b/add_connector.md
index 7fc3dcb27d1..f859c521f0e 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -668,6 +668,187 @@ In the `connector/utils.rs` file, you'll discover utility functions that aid in
let json_wallet_data: CheckoutGooglePayData =wallet_data.get_wallet_token_as_json()?;
```
+### **Connector configs for control center**
+
+This section is explicitly for developers who are using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Below is a more detailed documentation that guides you through updating the connector configuration in the `development.toml` file in Hyperswitch and running the wasm-pack build command. Please replace placeholders such as `/absolute/path/to/` with the actual absolute paths.
+
+1. Install wasm-pack: Run the following command to install wasm-pack:
+
+```bash
+cargo install wasm-pack
+```
+
+2. Add connector configuration:
+
+ Open the `development.toml` file located at `crates/connector_configs/toml/development.toml` in your Hyperswitch project.
+
+ Locate the [stripe] section as an example and add the configuration for the `example_connector`. Here's an example:
+
+ ```toml
+ # crates/connector_configs/toml/development.toml
+
+ # Other connector configurations...
+
+ [stripe]
+ [stripe.connector_auth.HeaderKey]
+ api_key="Secret Key"
+
+ # Add any other Stripe-specific configuration here
+
+ [example_connector]
+ # Your specific connector configuration for reference
+ # ...
+
+ ```
+
+ provide the necessary configuration details for the `example_connector`. Don't forget to save the file.
+
+3. Update paths:
+
+ Replace `/absolute/path/to/hyperswitch-control-center` with the absolute path to your Hyperswitch Control Center repository and `/absolute/path/to/hyperswitch` with the absolute path to your Hyperswitch repository.
+
+4. Run `wasm-pack` build:
+
+ Execute the following command in your terminal:
+
+ ```bash
+ wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector
+ ```
+
+ This command builds the WebAssembly files for the `dummy_connector` feature and places them in the specified directory.
+
+Notes:
+
+- Ensure that you replace placeholders like `/absolute/path/to/` with the actual absolute paths in your file system.
+- Verify that your connector configurations in `development.toml` are correct and saved before running the `wasm-pack` command.
+- Check for any error messages during the build process and resolve them accordingly.
+
+By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully.
+
+Certainly! Below is a detailed documentation guide on updating the `ConnectorTypes.res` and `ConnectorUtils.res` files in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project.
+
+Update `ConnectorTypes.res`:
+
+1. Open `ConnectorTypes.res`:
+
+ Open the `ConnectorTypes.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorTypes.res` in your Hyperswitch-Control-Center project.
+
+2. Add Connector enum:
+
+ Add the new connector name enum under the `type connectorName` section. Here's an example:
+
+ ```reason
+ /* src/screens/HyperSwitch/Connectors/ConnectorTypes.res */
+
+ type connectorName =
+ | Stripe
+ | DummyConnector
+ | YourNewConnector
+ /* Add any other connector enums as needed */
+ ```
+
+ Replace `YourNewConnector` with the name of your newly added connector.
+
+3. Save the file:
+
+ Save the changes made to `ConnectorTypes.res`.
+
+Update `ConnectorUtils.res`:
+
+1. Open `ConnectorUtils.res`:
+
+ Open the `ConnectorUtils.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorUtils.res` in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project.
+
+2. Add Connector Description:
+
+ Update the following functions in `ConnectorUtils.res`:
+
+ ```reason
+ /* src/screens/HyperSwitch/Connectors/ConnectorUtils.res */
+
+
+ let connectorList : array<connectorName> = [Stripe,YourNewConnector]
+
+
+ let getConnectorNameString = (connectorName: connectorName) =>
+ switch connectorName {
+ | Stripe => "Stripe"
+ | DummyConnector => "Dummy Connector"
+ | YourNewConnector => "Your New Connector"
+ /* Add cases for other connectors */
+ };
+
+ let getConnectorNameTypeFromString = (str: string) =>
+ switch str {
+ | "Stripe" => Stripe
+ | "Dummy Connector" => DummyConnector
+ | "Your New Connector" => YourNewConnector
+ /* Add cases for other connectors */
+ };
+
+ let getConnectorInfo = (connectorName: connectorName) =>
+ switch connectorName {
+ | Stripe => "Stripe connector description."
+ | DummyConnector => "Dummy Connector description."
+ | YourNewConnector => "Your New Connector description."
+ /* Add descriptions for other connectors */
+ };
+
+ let getDisplayNameForConnectors = (connectorName: connectorName) =>
+ switch connectorName {
+ | Stripe => "Stripe"
+ | DummyConnector => "Dummy Connector"
+ | YourNewConnector => "Your New Connector"
+ /* Add display names for other connectors */
+ };
+ ```
+
+ Adjust the strings and descriptions according to your actual connector names and descriptions.
+
+
+4. Save the File:
+
+ Save the changes made to `ConnectorUtils.res`.
+
+Notes:
+
+- Ensure that you replace placeholders like `YourNewConnector` with the actual names of your connectors.
+- Verify that your connector enums and descriptions are correctly updated.
+- Save the files after making the changes.
+
+By following these steps, you should be able to update the `ConnectorTypes.res` and `ConnectorUtils.res` files with the new connector enum and its related information.
+
+
+
+Certainly! Below is a detailed documentation guide on how to add a new connector icon under the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project.
+
+Add Connector icon:
+
+1. Prepare the icon:
+
+ Prepare your connector icon in SVG format. Ensure that the icon is named in uppercase, following the convention. For example, name it `YOURCONNECTOR.SVG`.
+
+2. Open file explorer:
+
+ Open your file explorer and navigate to the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project.
+
+3. Add Icon file:
+
+ Copy and paste your SVG icon file (e.g., `YOURCONNECTOR.SVG`) into the `Gateway` folder.
+
+4. Verify file structure:
+
+ Ensure that the file structure in the `Gateway` folder follows the uppercase convention. For example:
+
+ ```
+ public
+ └── hyperswitch
+ └── Gateway
+ └── YOURCONNECTOR.SVG
+ ```
+ Save the changes made to the `Gateway` folder.
+
+
### **Test the connector**
The template code script generates a test file for the connector, containing 20 sanity tests. We anticipate that you will implement these tests when adding a new connector.
| 2024-02-13T08:03:22Z |
## Description
<!-- Describe your changes in detail -->
This PR adds documentation to add_connector.md explaining how to add connectors to the Control Center via Wasm configs.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 6e103cef50fea31d2508880985f80f0fd65cd536 |
Testing not required
| [
"add_connector.md"
] | |
juspay/hyperswitch | juspay__hyperswitch-3634 | Bug: [FIX] unmask last4 when metadata changed during /payments
When a metadata is changed during /payments and list customer payment method is called, last4 digits is getting masked. Unmask it and respond with raw string. | diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 9691ea962fa..7cff6263344 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -209,9 +209,7 @@ where
let updated_card = Some(CardDetailFromLocker {
scheme: None,
last4_digits: Some(
- card.card_number.to_string().split_off(
- card.card_number.to_string().len() - 4,
- ),
+ card.card_number.clone().get_last4(),
),
issuer_country: None,
card_number: Some(card.card_number),
| 2024-02-12T13:34:27Z |
## Description
<!-- Describe your changes in detail -->
When a metadata is changed during /payments and list customer payment method is called, last4 digits is getting masked. This PR unmasks it
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cc6759bd2d4207ad874a69546cb0a48db70b8629 |
1. Save a card in locker using /payments
2. Change the metadata of the saved card and try to save it again in locker using /payments
3. Now when list_customer_payment_method is called, the last4_digits field of the updated card has to be unmasked
| [
"crates/router/src/core/payments/tokenization.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3632 | Bug: Add checks in Prod Intent to not sent mail
| diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index 82f95564768..7318f9973f1 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -4,10 +4,10 @@ use diesel_models::{
};
use error_stack::ResultExt;
#[cfg(feature = "email")]
+use masking::ExposeInterface;
+#[cfg(feature = "email")]
use router_env::logger;
-#[cfg(feature = "email")]
-use crate::services::email::types as email_types;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::AppState,
@@ -15,6 +15,8 @@ use crate::{
types::domain::{user::dashboard_metadata as types, MerchantKeyStore},
utils::user::dashboard_metadata as utils,
};
+#[cfg(feature = "email")]
+use crate::{services::email::types as email_types, types::domain};
pub async fn set_metadata(
state: AppState,
@@ -446,8 +448,8 @@ async fn insert_metadata(
metadata = utils::update_user_scoped_metadata(
state,
user.user_id.clone(),
- user.merchant_id,
- user.org_id,
+ user.merchant_id.clone(),
+ user.org_id.clone(),
metadata_key,
data.clone(),
)
@@ -457,7 +459,13 @@ async fn insert_metadata(
#[cfg(feature = "email")]
{
- if utils::is_prod_email_required(&data) {
+ let user_data = user.get_user(state).await?;
+ let user_email = domain::UserEmail::from_pii_email(user_data.email.clone())
+ .change_context(UserErrors::InternalServerError)?
+ .get_secret()
+ .expose();
+
+ if utils::is_prod_email_required(&data, user_email) {
let email_contents = email_types::BizEmailProd::new(state, data)?;
let send_email_result = state
.email_client
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index ac3d918a34f..58841580244 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -279,9 +279,15 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay
})
}
-pub fn is_prod_email_required(data: &ProdIntent) -> bool {
- !(data
- .poc_email
+fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> bool {
+ value
.as_ref()
- .map_or(true, |mail| mail.contains("juspay")))
+ .map_or(false, |mail| !mail.contains(value_to_be_checked))
+}
+
+pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {
+ not_contains_string(&data.poc_email, "juspay")
+ && not_contains_string(&data.business_website, "juspay")
+ && not_contains_string(&data.business_website, "hyperswitch")
+ && not_contains_string(&Some(user_email), "juspay")
}
| 2024-02-12T12:47:26Z |
## Description
Added some checks so unnecessary biz emails won't be sent.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 8853a60bf4e2ed2490c60df9eaac2a8e46552b96 | When we hit this URL the email is sent to biz@hyperswitch.io so to restrict the unnecessary test mails added some checks.
```
curl --location 'http://localhost:8080/user/data' \
--header 'api-key: hyperswitch' \
--header 'Content-Type: text/plain' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"ProdIntent": {
"poc_email": "---",
"is_completed": true,
"legal_business_name": "---",
"business_location": "AX",
"business_website": "---",
"poc_name": "---",
"comments": "---"
}
}'
```
| [
"crates/router/src/core/user/dashboard_metadata.rs",
"crates/router/src/utils/user/dashboard_metadata.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3721 | Bug: [Refactor]: Make use of Locker for generating/storing fingerprints
# Description
Previously we were generating the fingerprints on our application end itself after this change we will have the fingerprints generated by our locker.
Fingerprint is generated for each and every card payment. Moreover we are storing fingerprint in all the attempt tables.
Now vouching for the scenarios were there are more than one attempt associated with one intent in that case we are adding the successful attempt's fingerprint in intent.
So how does the whole flow works:
1. Before confirmation of payment the payment instrument's fingerprint is cross-checked with the blocklist.
2. If it is present in blocklist the payment will be blocked (status as false).
3. This payment can be retried with another instrument and in case if succeeds the fingerprint will be added in intent.
**Note**: All successful attempts will have a fingerprint but intent's fingerprint will always be the successful attempt's fingerprint.
Other checkpoints under same hood:-
- [x] Instead of generating the fingerprint in application add support for `/cards/fingerprint` API call with `hash_key` (Also ensure to whitelist this endpoint in proxy).
- [x] Storing the fingerprint in payment attempt and payment intent table.
- [x] Refactoring Block List checking using the fingerprint API
# Testing
### Generating fingerprints
-> Toggle the blocklist guard from merchant account being used using `/blocklist/toggle?status=true`. More about
toggling guard [here](https://github.com/juspay/hyperswitch/issues/3467).
-> We need to create a payment.
-> While trying to confirm the payment it will have the `fingerprint_id` in the response. This can be used to block the
instrument. If the payment was able to be captured the fingerprint will be stored in the intent table as well
### Blocking fingerprints
Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin.
[blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip)
```
For Card Bin and Extended Card Bin :-
1. Setup a Merchant Account and any Connector account
2. Make a payment with a certain card (ensure it succeeds)
3. Block the card's card bin or extended card bin
4. Try the payment again (should fail this time with an API response saying that the payment was blocked)
For Payment Instrument :-
1. Repeat steps 1 and 2 of previous section
2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card.
3. Try the payment again (should fail)
```
# Curls for testing out the complete flow
### Toggle Blocklist Guard for merchant
```
Req
curl --location --request POST 'https://sandbox.hyperswitch.io/blocklist/toggle?status=true' \
--header 'api-key: snd_key'
Response
{
"blocklist_guard_status": "enabled"
}
```
### Blocklisting fingerprint for merchant
```
Req
curl --location 'https://sandbox.hyperswitch.io/blocklist' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--header 'api-key:snd_key' \
--data '{
"type": "fingerprint",
"data": "**fingerprint got in intent**"
}
'
Response
{
"fingerprint_id": "**fingerprint got in intent**",
"data_kind": "payment_method",
"created_at": "2024-02-21T07:47:01.939Z"
}
```
### Listing Blocked fingerprints of merchant
```
Req
curl --location 'https://sandbox.hyperswitch.io/blocklist?data_kind=payment_method' \
--header 'x-feature: router-custom' \
--header 'api-key: snd_key'
'
Response
[
{
"fingerprint_id": "**fingerprint got in intent**",
"data_kind": "payment_method",
"created_at": "2024-02-21T07:47:01.939Z"
}
]
```
### Unblocking Blocked fingerprints for merchant
```
Req
curl --location --request DELETE 'https://sandbox.hyperswitch.io/blocklist' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--header 'api-key: snd_key' \
--data '{
"type": "fingerprint",
"data": "**fingerprint got in list blocklist**"
}'
Response
[
{
"fingerprint_id": "**fingerprint got in list blocklist**",
"data_kind": "payment_method",
"created_at": "2024-02-21T07:47:01.939Z"
}
]
```
| diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs
index 9672b6de6ee..2afeb2db4f6 100644
--- a/crates/api_models/src/blocklist.rs
+++ b/crates/api_models/src/blocklist.rs
@@ -1,5 +1,6 @@
use common_enums::enums;
use common_utils::events::ApiEventMetric;
+use masking::StrongSecret;
use utoipa::ToSchema;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -10,6 +11,15 @@ pub enum BlocklistRequest {
ExtendedCardBin(String),
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct GenerateFingerprintRequest {
+ pub card: Card,
+ pub hash_key: StrongSecret<String>,
+}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub struct Card {
+ pub card_number: StrongSecret<String>,
+}
pub type AddToBlocklistRequest = BlocklistRequest;
pub type DeleteFromBlocklistRequest = BlocklistRequest;
@@ -22,6 +32,11 @@ pub struct BlocklistResponse {
pub created_at: time::PrimitiveDateTime,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct GenerateFingerprintResponsePayload {
+ pub card_fingerprint: String,
+}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleBlocklistResponse {
pub blocklist_guard_status: String,
@@ -54,4 +69,7 @@ impl ApiEventMetric for BlocklistRequest {}
impl ApiEventMetric for BlocklistResponse {}
impl ApiEventMetric for ToggleBlocklistResponse {}
impl ApiEventMetric for ListBlocklistQuery {}
+impl ApiEventMetric for GenerateFingerprintRequest {}
impl ApiEventMetric for ToggleBlocklistQuery {}
+impl ApiEventMetric for GenerateFingerprintResponsePayload {}
+impl ApiEventMetric for Card {}
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 084b0ef251e..3e187e25bc5 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -160,6 +160,7 @@ pub struct PaymentAttempt {
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub mandate_data: Option<MandateDetails>,
+ pub fingerprint_id: Option<String>,
}
impl PaymentAttempt {
@@ -238,6 +239,7 @@ pub struct PaymentAttemptNew {
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub mandate_data: Option<MandateDetails>,
+ pub fingerprint_id: Option<String>,
}
impl PaymentAttemptNew {
@@ -270,6 +272,7 @@ pub enum PaymentAttemptUpdate {
capture_method: Option<storage_enums::CaptureMethod>,
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
+ fingerprint_id: Option<String>,
updated_by: String,
},
UpdateTrackers {
@@ -307,6 +310,7 @@ pub enum PaymentAttemptUpdate {
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
merchant_connector_id: Option<String>,
+ fingerprint_id: Option<String>,
},
RejectUpdate {
status: storage_enums::AttemptStatus,
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 7470b5f8502..b2fafeb92a0 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -121,6 +121,7 @@ pub enum PaymentIntentUpdate {
amount_captured: Option<i64>,
return_url: Option<String>,
updated_by: String,
+ fingerprint_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
},
MetadataUpdate {
@@ -335,6 +336,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
// currency,
status,
amount_captured,
+ fingerprint_id,
// customer_id,
return_url,
updated_by,
@@ -344,6 +346,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
// currency: Some(currency),
status: Some(status),
amount_captured,
+ fingerprint_id,
// customer_id,
return_url,
modified_at: Some(common_utils::date_time::now()),
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 9af4595c9f4..927a05bfa56 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -65,6 +65,7 @@ pub struct PaymentAttempt {
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
pub mandate_data: Option<storage_enums::MandateDetails>,
+ pub fingerprint_id: Option<String>,
}
impl PaymentAttempt {
@@ -140,6 +141,7 @@ pub struct PaymentAttemptNew {
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
pub mandate_data: Option<storage_enums::MandateDetails>,
+ pub fingerprint_id: Option<String>,
}
impl PaymentAttemptNew {
@@ -177,6 +179,7 @@ pub enum PaymentAttemptUpdate {
capture_method: Option<storage_enums::CaptureMethod>,
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
+ fingerprint_id: Option<String>,
updated_by: String,
},
UpdateTrackers {
@@ -212,6 +215,7 @@ pub enum PaymentAttemptUpdate {
amount_capturable: Option<i64>,
surcharge_amount: Option<i64>,
tax_amount: Option<i64>,
+ fingerprint_id: Option<String>,
updated_by: String,
merchant_connector_id: Option<String>,
},
@@ -351,6 +355,7 @@ pub struct PaymentAttemptUpdateInternal {
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
+ fingerprint_id: Option<String>,
}
impl PaymentAttemptUpdateInternal {
@@ -411,6 +416,7 @@ impl PaymentAttemptUpdate {
encoded_data,
unified_code,
unified_message,
+ fingerprint_id,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -452,6 +458,7 @@ impl PaymentAttemptUpdate {
encoded_data: encoded_data.or(source.encoded_data),
unified_code: unified_code.unwrap_or(source.unified_code),
unified_message: unified_message.unwrap_or(source.unified_message),
+ fingerprint_id: fingerprint_id.or(source.fingerprint_id),
..source
}
}
@@ -476,6 +483,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
} => Self {
amount: Some(amount),
@@ -494,6 +502,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
..Default::default()
},
@@ -527,6 +536,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
merchant_connector_id,
surcharge_amount,
tax_amount,
+ fingerprint_id,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -549,6 +559,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
merchant_connector_id: merchant_connector_id.map(Some),
surcharge_amount,
tax_amount,
+ fingerprint_id,
..Default::default()
},
PaymentAttemptUpdate::VoidUpdate {
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 31bc0c06c51..69fb61a8d42 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -116,6 +116,7 @@ pub enum PaymentIntentUpdate {
ResponseUpdate {
status: storage_enums::IntentStatus,
amount_captured: Option<i64>,
+ fingerprint_id: Option<String>,
return_url: Option<String>,
updated_by: String,
incremental_authorization_allowed: Option<bool>,
@@ -405,6 +406,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
// currency,
status,
amount_captured,
+ fingerprint_id,
// customer_id,
return_url,
updated_by,
@@ -414,6 +416,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
// currency: Some(currency),
status: Some(status),
amount_captured,
+ fingerprint_id,
// customer_id,
return_url,
modified_at: Some(common_utils::date_time::now()),
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 2cbcb52fb44..5093f0df7d0 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -689,6 +689,8 @@ diesel::table! {
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
mandate_data -> Nullable<Jsonb>,
+ #[max_length = 64]
+ fingerprint_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 6a6d4c52c97..beac5b0733e 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -68,6 +68,7 @@ pub struct PaymentAttemptBatchNew {
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
pub mandate_data: Option<MandateDetails>,
+ pub fingerprint_id: Option<String>,
}
#[allow(dead_code)]
@@ -122,6 +123,7 @@ impl PaymentAttemptBatchNew {
unified_message: self.unified_message,
net_amount: self.net_amount,
mandate_data: self.mandate_data,
+ fingerprint_id: self.fingerprint_id,
}
}
}
diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs
index 2cb5f86a264..f4122a6a651 100644
--- a/crates/router/src/core/blocklist/transformers.rs
+++ b/crates/router/src/core/blocklist/transformers.rs
@@ -1,6 +1,28 @@
-use api_models::blocklist;
+use api_models::{blocklist, enums as api_enums};
+use common_utils::{
+ ext_traits::{Encode, StringExt},
+ request::RequestContent,
+};
+use error_stack::ResultExt;
+use josekit::jwe;
+#[cfg(feature = "aws_kms")]
+use masking::PeekInterface;
+use masking::StrongSecret;
+use router_env::{instrument, tracing};
-use crate::types::{storage, transformers::ForeignFrom};
+use crate::{
+ configs::settings,
+ core::{
+ errors::{self, CustomResult},
+ payment_methods::transformers as payment_methods,
+ },
+ headers, routes,
+ services::{api as services, encryption},
+ types::{storage, transformers::ForeignFrom},
+ utils::ConnectorResponseExt,
+};
+
+const LOCKER_FINGERPRINT_PATH: &str = "/cards/fingerprint";
impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {
fn foreign_from(from: storage::Blocklist) -> Self {
@@ -11,3 +33,192 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {
}
}
}
+
+async fn generate_fingerprint_request<'a>(
+ #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ locker: &settings::Locker,
+ payload: &blocklist::GenerateFingerprintRequest,
+ locker_choice: api_enums::LockerChoice,
+) -> CustomResult<services::Request, errors::VaultError> {
+ let payload = payload
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)?;
+
+ #[cfg(feature = "aws_kms")]
+ let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
+
+ #[cfg(not(feature = "aws_kms"))]
+ let private_key = jwekey.vault_private_key.as_bytes();
+
+ let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
+ .await
+ .change_context(errors::VaultError::RequestEncodingFailed)?;
+
+ let jwe_payload = generate_jwe_payload_for_request(jwekey, &jws, locker_choice).await?;
+ let mut url = match locker_choice {
+ api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
+ };
+ url.push_str(LOCKER_FINGERPRINT_PATH);
+ let mut request = services::Request::new(services::Method::Post, &url);
+ request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.set_body(RequestContent::Json(Box::new(jwe_payload)));
+ Ok(request)
+}
+
+async fn generate_jwe_payload_for_request(
+ #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ jws: &str,
+ locker_choice: api_enums::LockerChoice,
+) -> CustomResult<encryption::JweBody, errors::VaultError> {
+ let jws_payload: Vec<&str> = jws.split('.').collect();
+
+ let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
+ Some(encryption::JwsBody {
+ header: payload.first()?.to_string(),
+ payload: payload.get(1)?.to_string(),
+ signature: payload.get(2)?.to_string(),
+ })
+ };
+
+ let jws_body =
+ generate_jws_body(jws_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?;
+
+ let payload = jws_body
+ .encode_to_vec()
+ .change_context(errors::VaultError::GenerateFingerprintFailed)?;
+
+ #[cfg(feature = "aws_kms")]
+ let public_key = match locker_choice {
+ api_enums::LockerChoice::HyperswitchCardVault => {
+ jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ }
+ };
+
+ #[cfg(not(feature = "aws_kms"))]
+ let public_key = match locker_choice {
+ api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
+ };
+
+ let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key)
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Error on jwe encrypt")?;
+ let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
+
+ let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
+ Some(encryption::JweBody {
+ header: payload.first()?.to_string(),
+ iv: payload.get(2)?.to_string(),
+ encrypted_payload: payload.get(3)?.to_string(),
+ tag: payload.get(4)?.to_string(),
+ encrypted_key: payload.get(1)?.to_string(),
+ })
+ };
+
+ let jwe_body =
+ generate_jwe_body(jwe_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?;
+
+ Ok(jwe_body)
+}
+
+#[instrument(skip_all)]
+pub async fn generate_fingerprint(
+ state: &routes::AppState,
+ card_number: StrongSecret<String>,
+ hash_key: StrongSecret<String>,
+ locker_choice: api_enums::LockerChoice,
+) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> {
+ let payload = blocklist::GenerateFingerprintRequest {
+ card: blocklist::Card { card_number },
+ hash_key,
+ };
+
+ let generate_fingerprint_resp =
+ call_to_locker_for_fingerprint(state, &payload, locker_choice).await?;
+
+ Ok(generate_fingerprint_resp)
+}
+
+#[instrument(skip_all)]
+async fn call_to_locker_for_fingerprint(
+ state: &routes::AppState,
+ payload: &blocklist::GenerateFingerprintRequest,
+ locker_choice: api_enums::LockerChoice,
+) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> {
+ let locker = &state.conf.locker;
+ #[cfg(not(feature = "aws_kms"))]
+ let jwekey = &state.conf.jwekey;
+ #[cfg(feature = "aws_kms")]
+ let jwekey = &state.kms_secrets;
+
+ let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?;
+ let response = services::call_connector_api(state, request)
+ .await
+ .change_context(errors::VaultError::GenerateFingerprintFailed);
+ let jwe_body: encryption::JweBody = response
+ .get_response_inner("JweBody")
+ .change_context(errors::VaultError::GenerateFingerprintFailed)?;
+
+ let decrypted_payload =
+ decrypt_generate_fingerprint_response_payload(jwekey, jwe_body, Some(locker_choice))
+ .await
+ .change_context(errors::VaultError::GenerateFingerprintFailed)
+ .attach_printable("Error getting decrypted fingerprint response payload")?;
+ let generate_fingerprint_response: blocklist::GenerateFingerprintResponsePayload =
+ decrypted_payload
+ .parse_struct("GenerateFingerprintResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)?;
+
+ Ok(generate_fingerprint_response)
+}
+
+async fn decrypt_generate_fingerprint_response_payload(
+ #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey,
+ #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets,
+ jwe_body: encryption::JweBody,
+ locker_choice: Option<api_enums::LockerChoice>,
+) -> CustomResult<String, errors::VaultError> {
+ let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
+
+ #[cfg(feature = "aws_kms")]
+ let public_key = match target_locker {
+ api_enums::LockerChoice::HyperswitchCardVault => {
+ jwekey.jwekey.peek().vault_encryption_key.as_bytes()
+ }
+ };
+
+ #[cfg(feature = "aws_kms")]
+ let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes();
+
+ #[cfg(not(feature = "aws_kms"))]
+ let public_key = match target_locker {
+ api_enums::LockerChoice::HyperswitchCardVault => jwekey.vault_encryption_key.as_bytes(),
+ };
+
+ #[cfg(not(feature = "aws_kms"))]
+ let private_key = jwekey.vault_private_key.as_bytes();
+
+ let jwt = payment_methods::get_dotted_jwe(jwe_body);
+ let alg = jwe::RSA_OAEP;
+
+ let jwe_decrypted = encryption::decrypt_jwe(
+ &jwt,
+ encryption::KeyIdCheck::SkipKeyIdCheck,
+ private_key,
+ alg,
+ )
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jwe Decryption failed for JweBody for vault")?;
+
+ let jws = jwe_decrypted
+ .parse_struct("JwsBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)?;
+ let jws_body = payment_methods::get_dotted_jws(jws);
+
+ encryption::verify_sign(jws_body, public_key)
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jws Decryption failed for JwsBody for vault")
+}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 733b565beed..68cdb2690b7 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -1,15 +1,11 @@
use api_models::blocklist as api_blocklist;
use common_enums::MerchantDecision;
-use common_utils::{
- crypto::{self, SignMessage},
- errors::CustomResult,
-};
+use common_utils::errors::CustomResult;
use diesel_models::configs;
use error_stack::{IntoReport, ResultExt};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
+use masking::StrongSecret;
-use super::{errors, AppState};
+use super::{errors, transformers::generate_fingerprint, AppState};
use crate::{
consts,
core::{
@@ -35,52 +31,13 @@ pub async fn delete_entry_from_blocklist(
delete_card_bin_blocklist_entry(state, &xbin, &merchant_id).await?
}
- api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => {
- let blocklist_fingerprint = state
- .store
- .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
- &merchant_id,
- &fingerprint_id,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
- message: "blocklist record with given fingerprint id not found".to_string(),
- })?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(blocklist_fingerprint.encrypted_fingerprint)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to kms decrypt fingerprint")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint;
-
- let blocklist_entry = state
- .store
- .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
- message: "no blocklist record for the given fingerprint id was found"
- .to_string(),
- })?;
-
- state
- .store
- .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
- &merchant_id,
- &decrypted_fingerprint,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
- message: "no blocklist record for the given fingerprint id was found"
- .to_string(),
- })?;
-
- blocklist_entry
- }
+ api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state
+ .store
+ .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "no blocklist record for the given fingerprint id was found".to_string(),
+ })?,
};
Ok(blocklist_entry.foreign_into())
@@ -232,57 +189,20 @@ pub async fn insert_entry_into_blocklist(
}
}
- let blocklist_fingerprint = state
- .store
- .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
- &merchant_id,
- fingerprint_id,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
- message: "fingerprint not found".to_string(),
- })?;
-
- #[cfg(feature = "aws_kms")]
- let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms)
- .await
- .decrypt(blocklist_fingerprint.encrypted_fingerprint)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to kms decrypt encrypted fingerprint")?;
-
- #[cfg(not(feature = "aws_kms"))]
- let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint;
-
- state
- .store
- .insert_blocklist_lookup_entry(
- diesel_models::blocklist_lookup::BlocklistLookupNew {
- merchant_id: merchant_id.clone(),
- fingerprint: decrypted_fingerprint,
- },
- )
- .await
- .to_duplicate_response(errors::ApiErrorResponse::PreconditionFailed {
- message: "the payment instrument associated with the given fingerprint is already in the blocklist".to_string(),
- })
- .attach_printable("failed to add fingerprint to blocklist lookup")?;
-
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
merchant_id: merchant_id.clone(),
fingerprint_id: fingerprint_id.clone(),
- data_kind: blocklist_fingerprint.data_kind,
+ data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod,
metadata: None,
created_at: common_utils::date_time::now(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to add fingerprint to pm blocklist")?
+ .attach_printable("failed to add fingerprint to blocklist")?
}
};
-
Ok(blocklist_entry.foreign_into())
}
@@ -330,17 +250,6 @@ async fn duplicate_check_insert_bin(
merchant_id: &str,
data_kind: common_enums::BlocklistDataKind,
) -> RouterResult<storage::Blocklist> {
- let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
- let bin_fingerprint = crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_secret.clone().as_bytes(),
- bin.as_bytes(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error in bin hash creation")?;
-
- let encoded_fingerprint = hex::encode(bin_fingerprint.clone());
-
let blocklist_entry_result = state
.store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
@@ -363,17 +272,6 @@ async fn duplicate_check_insert_bin(
}
}
- // Checking for duplicacy
- state
- .store
- .insert_blocklist_lookup_entry(diesel_models::blocklist_lookup::BlocklistLookupNew {
- merchant_id: merchant_id.to_string(),
- fingerprint: encoded_fingerprint.clone(),
- })
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error inserting blocklist lookup entry")?;
-
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
@@ -393,21 +291,6 @@ async fn delete_card_bin_blocklist_entry(
bin: &str,
merchant_id: &str,
) -> RouterResult<storage::Blocklist> {
- let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
- let bin_fingerprint = crypto::HmacSha512
- .sign_message(merchant_secret.as_bytes(), bin.as_bytes())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error when hashing card bin")?;
- let encoded_fingerprint = hex::encode(bin_fingerprint);
-
- state
- .store
- .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, &encoded_fingerprint)
- .await
- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
- message: "could not find a blocklist entry for the given bin".to_string(),
- })?;
-
state
.store
.delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
@@ -431,28 +314,28 @@ where
get_merchant_fingerprint_secret(state, merchant_id.as_str()).await?;
// Hashed Fingerprint to check whether or not this payment should be blocked.
- let card_number_fingerprint = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_card_no().as_bytes(),
- )
- .attach_printable("error in pm fingerprint creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
- }
- _ => None,
- })
- .map(hex::encode);
+ let card_number_fingerprint = if let Some(api_models::payments::PaymentMethodData::Card(card)) =
+ payment_data.payment_method_data.as_ref()
+ {
+ generate_fingerprint(
+ state,
+ StrongSecret::new(card.card_number.clone().get_card_no()),
+ StrongSecret::new(merchant_fingerprint_secret.clone()),
+ api_models::enums::LockerChoice::HyperswitchCardVault,
+ )
+ .await
+ .attach_printable("error in pm fingerprint creation")
+ .map_or_else(
+ |err| {
+ logger::error!(error=?err);
+ None
+ },
+ Some,
+ )
+ .map(|payload| payload.card_fingerprint)
+ } else {
+ None
+ };
// Hashed Cardbin to check whether or not this payment should be blocked.
let card_bin_fingerprint = payment_data
@@ -460,66 +343,43 @@ where
.as_ref()
.and_then(|pm_data| match pm_data {
api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_card_isin().as_bytes(),
- )
- .attach_printable("error in card bin hash creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
+ Some(card.card_number.clone().get_card_isin())
}
_ => None,
- })
- .map(hex::encode);
+ });
// Hashed Extended Cardbin to check whether or not this payment should be blocked.
- let extended_card_bin_fingerprint = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_extended_card_bin().as_bytes(),
- )
- .attach_printable("error in extended card bin hash creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
- }
- _ => None,
- })
- .map(hex::encode);
+ let extended_card_bin_fingerprint =
+ payment_data
+ .payment_method_data
+ .as_ref()
+ .and_then(|pm_data| match pm_data {
+ api_models::payments::PaymentMethodData::Card(card) => {
+ Some(card.card_number.clone().get_extended_card_bin())
+ }
+ _ => None,
+ });
//validating the payment method.
let mut blocklist_futures = Vec::new();
if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
+ blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
card_number_fingerprint,
));
}
if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
- merchant_id,
- card_bin_fingerprint,
- ));
+ blocklist_futures.push(
+ db.find_blocklist_entry_by_merchant_id_fingerprint_id(
+ merchant_id,
+ card_bin_fingerprint,
+ ),
+ );
}
if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
+ blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
extended_card_bin_fingerprint,
));
@@ -538,7 +398,6 @@ where
}
}
}
-
if should_payment_be_blocked {
// Update db for attempt and intent status.
db.update_payment_intent(
@@ -582,13 +441,12 @@ where
}
.into())
} else {
- payment_data.payment_intent.fingerprint_id = generate_payment_fingerprint(
+ payment_data.payment_attempt.fingerprint_id = generate_payment_fingerprint(
state,
payment_data.payment_attempt.merchant_id.clone(),
payment_data.payment_method_data.clone(),
)
.await?;
-
Ok(false)
}
}
@@ -598,68 +456,31 @@ pub async fn generate_payment_fingerprint(
merchant_id: String,
payment_method_data: Option<crate::types::api::PaymentMethodData>,
) -> CustomResult<Option<String>, errors::ApiErrorResponse> {
- let db = &state.store;
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?;
- let card_number_fingerprint = payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_card_no().as_bytes(),
- )
- .attach_printable("error in pm fingerprint creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
- }
- _ => None,
- })
- .map(hex::encode);
- let mut fingerprint_id = None;
- if let Some(encoded_hash) = card_number_fingerprint {
- #[cfg(feature = "kms")]
- let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms)
- .await
- .encrypt(encoded_hash)
+ Ok(
+ if let Some(api_models::payments::PaymentMethodData::Card(card)) =
+ payment_method_data.as_ref()
+ {
+ generate_fingerprint(
+ state,
+ StrongSecret::new(card.card_number.clone().get_card_no()),
+ StrongSecret::new(merchant_fingerprint_secret),
+ api_models::enums::LockerChoice::HyperswitchCardVault,
+ )
.await
+ .attach_printable("error in pm fingerprint creation")
.map_or_else(
- |e| {
- logger::error!(error=?e, "failed kms encryption of card fingerprint");
+ |err| {
+ logger::error!(error=?err);
None
},
Some,
- );
-
- #[cfg(not(feature = "kms"))]
- let encrypted_fingerprint = Some(encoded_hash);
-
- if let Some(encrypted_fingerprint) = encrypted_fingerprint {
- fingerprint_id = db
- .insert_blocklist_fingerprint_entry(
- diesel_models::blocklist_fingerprint::BlocklistFingerprintNew {
- merchant_id,
- fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"),
- encrypted_fingerprint,
- data_kind: common_enums::BlocklistDataKind::PaymentMethod,
- created_at: common_utils::date_time::now(),
- },
- )
- .await
- .map_or_else(
- |e| {
- logger::error!(error=?e, "failed storing card fingerprint in db");
- None
- },
- |fp| Some(fp.fingerprint_id),
- );
- }
- }
- Ok(fingerprint_id)
+ )
+ .map(|payload| payload.card_fingerprint)
+ } else {
+ logger::error!("failed to retrieve card fingerprint");
+ None
+ },
+ )
}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d1814f7ee82..cec563b9631 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -236,6 +236,8 @@ pub enum VaultError {
FetchPaymentMethodFailed,
#[error("Failed to save payment method in vault")]
SavePaymentMethodFailed,
+ #[error("Failed to generate fingerprint")]
+ GenerateFingerprintFailed,
}
#[derive(Debug, thiserror::Error)]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 635ba917168..764752ba903 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3202,6 +3202,7 @@ impl AttemptType {
unified_message: None,
net_amount: old_payment_attempt.amount,
mandate_data: old_payment_attempt.mandate_data,
+ fingerprint_id: None,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 734839c9b6d..2d2ee0e8728 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -739,6 +739,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let m_straight_through_algorithm = straight_through_algorithm.clone();
let m_error_code = error_code.clone();
let m_error_message = error_message.clone();
+ let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();
let m_db = state.clone().store;
let surcharge_amount = payment_data
.surcharge_details
@@ -774,6 +775,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
merchant_connector_id,
surcharge_amount,
tax_amount,
+ fingerprint_id: m_fingerprint_id,
},
storage_scheme,
)
@@ -784,7 +786,6 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
);
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
- let m_fingerprint_id = payment_data.payment_intent.fingerprint_id.clone();
let m_customer_id = customer_id.clone();
let m_shipping_address_id = shipping_address.clone();
let m_billing_address_id = billing_address.clone();
@@ -821,7 +822,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
- fingerprint_id: m_fingerprint_id,
+ fingerprint_id: None,
session_expiry,
},
storage_scheme,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6bd6ca91100..099eae71800 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -604,6 +604,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
if router_data.status == enums::AttemptStatus::Charged {
+ payment_data.payment_intent.fingerprint_id =
+ payment_data.payment_attempt.fingerprint_id.clone();
metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
}
@@ -798,6 +800,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
return_url: router_data.return_url.clone(),
amount_captured,
updated_by: storage_scheme.to_string(),
+ fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),
incremental_authorization_allowed: payment_data
.payment_intent
.incremental_authorization_allowed,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 0ec11e39f62..071d919eb19 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -559,6 +559,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id: None,
updated_by: storage_scheme.to_string(),
},
storage_scheme,
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index f4d74c4f81b..a2cf65ce66b 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -114,6 +114,7 @@ pub fn proxy_bypass_urls(locker: &Locker) -> Vec<String> {
let locker_host_rs = locker.host_rs.to_owned();
vec![
format!("{locker_host}/cards/add"),
+ format!("{locker_host}/cards/fingerprint"),
format!("{locker_host}/cards/retrieve"),
format!("{locker_host}/cards/delete"),
format!("{locker_host_rs}/cards/add"),
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index e60e32227d3..5add5036f08 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -148,6 +148,7 @@ impl PaymentAttemptInterface for MockDb {
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
mandate_data: payment_attempt.mandate_data,
+ fingerprint_id: payment_attempt.fingerprint_id,
};
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 ec19e30c0ec..a51f95e1e74 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -391,6 +391,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
unified_code: payment_attempt.unified_code.clone(),
unified_message: payment_attempt.unified_message.clone(),
mandate_data: payment_attempt.mandate_data.clone(),
+ fingerprint_id: payment_attempt.fingerprint_id.clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -1105,6 +1106,7 @@ impl DataModelExt for PaymentAttempt {
unified_code: self.unified_code,
unified_message: self.unified_message,
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
+ fingerprint_id: self.fingerprint_id,
}
}
@@ -1163,6 +1165,7 @@ impl DataModelExt for PaymentAttempt {
mandate_data: storage_model
.mandate_data
.map(MandateDetails::from_storage_model),
+ fingerprint_id: storage_model.fingerprint_id,
}
}
}
@@ -1219,6 +1222,7 @@ impl DataModelExt for PaymentAttemptNew {
unified_code: self.unified_code,
unified_message: self.unified_message,
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
+ fingerprint_id: self.fingerprint_id,
}
}
@@ -1275,6 +1279,7 @@ impl DataModelExt for PaymentAttemptNew {
mandate_data: storage_model
.mandate_data
.map(MandateDetails::from_storage_model),
+ fingerprint_id: storage_model.fingerprint_id,
}
}
}
@@ -1299,6 +1304,7 @@ impl DataModelExt for PaymentAttemptUpdate {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
} => DieselPaymentAttemptUpdate::Update {
amount,
@@ -1315,6 +1321,7 @@ impl DataModelExt for PaymentAttemptUpdate {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
},
Self::UpdateTrackers {
@@ -1373,6 +1380,7 @@ impl DataModelExt for PaymentAttemptUpdate {
amount_capturable,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
} => DieselPaymentAttemptUpdate::ConfirmUpdate {
@@ -1394,6 +1402,7 @@ impl DataModelExt for PaymentAttemptUpdate {
amount_capturable,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
},
@@ -1578,6 +1587,7 @@ impl DataModelExt for PaymentAttemptUpdate {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
} => Self::Update {
amount,
@@ -1594,6 +1604,7 @@ impl DataModelExt for PaymentAttemptUpdate {
capture_method,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
},
DieselPaymentAttemptUpdate::UpdateTrackers {
@@ -1641,6 +1652,7 @@ impl DataModelExt for PaymentAttemptUpdate {
amount_capturable,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
} => Self::ConfirmUpdate {
@@ -1662,6 +1674,7 @@ impl DataModelExt for PaymentAttemptUpdate {
amount_capturable,
surcharge_amount,
tax_amount,
+ fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
},
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 7efbafb662d..d201d2a053a 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -925,12 +925,14 @@ impl DataModelExt for PaymentIntentUpdate {
Self::ResponseUpdate {
status,
amount_captured,
+ fingerprint_id,
return_url,
updated_by,
incremental_authorization_allowed,
} => DieselPaymentIntentUpdate::ResponseUpdate {
status,
amount_captured,
+ fingerprint_id,
return_url,
updated_by,
incremental_authorization_allowed,
diff --git a/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql
new file mode 100644
index 00000000000..c6647bd3ab0
--- /dev/null
+++ b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS fingerprint_id;
diff --git a/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql
new file mode 100644
index 00000000000..8d219935234
--- /dev/null
+++ b/migrations/2024-02-12-135546_add_fingerprint_id_in_payment_attempt/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64);
| 2024-02-12T11:07:58Z |
## Description
<!-- Describe your changes in detail -->
After this change we will store the fingerprints on our locker in fingerprints table. No more storing anything related to fingerprints in our DB. There will be only one table usable left for blocklsit which will be `blocklist` (stores all the fingerprints blocked by a merchant with their type and metadata).
Previously we were generating the fingerprints on our application end itself after this change we will have the fingerprints generated by our locker.
Fingerprint is generated for each and every card payment. Moreover we are storing fingerprint in all the attempt tables.
Now vouching for the scenarios were there are more than one attempt associated with one intent in that case we are adding the successful attempt's fingerprint in intent.
## Required DB changes
purpose: support for addition of fingerprint_id in payment_attempt table
Query:
`ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64);`
So how does the whole flow works:
1. Before confirmation of payment the payment instrument's fingerprint is cross-checked with the blocklist.
2. If it is present in blocklist the payment will be blocked (status as false).
3. This payment can be retried with another instrument and in case if succeeds the fingerprint will be added in intent.
**Note**: All successful attempts will have a fingerprint but intent's fingerprint will always be the successful attempt's fingerprint.
### Other checkpoints under same hood
- [x] Instead of generating the fingerprint in application add support for `/cards/fingerprint` API call with `hash_key`.
- [x] whitelisting mentioned endpoint in proxy.
- [x] Storing the fingerprint in payment attempt and payment intent table.
- [x] Refactoring Block List checking using the fingerprint API.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
#
### Blocking fingerprints
Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin.
[blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip)
```
For Card Bin and Extended Card Bin :-
1. Setup a Merchant Account and any Connector account
2. Make a payment with a certain card (ensure it succeeds)
3. Block the card's card bin or extended card bin
4. Try the payment again (should fail this time with an API response saying that the payment was blocked)
For Payment Instrument :-
1. Repeat steps 1 and 2 of previous section
2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card.
3. Try the payment again (should fail)
```
The respected curls are mentioned in the issue. | e5e44857d21af9db8dee580e276028de76c7d278 | ### Generating fingerprints
-> Toggle the blocklist guard from merchant account being used using `/blocklist/toggle?status=true`. More about
toggling guard [here](https://github.com/juspay/hyperswitch/issues/3467).
-> We need to create a payment.
-> While trying to confirm the payment it will have the `fingerprint_id` in the response. This can be used to block the
instrument. If the payment was able to be captured the fingerprint will be stored in the intent table as well
### Blocking fingerprints
Refer to the attached postman collection for the API contracts for the blocklist APIs([Description](https://github.com/juspay/hyperswitch/issues/3439)). Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin.
[blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip)
```
For Card Bin and Extended Card Bin :-
1. Setup a Merchant Account and any Connector account
2. Make a payment with a certain card (ensure it succeeds)
3. Block the card's card bin or extended card bin
4. Try the payment again (should fail this time with an API response saying that the payment was blocked)
For Payment Instrument :-
1. Repeat steps 1 and 2 of previous section
2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card.
3. Try the payment again (should fail)
```
The respected curls are mentioned in the issue.
| [
"crates/api_models/src/blocklist.rs",
"crates/data_models/src/payments/payment_attempt.rs",
"crates/data_models/src/payments/payment_intent.rs",
"crates/diesel_models/src/payment_attempt.rs",
"crates/diesel_models/src/payment_intent.rs",
"crates/diesel_models/src/schema.rs",
"crates/diesel_models/src/us... | |
juspay/hyperswitch | juspay__hyperswitch-3628 | Bug: [REFACTOR] Incorporate `hyperswitch_interface` into drainer
Refactor drainer to incorporate the newly added crate `hyperswitch_interface` for secrets decryption | diff --git a/Cargo.lock b/Cargo.lock
index 4bee1804f4c..dcde5456d7d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2342,6 +2342,7 @@ dependencies = [
"diesel_models",
"error-stack",
"external_services",
+ "hyperswitch_interfaces",
"masking",
"mime",
"once_cell",
diff --git a/config/deployments/drainer.toml b/config/deployments/drainer.toml
index 42c89cbfd58..f8bf2826768 100644
--- a/config/deployments/drainer.toml
+++ b/config/deployments/drainer.toml
@@ -5,7 +5,17 @@ num_partitions = 64
shutdown_interval = 1000
stream_name = "drainer_stream"
-[kms]
+[secrets_management]
+secrets_manager = "aws_kms"
+
+[secrets_management.aws_kms]
+key_id = "kms_key_id"
+region = "kms_region"
+
+[encryption_management]
+encryption_manager = "aws_kms"
+
+[encryption_management.aws_kms]
key_id = "kms_key_id"
region = "kms_region"
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index a8972e279a6..f45c1979827 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -35,6 +35,7 @@ async-trait = "0.1.74"
common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
external_services = { version = "0.1.0", path = "../external_services" }
+hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }
masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs
index e01b72150c5..c539e9a734c 100644
--- a/crates/drainer/src/connection.rs
+++ b/crates/drainer/src/connection.rs
@@ -1,23 +1,13 @@
use bb8::PooledConnection;
use diesel::PgConnection;
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt};
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::{
- core::{HashiCorpVault, Kv2},
- decrypt::VaultFetch,
-};
-#[cfg(not(feature = "aws_kms"))]
use masking::PeekInterface;
-use crate::settings::Database;
+use crate::{settings::Database, Settings};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
#[allow(clippy::expect_used)]
-pub async fn redis_connection(
- conf: &crate::settings::Settings,
-) -> redis_interface::RedisConnectionPool {
+pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
@@ -28,31 +18,14 @@ pub async fn redis_connection(
///
/// Will panic if could not create a db pool
#[allow(clippy::expect_used)]
-pub async fn diesel_make_pg_pool(
- database: &Database,
- _test_transaction: bool,
- #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::core::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static HashiCorpVault,
-) -> PgPool {
- let password = database.password.clone();
- #[cfg(feature = "hashicorp-vault")]
- let password = password
- .fetch_inner::<Kv2>(hashicorp_client)
- .await
- .expect("Failed while fetching db password");
-
- #[cfg(feature = "aws_kms")]
- let password = password
- .decrypt_inner(aws_kms_client)
- .await
- .expect("Failed to decrypt password");
-
- #[cfg(not(feature = "aws_kms"))]
- let password = &password.peek();
-
+pub async fn diesel_make_pg_pool(database: &Database, _test_transaction: bool) -> PgPool {
let database_url = format!(
"postgres://{}:{}@{}:{}/{}",
- database.username, password, database.host, database.port, database.dbname
+ database.username,
+ database.password.peek(),
+ database.host,
+ database.port,
+ database.dbname
);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let pool = bb8::Pool::builder()
diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs
index 33b4a1395a8..443cb5b6f3f 100644
--- a/crates/drainer/src/health_check.rs
+++ b/crates/drainer/src/health_check.rs
@@ -11,7 +11,7 @@ use crate::{
connection::{pg_connection, redis_connection},
errors::HealthCheckError,
services::{self, Store},
- settings::Settings,
+ Settings,
};
pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0";
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index 909ae065e26..0ed6183faef 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -11,19 +11,20 @@ mod stream;
mod types;
mod utils;
use std::sync::Arc;
+mod secrets_transformers;
use actix_web::dev::Server;
use common_utils::signals::get_allowed_signals;
use diesel_models::kv;
use error_stack::{IntoReport, ResultExt};
+use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use router_env::{instrument, tracing};
use tokio::sync::mpsc;
+pub(crate) type Settings = crate::settings::Settings<RawSecret>;
+
use crate::{
- connection::pg_connection,
- services::Store,
- settings::{DrainerSettings, Settings},
- types::StreamData,
+ connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData,
};
pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::DrainerResult<()> {
diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs
index 943a66f6791..377fdcd1569 100644
--- a/crates/drainer/src/main.rs
+++ b/crates/drainer/src/main.rs
@@ -15,7 +15,9 @@ async fn main() -> DrainerResult<()> {
conf.validate()
.expect("Failed to validate drainer configuration");
- let store = services::Store::new(&conf, false).await;
+ let state = settings::AppState::new(conf.clone()).await;
+
+ let store = services::Store::new(&state.conf, false).await;
let store = std::sync::Arc::new(store);
#[cfg(feature = "vergen")]
@@ -28,7 +30,7 @@ async fn main() -> DrainerResult<()> {
);
#[allow(clippy::expect_used)]
- let web_server = Box::pin(start_web_server(conf.clone(), store.clone()))
+ let web_server = Box::pin(start_web_server(state.conf.as_ref().clone(), store.clone()))
.await
.expect("Failed to create the server");
diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rs
new file mode 100644
index 00000000000..c0447725a79
--- /dev/null
+++ b/crates/drainer/src/secrets_transformers.rs
@@ -0,0 +1,50 @@
+use common_utils::errors::CustomResult;
+use hyperswitch_interfaces::secrets_interface::{
+ secret_handler::SecretsHandler,
+ secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
+ SecretManagementInterface, SecretsManagementError,
+};
+
+use crate::settings::{Database, Settings};
+
+#[async_trait::async_trait]
+impl SecretsHandler for Database {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: Box<dyn SecretManagementInterface>,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let secured_db_config = value.get_inner();
+ let raw_db_password = secret_management_client
+ .get_secret(secured_db_config.password.clone())
+ .await?;
+
+ Ok(value.transition_state(|db| Self {
+ password: raw_db_password,
+ ..db
+ }))
+ }
+}
+
+/// # Panics
+///
+/// Will panic even if fetching raw secret fails for at least one config value
+#[allow(clippy::unwrap_used)]
+pub async fn fetch_raw_secrets(
+ conf: Settings<SecuredSecret>,
+ secret_management_client: Box<dyn SecretManagementInterface>,
+) -> Settings<RawSecret> {
+ #[allow(clippy::expect_used)]
+ let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client)
+ .await
+ .expect("Failed to decrypt database password");
+
+ Settings {
+ server: conf.server,
+ master_database: database,
+ redis: conf.redis,
+ log: conf.log,
+ drainer: conf.drainer,
+ encryption_management: conf.encryption_management,
+ secrets_management: conf.secrets_management,
+ }
+}
diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs
index 3918c756c10..9e0165548a0 100644
--- a/crates/drainer/src/services.rs
+++ b/crates/drainer/src/services.rs
@@ -28,20 +28,10 @@ impl Store {
/// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration.
/// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client.
///
- pub async fn new(config: &crate::settings::Settings, test_transaction: bool) -> Self {
+ pub async fn new(config: &crate::Settings, test_transaction: bool) -> Self {
Self {
- master_pool: diesel_make_pg_pool(
- &config.master_database,
- test_transaction,
- #[cfg(feature = "aws_kms")]
- external_services::aws_kms::core::get_aws_kms_client(&config.kms).await,
- #[cfg(feature = "hashicorp-vault")]
- #[allow(clippy::expect_used)]
- external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
- .await
- .expect("Failed while getting hashicorp client"),
- )
- .await,
+ master_pool: diesel_make_pg_pool(config.master_database.get_inner(), test_transaction)
+ .await,
redis_conn: Arc::new(crate::connection::redis_connection(config).await),
config: StoreConfig {
drainer_stream_name: config.drainer.stream_name.clone(),
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index de5af654540..ec24c472af2 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -1,22 +1,23 @@
-use std::path::PathBuf;
+use std::{path::PathBuf, sync::Arc};
use common_utils::ext_traits::ConfigExt;
use config::{Environment, File};
-#[cfg(feature = "aws_kms")]
-use external_services::aws_kms;
-#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault;
+use external_services::managers::{
+ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig,
+};
+use hyperswitch_interfaces::{
+ encryption_interface::EncryptionManagementInterface,
+ secrets_interface::secret_state::{
+ RawSecret, SecretState, SecretStateContainer, SecuredSecret,
+ },
+};
+use masking::Secret;
use redis_interface as redis;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use router_env::{env, logger};
use serde::Deserialize;
-use crate::errors;
-
-#[cfg(feature = "aws_kms")]
-pub type Password = aws_kms::core::AwsKmsValue;
-#[cfg(not(feature = "aws_kms"))]
-pub type Password = masking::Secret<String>;
+use crate::{errors, secrets_transformers};
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
@@ -27,25 +28,58 @@ pub struct CmdLineConf {
pub config_path: Option<PathBuf>,
}
+#[derive(Clone)]
+pub struct AppState {
+ pub conf: Arc<Settings<RawSecret>>,
+ pub encryption_client: Box<dyn EncryptionManagementInterface>,
+}
+
+impl AppState {
+ /// # Panics
+ ///
+ /// Panics if secret or encryption management client cannot be initiated
+ pub async fn new(conf: Settings<SecuredSecret>) -> Self {
+ #[allow(clippy::expect_used)]
+ let secret_management_client = conf
+ .secrets_management
+ .get_secret_management_client()
+ .await
+ .expect("Failed to create secret management client");
+
+ let raw_conf =
+ secrets_transformers::fetch_raw_secrets(conf, secret_management_client).await;
+
+ #[allow(clippy::expect_used)]
+ let encryption_client = raw_conf
+ .encryption_management
+ .get_encryption_management_client()
+ .await
+ .expect("Failed to create encryption management client");
+
+ Self {
+ conf: Arc::new(raw_conf),
+ encryption_client,
+ }
+ }
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
-pub struct Settings {
+pub struct Settings<S: SecretState> {
pub server: Server,
- pub master_database: Database,
+ pub master_database: SecretStateContainer<Database, S>,
pub redis: redis::RedisSettings,
pub log: Log,
pub drainer: DrainerSettings,
- #[cfg(feature = "aws_kms")]
- pub kms: aws_kms::core::AwsKmsConfig,
- #[cfg(feature = "hashicorp-vault")]
- pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
+ pub encryption_management: EncryptionManagementConfig,
+ pub secrets_management: SecretsManagementConfig,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Database {
pub username: String,
- pub password: Password,
+ pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
@@ -85,7 +119,7 @@ impl Default for Database {
fn default() -> Self {
Self {
username: String::new(),
- password: Password::default(),
+ password: String::new().into(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
@@ -157,7 +191,7 @@ impl DrainerSettings {
}
}
-impl Settings {
+impl Settings<SecuredSecret> {
pub fn new() -> Result<Self, errors::DrainerError> {
Self::with_config_path(None)
}
@@ -199,12 +233,25 @@ impl Settings {
pub fn validate(&self) -> Result<(), errors::DrainerError> {
self.server.validate()?;
- self.master_database.validate()?;
+ self.master_database.get_inner().validate()?;
self.redis.validate().map_err(|error| {
println!("{error}");
errors::DrainerError::ConfigParsingError("invalid Redis configuration".into())
})?;
self.drainer.validate()?;
+ self.secrets_management.validate().map_err(|error| {
+ println!("{error}");
+ errors::DrainerError::ConfigParsingError(
+ "invalid secrets management configuration".into(),
+ )
+ })?;
+
+ self.encryption_management.validate().map_err(|error| {
+ println!("{error}");
+ errors::DrainerError::ConfigParsingError(
+ "invalid encryption management configuration".into(),
+ )
+ })?;
Ok(())
}
diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
index 6d3f75500af..d1da6a8c8b6 100644
--- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
+++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
@@ -8,12 +8,12 @@ use serde::{Deserialize, Deserializer};
pub trait SecretState {}
/// Decrypted state
-#[derive(Debug, Clone, Deserialize)]
-pub enum RawSecret {}
+#[derive(Debug, Clone, Deserialize, Default)]
+pub struct RawSecret {}
/// Encrypted state
-#[derive(Debug, Clone, Deserialize)]
-pub enum SecuredSecret {}
+#[derive(Debug, Clone, Deserialize, Default)]
+pub struct SecuredSecret {}
impl SecretState for RawSecret {}
impl SecretState for SecuredSecret {}
| 2024-02-12T10:38:57Z |
## Description
<!-- Describe your changes in detail -->
Added `AppState` in drainer which now contains `encryption_client` for runtime encryption and decryption of values. This PR also incorporates the newly added `hyperswitch_interface` crate for decrypting the secrets during application startup.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 5fb3c001b5dc371f81fe1708fd9a6c6978fb726e |
This PR refactors the way decryption of secrets work in drainer. So this cannot be tested
| [
"Cargo.lock",
"config/deployments/drainer.toml",
"crates/drainer/Cargo.toml",
"crates/drainer/src/connection.rs",
"crates/drainer/src/health_check.rs",
"crates/drainer/src/lib.rs",
"crates/drainer/src/main.rs",
"crates/drainer/src/secrets_transformers.rs",
"crates/drainer/src/services.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-3627 | Bug: [BUG] Wrong email content in invite users
| diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 389979d5723..598a2620937 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -275,7 +275,7 @@ impl EmailData for InviteUser {
let invite_user_link =
get_link_with_token(&self.settings.email.base_url, token, "set_password");
- let body = html::get_html_body(EmailBody::MagicLink {
+ let body = html::get_html_body(EmailBody::InviteUser {
link: invite_user_link,
user_name: self.user_name.clone().get_secret().expose(),
});
| 2024-02-12T08:44:37Z |
## Description
Invite users email content was of `magic link`. This PR changed it to `invite users`
## Motivation and Context
Right content in email body of invite users
# | 4ae28e48cd73a9f96b6ae24babf167824fd182a0 | With local SES.
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"email": "new_unregistered_email",
"name": "username",
"role_id": "any role"
}'
```
| [
"crates/router/src/services/email/types.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3618 | Bug: [BUG] unmask last4 digits of card when listing payment methods for customer
When metadata of a saved card is updated and customer payment methods are listed, the updated card's last 4 digit is getting masked in the response. Instead unmask it and return the raw digits. | diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 152232d2dec..4f6d6b4c62b 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -248,11 +248,7 @@ pub async fn add_payment_method(
Ok(pm) => {
let updated_card = Some(api::CardDetailFromLocker {
scheme: None,
- last4_digits: Some(
- card.card_number
- .to_string()
- .split_off(card.card_number.to_string().len() - 4),
- ),
+ last4_digits: Some(card.card_number.clone().get_last4()),
issuer_country: None,
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
| 2024-02-10T16:51:23Z |
## Description
<!-- Describe your changes in detail -->
When metadata of a saved card is updated and customer payment methods are listed, the updated card's last 4 digit is getting masked in the response. This PR unmasks it and returns the raw digits.
Bug: `last4_digits` is masked -

Fix: unmasked -

## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | b9c29e7fd3bdc5e582a2dddbb98f3d2dbda72dd6 |
1. Save a card in locker
2. Change the metadata of the saved card and try to save it again in locker
3. Now when `list_customer_payment_method` is called, the `last4_digits` field of the updated card has to be unmasked
| [
"crates/router/src/core/payment_methods/cards.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3616 | Bug: [DOCS] Update Rustman documentation
The current documentation misses some key points that WILL result in people not being able to run the collections and ask for help.
We would want to update it so that it look cleaner with `Notes` that are highlighted thereby making it more readable and clearer. | diff --git a/crates/test_utils/README.md b/crates/test_utils/README.md
index a82c74cb59f..3c50499adc0 100644
--- a/crates/test_utils/README.md
+++ b/crates/test_utils/README.md
@@ -2,7 +2,8 @@
The heart of `newman`(with directory support) and `UI-tests`
-> If you're developing a collection and you want to learn more about it, click [_**here**_](/README.md)
+> [!NOTE]
+> If you're developing a collection and you want to learn more about it, click [_**here**_](/postman/README.md)
## Newman
@@ -14,10 +15,14 @@ The heart of `newman`(with directory support) and `UI-tests`
- Add the connector credentials to the `connector_auth.toml` / `auth.toml` by creating a copy of the `sample_auth.toml` from `router/tests/connectors/sample_auth.toml`
- Export the auth file path as an environment variable:
+
```shell
export CONNECTOR_AUTH_FILE_PATH=/path/to/auth.toml
```
+> [!IMPORTANT]
+> You might also need to export the `GATEWAY_MERCHANT_ID`, `GPAY_CERTIFICATE` and `GPAY_CERTIFICATE_KEYS` as environment variables for certain collections with necessary values. Make sure you do that before running the tests
+
### Supported Commands
Required fields:
@@ -40,18 +45,21 @@ Optional fields:
- Example: `--header "key1:value1" --header "key2:value2"`
- `--verbose` -- A boolean to print detailed logs (requests and responses)
-**Note:** Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository.
+> [!Note]
+> Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository.
### Running tests
- Tests can be run with the following command:
+
```shell
cargo run --package test_utils --bin test_utils -- --connector-name=<connector_name> --base-url=<base_url> --admin-api-key=<admin_api_key> \
# optionally
--folder "<folder_name_1>,<folder_name_2>,...<folder_name_n>" --verbose
```
-**Note**: You can omit `--package test_utils` at the time of running the above command since it is optional.
+> [!Note]
+> You can omit `--package test_utils` at the time of running the above command since it is optional.
## UI tests
diff --git a/postman/README.md b/postman/README.md
index 342e7ebe1bd..c3d3c63e459 100644
--- a/postman/README.md
+++ b/postman/README.md
@@ -26,10 +26,11 @@ This directory contains the Postman collection for all Hyperswitch supported con
- Make sure that you update the `tests` section where the necessary `javascript` code has to written/updated to test the feature (assertion checks where you verify the results obtained with the expected outcome)
- If certain `tests` need to be run at the time of making a request, make sure you add them to the `Pre-request Script` section of the request
+- Make sure that the request body does not contain any comments else the `newman dir-export` command will fail which is used to export the collection to its directory structure
---
- After all the development is done, make sure you right click and run the collection in respective environments to make sure that the collection runs successfully
-- Export the collection as `v2.1` and save it `postman/collection-json` directory
-- Export the postman-collection to its directory structure by using the command `newman dir-export /path/to/collection.json` and move the folder to `postman/collection-dir` (for more info, refer to [Newman-Fork](https://github.com/juspay/hyperswitch/tree/main/crates/test_utils#newman))
-- You can run the dir postman collection from newman using `rustman` by referring [here](https://github.com/juspay/hyperswitch/tree/main/crates/test_utils#running-tests)
\ No newline at end of file
+- Export the collection as `v2.1` and save it `postman/collection-json` directory with file name following the format `<connector_name>.postman_collection.json`
+- Export the postman-collection to its directory structure by using the command `newman dir-export /path/to/collection.json` and move the folder to `postman/collection-dir` (for more info, refer to [Newman-Fork](/crates/test_utils/README.md#newman)) with the folder renamed with name of the connector
+- You can run the postman collection from directory structure by referring [here](/crates/test_utils/README.md#running-tests)
| 2024-02-09T18:43:21Z |
## Description
<!-- Describe your changes in detail -->
This PR updates the `Rustman` documentation easing the collection development process along with the things to look for before running the collection.
Closes #3616
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 documentation misses some key points which is why some of the developers and contributors are finding it difficult to test their work.
# | b9c29e7fd3bdc5e582a2dddbb98f3d2dbda72dd6 |
Below 2 files look cleaner and clearer:
- https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/crates/test_utils/README.md
- https://github.com/juspay/hyperswitch/blob/af7e39e57fd079bad60d8afed97c74fe633e4645/postman/README.md
| [
"crates/test_utils/README.md",
"postman/README.md"
] | |
juspay/hyperswitch | juspay__hyperswitch-3607 | Bug: [FEATURE] Add new column in PaymentAttempt for storing mandate_data
### Feature Description
Add new column in PaymentAttempt for storing mandate_data to be future compatible
### Possible Implementation
Add a column mandate_data which would be a struct , in order to store the mandate details for a mandate in Payment Attempt table
### 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/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs
index 319a78cf661..b4478f84ee9 100644
--- a/crates/data_models/src/mandates.rs
+++ b/crates/data_models/src/mandates.rs
@@ -13,7 +13,6 @@ use time::PrimitiveDateTime;
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
- pub mandate_type: Option<MandateDataType>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
@@ -23,13 +22,6 @@ pub enum MandateDataType {
MultiUse(Option<MandateAmountData>),
}
-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-#[serde(untagged)]
-pub enum MandateTypeDetails {
- MandateType(MandateDataType),
- MandateDetails(MandateDetails),
-}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: i64,
diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs
index 2b5705c155b..084b0ef251e 100644
--- a/crates/data_models/src/payments/payment_attempt.rs
+++ b/crates/data_models/src/payments/payment_attempt.rs
@@ -4,7 +4,11 @@ use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use super::PaymentIntent;
-use crate::{errors, mandates::MandateTypeDetails, ForeignIDRef};
+use crate::{
+ errors,
+ mandates::{MandateDataType, MandateDetails},
+ ForeignIDRef,
+};
#[async_trait::async_trait]
pub trait PaymentAttemptInterface {
@@ -143,7 +147,7 @@ pub struct PaymentAttempt {
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
- pub mandate_details: Option<MandateTypeDetails>,
+ pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
@@ -155,6 +159,7 @@ pub struct PaymentAttempt {
pub merchant_connector_id: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
+ pub mandate_data: Option<MandateDetails>,
}
impl PaymentAttempt {
@@ -221,7 +226,7 @@ pub struct PaymentAttemptNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<MandateTypeDetails>,
+ pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
@@ -232,6 +237,7 @@ pub struct PaymentAttemptNew {
pub merchant_connector_id: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
+ pub mandate_data: Option<MandateDetails>,
}
impl PaymentAttemptNew {
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index babffdbc4a8..d65f6c5efa9 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -174,20 +174,8 @@ use diesel::{
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
- pub mandate_type: Option<MandateDataType>,
}
-
-#[derive(
- serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
-)]
-#[diesel(sql_type = Jsonb)]
-#[serde(rename_all = "snake_case")]
-pub enum MandateDataType {
- SingleUse(MandateAmountData),
- MultiUse(Option<MandateAmountData>),
-}
-
-impl<DB: Backend> FromSql<Jsonb, DB> for MandateDataType
+impl<DB: Backend> FromSql<Jsonb, DB> for MandateDetails
where
serde_json::Value: FromSql<Jsonb, DB>,
{
@@ -197,7 +185,7 @@ where
}
}
-impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType
+impl ToSql<Jsonb, diesel::pg::Pg> for MandateDetails
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
@@ -210,19 +198,17 @@ where
<serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
-
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression,
)]
#[diesel(sql_type = Jsonb)]
-#[serde(untagged)]
#[serde(rename_all = "snake_case")]
-pub enum MandateTypeDetails {
- MandateType(MandateDataType),
- MandateDetails(MandateDetails),
+pub enum MandateDataType {
+ SingleUse(MandateAmountData),
+ MultiUse(Option<MandateAmountData>),
}
-impl<DB: Backend> FromSql<Jsonb, DB> for MandateTypeDetails
+impl<DB: Backend> FromSql<Jsonb, DB> for MandateDataType
where
serde_json::Value: FromSql<Jsonb, DB>,
{
@@ -231,7 +217,8 @@ where
Ok(serde_json::from_value(value)?)
}
}
-impl ToSql<Jsonb, diesel::pg::Pg> for MandateTypeDetails
+
+impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index d286cc312bc..9af4595c9f4 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -51,7 +51,7 @@ pub struct PaymentAttempt {
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
- pub mandate_details: Option<storage_enums::MandateTypeDetails>,
+ pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
@@ -64,6 +64,7 @@ pub struct PaymentAttempt {
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
+ pub mandate_data: Option<storage_enums::MandateDetails>,
}
impl PaymentAttempt {
@@ -126,7 +127,7 @@ pub struct PaymentAttemptNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<storage_enums::MandateTypeDetails>,
+ pub mandate_details: Option<storage_enums::MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
@@ -138,6 +139,7 @@ pub struct PaymentAttemptNew {
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
+ pub mandate_data: Option<storage_enums::MandateDetails>,
}
impl PaymentAttemptNew {
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index c9887e1770f..6c28677432b 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -688,6 +688,7 @@ diesel::table! {
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
+ mandate_data -> Nullable<Jsonb>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 5a2226f0676..6a6d4c52c97 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -5,7 +5,11 @@ use common_enums::{
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
-use crate::{enums::MandateTypeDetails, schema::payment_attempt, PaymentAttemptNew};
+use crate::{
+ enums::{MandateDataType, MandateDetails},
+ schema::payment_attempt,
+ PaymentAttemptNew,
+};
#[derive(
Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
@@ -50,7 +54,7 @@ pub struct PaymentAttemptBatchNew {
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
- pub mandate_details: Option<MandateTypeDetails>,
+ pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub connector_transaction_id: Option<String>,
@@ -63,6 +67,7 @@ pub struct PaymentAttemptBatchNew {
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<i64>,
+ pub mandate_data: Option<MandateDetails>,
}
#[allow(dead_code)]
@@ -116,6 +121,7 @@ impl PaymentAttemptBatchNew {
unified_code: self.unified_code,
unified_message: self.unified_message,
net_amount: self.net_amount,
+ mandate_data: self.mandate_data,
}
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 7b505e7c01c..5d287a89f62 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1837,17 +1837,8 @@ pub async fn list_payment_methods(
merchant_name: merchant_account.merchant_name,
payment_type,
payment_methods: payment_method_responses,
- mandate_payment: payment_attempt
- .and_then(|inner| inner.mandate_details)
- .and_then(|man_type_details| match man_type_details {
- data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => {
- Some(mandate_type)
- }
- data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => {
- mandate_details.mandate_type
- }
- })
- .map(|d| match d {
+ mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
+ |d| match d {
data_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::MandateAmountData {
amount: i.amount,
@@ -1869,7 +1860,8 @@ pub async fn list_payment_methods(
data_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
- }),
+ },
+ ),
show_surcharge_breakup_screen: merchant_surcharge_configs
.show_surcharge_breakup_screen
.unwrap_or_default(),
@@ -2079,28 +2071,20 @@ pub async fn filter_payment_methods(
})?;
let filter7 = payment_attempt
.and_then(|attempt| attempt.mandate_details.as_ref())
- .map(|mandate_details| {
- let (mandate_type_present, update_mandate_id_present) =
- match mandate_details {
- data_models::mandates::MandateTypeDetails::MandateType(_) => {
- (true, false)
- }
- data_models::mandates::MandateTypeDetails::MandateDetails(
- mand_details,
- ) => (
- mand_details.mandate_type.is_some(),
- mand_details.update_mandate_id.is_some(),
- ),
- };
-
- if mandate_type_present {
- filter_pm_based_on_supported_payments_for_mandate(
- supported_payment_methods_for_mandate,
- &payment_method,
- &payment_method_object.payment_method_type,
- connector_variant,
- )
- } else if update_mandate_id_present {
+ .map(|_mandate_details| {
+ filter_pm_based_on_supported_payments_for_mandate(
+ supported_payment_methods_for_mandate,
+ &payment_method,
+ &payment_method_object.payment_method_type,
+ connector_variant,
+ )
+ })
+ .unwrap_or(true);
+
+ let filter8 = payment_attempt
+ .and_then(|attempt| attempt.mandate_data.as_ref())
+ .map(|mandate_detail| {
+ if mandate_detail.update_mandate_id.is_some() {
filter_pm_based_on_update_mandate_support_for_connector(
supported_payment_methods_for_update_mandate,
&payment_method,
@@ -2121,7 +2105,15 @@ pub async fn filter_payment_methods(
payment_method,
);
- if filter && filter2 && filter3 && filter4 && filter5 && filter6 && filter7 {
+ if filter
+ && filter2
+ && filter3
+ && filter4
+ && filter5
+ && filter6
+ && filter7
+ && filter8
+ {
resp.push(response_pm_type);
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 7ec1f5e9213..c6ba4a4e987 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3201,6 +3201,7 @@ impl AttemptType {
unified_code: None,
unified_message: None,
net_amount: old_payment_attempt.amount,
+ mandate_data: old_payment_attempt.mandate_data,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 54ec47ecea5..8349f050135 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -441,28 +441,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
// The operation merges mandate data from both request and payment_attempt
setup_mandate = setup_mandate.map(|mut sm| {
- sm.mandate_type = payment_attempt
- .mandate_details
- .clone()
- .and_then(|mandate| match mandate {
- data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => {
- Some(mandate_type)
- }
- data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => {
- mandate_details.mandate_type
- }
- })
- .or(sm.mandate_type);
+ sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
sm.update_mandate_id = payment_attempt
- .mandate_details
+ .mandate_data
.clone()
- .and_then(|mandate| match mandate {
- data_models::mandates::MandateTypeDetails::MandateType(_) => None,
- data_models::mandates::MandateTypeDetails::MandateDetails(update_id) => {
- Some(update_id.update_mandate_id)
- }
- })
- .flatten()
+ .and_then(|mandate| mandate.update_mandate_id)
.or(sm.update_mandate_id);
sm
});
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 8d37fc486c5..0f581be3089 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -4,7 +4,7 @@ use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use data_models::{
- mandates::{MandateData, MandateDetails, MandateTypeDetails},
+ mandates::{MandateData, MandateDetails},
payments::payment_attempt::PaymentAttempt,
};
use diesel_models::ephemeral_key;
@@ -733,27 +733,17 @@ impl PaymentCreate {
Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
}
- let mandate_details = if request.mandate_data.is_none() {
- None
- } else if let Some(update_id) = request
+ let mandate_data = if let Some(update_id) = request
.mandate_data
.as_ref()
.and_then(|inner| inner.update_mandate_id.clone())
{
- let mandate_data = MandateDetails {
+ let mandate_details = MandateDetails {
update_mandate_id: Some(update_id),
- mandate_type: None,
};
- Some(MandateTypeDetails::MandateDetails(mandate_data))
+ Some(mandate_details)
} else {
- let mandate_data = MandateDetails {
- update_mandate_id: None,
- mandate_type: request
- .mandate_data
- .as_ref()
- .and_then(|inner| inner.mandate_type.clone().map(Into::into)),
- };
- Some(MandateTypeDetails::MandateDetails(mandate_data))
+ None
};
Ok((
@@ -782,7 +772,11 @@ impl PaymentCreate {
business_sub_label: request.business_sub_label.clone(),
surcharge_amount,
tax_amount,
- mandate_details,
+ mandate_details: request
+ .mandate_data
+ .as_ref()
+ .and_then(|inner| inner.mandate_type.clone().map(Into::into)),
+ mandate_data,
..storage::PaymentAttemptNew::default()
},
additional_pm_data,
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 24863ddc568..e60e32227d3 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -147,6 +147,7 @@ impl PaymentAttemptInterface for MockDb {
merchant_connector_id: payment_attempt.merchant_connector_id,
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
+ mandate_data: payment_attempt.mandate_data,
};
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 6af136c1062..ec19e30c0ec 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -2,7 +2,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMet
use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found};
use data_models::{
errors,
- mandates::{MandateAmountData, MandateDataType, MandateDetails, MandateTypeDetails},
+ mandates::{MandateAmountData, MandateDataType, MandateDetails},
payments::{
payment_attempt::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate,
@@ -14,8 +14,7 @@ use data_models::{
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
- MandateDetails as DieselMandateDetails, MandateTypeDetails as DieselMandateTypeOrDetails,
- MerchantStorageScheme,
+ MandateDetails as DieselMandateDetails, MerchantStorageScheme,
},
kv,
payment_attempt::{
@@ -391,6 +390,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
unified_code: payment_attempt.unified_code.clone(),
unified_message: payment_attempt.unified_message.clone(),
+ mandate_data: payment_attempt.mandate_data.clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -1016,42 +1016,11 @@ impl DataModelExt for MandateDetails {
fn to_storage_model(self) -> Self::StorageModel {
DieselMandateDetails {
update_mandate_id: self.update_mandate_id,
- mandate_type: self
- .mandate_type
- .map(|mand_type| mand_type.to_storage_model()),
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
update_mandate_id: storage_model.update_mandate_id,
- mandate_type: storage_model
- .mandate_type
- .map(MandateDataType::from_storage_model),
- }
- }
-}
-impl DataModelExt for MandateTypeDetails {
- type StorageModel = DieselMandateTypeOrDetails;
-
- fn to_storage_model(self) -> Self::StorageModel {
- match self {
- Self::MandateType(mandate_type) => {
- DieselMandateTypeOrDetails::MandateType(mandate_type.to_storage_model())
- }
- Self::MandateDetails(mandate_details) => {
- DieselMandateTypeOrDetails::MandateDetails(mandate_details.to_storage_model())
- }
- }
- }
-
- fn from_storage_model(storage_model: Self::StorageModel) -> Self {
- match storage_model {
- DieselMandateTypeOrDetails::MandateType(data) => {
- Self::MandateType(MandateDataType::from_storage_model(data))
- }
- DieselMandateTypeOrDetails::MandateDetails(data) => {
- Self::MandateDetails(MandateDetails::from_storage_model(data))
- }
}
}
}
@@ -1124,7 +1093,7 @@ impl DataModelExt for PaymentAttempt {
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
- mandate_details: self.mandate_details.map(|md| md.to_storage_model()),
+ mandate_details: self.mandate_details.map(|d| d.to_storage_model()),
error_reason: self.error_reason,
multiple_capture_count: self.multiple_capture_count,
connector_response_reference_id: self.connector_response_reference_id,
@@ -1135,6 +1104,7 @@ impl DataModelExt for PaymentAttempt {
merchant_connector_id: self.merchant_connector_id,
unified_code: self.unified_code,
unified_message: self.unified_message,
+ mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
}
}
@@ -1179,7 +1149,7 @@ impl DataModelExt for PaymentAttempt {
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
- .map(MandateTypeDetails::from_storage_model),
+ .map(MandateDataType::from_storage_model),
error_reason: storage_model.error_reason,
multiple_capture_count: storage_model.multiple_capture_count,
connector_response_reference_id: storage_model.connector_response_reference_id,
@@ -1190,6 +1160,9 @@ impl DataModelExt for PaymentAttempt {
merchant_connector_id: storage_model.merchant_connector_id,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
+ mandate_data: storage_model
+ .mandate_data
+ .map(MandateDetails::from_storage_model),
}
}
}
@@ -1245,6 +1218,7 @@ impl DataModelExt for PaymentAttemptNew {
merchant_connector_id: self.merchant_connector_id,
unified_code: self.unified_code,
unified_message: self.unified_message,
+ mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
}
}
@@ -1287,7 +1261,7 @@ impl DataModelExt for PaymentAttemptNew {
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model
.mandate_details
- .map(MandateTypeDetails::from_storage_model),
+ .map(MandateDataType::from_storage_model),
error_reason: storage_model.error_reason,
connector_response_reference_id: storage_model.connector_response_reference_id,
multiple_capture_count: storage_model.multiple_capture_count,
@@ -1298,6 +1272,9 @@ impl DataModelExt for PaymentAttemptNew {
merchant_connector_id: storage_model.merchant_connector_id,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
+ mandate_data: storage_model
+ .mandate_data
+ .map(MandateDetails::from_storage_model),
}
}
}
diff --git a/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql
new file mode 100644
index 00000000000..9d2071f8dda
--- /dev/null
+++ b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS mandate_data;
diff --git a/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql
new file mode 100644
index 00000000000..31ed6e88fea
--- /dev/null
+++ b/migrations/2024-02-08-142804_add_mandate_data_payment_attempt/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS mandate_data JSONB DEFAULT NULL;
\ No newline at end of file
| 2024-02-09T05:57:16Z |
## Description
To make the mandate_details forward compatible , instead of storing update mandate id in mandate details we store it in the new column mandate data. Currently in mandate_data column we only store update_mandate_id
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | e54b0dd20fabf48cc8f6ea59bb197f05b8b5adeb | - Create an MA and an MCA
- Make a mandate_payment
- And then make an update_mandate_payment with the mandate_id generated in the previous step
- The card would be updated and reflected when we do list mandate
<img width="1728" alt="Screenshot 2024-02-09 at 1 08 48 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/13fdc4ba-479f-4f9f-ad65-56c5c14d9dbf">

<img width="1728" alt="Screenshot 2024-02-09 at 1 12 35 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/74e4cb0f-aae3-451e-9b7a-647da8167c67">

| [
"crates/data_models/src/mandates.rs",
"crates/data_models/src/payments/payment_attempt.rs",
"crates/diesel_models/src/enums.rs",
"crates/diesel_models/src/payment_attempt.rs",
"crates/diesel_models/src/schema.rs",
"crates/diesel_models/src/user/sample_data.rs",
"crates/router/src/core/payment_methods/ca... | |
juspay/hyperswitch | juspay__hyperswitch-3604 | Bug: chore: address Rust 1.76 clippy lints
Address the clippy lints occurring due to new rust version 1.76
See #3391 for more information. | diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index d3ca0172f26..da14475f120 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -42,7 +42,7 @@ where
let start_instant = Instant::now();
logger::info!(tag = ?Tag::BeginRequest, payload = ?payload);
- let res = match metrics::request::record_request_time_metric(
+ let server_wrap_util_res = metrics::request::record_request_time_metric(
api::server_wrap_util(
&flow,
state.clone().into(),
@@ -58,7 +58,9 @@ where
.map(|response| {
logger::info!(api_response =? response);
response
- }) {
+ });
+
+ let res = match server_wrap_util_res {
Ok(api::ApplicationResponse::Json(response)) => {
let response = S::try_from(response);
match response {
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 689d1f9c789..99006752f57 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -656,7 +656,7 @@ impl AddressInterface for MockDb {
address_update: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
- match self
+ let updated_addr = self
.addresses
.lock()
.await
@@ -667,7 +667,8 @@ impl AddressInterface for MockDb {
AddressUpdateInternal::from(address_update).create_address(a.clone());
*a = address_updated.clone();
address_updated
- }) {
+ });
+ match updated_addr {
Some(address_updated) => address_updated
.convert(key_store.key.get_inner())
.await
@@ -687,7 +688,7 @@ impl AddressInterface for MockDb {
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Address, errors::StorageError> {
- match self
+ let updated_addr = self
.addresses
.lock()
.await
@@ -698,7 +699,8 @@ impl AddressInterface for MockDb {
AddressUpdateInternal::from(address_update).create_address(a.clone());
*a = address_updated.clone();
address_updated
- }) {
+ });
+ match updated_addr {
Some(address_updated) => address_updated
.convert(key_store.key.get_inner())
.await
@@ -757,7 +759,7 @@ impl AddressInterface for MockDb {
address_update: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
- match self
+ let updated_addr = self
.addresses
.lock()
.await
@@ -771,7 +773,8 @@ impl AddressInterface for MockDb {
AddressUpdateInternal::from(address_update).create_address(a.clone());
*a = address_updated.clone();
address_updated
- }) {
+ });
+ match updated_addr {
Some(address) => {
let address: domain::Address = address
.convert(key_store.key.get_inner())
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 3718b962b45..0dd20721c3a 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -691,7 +691,7 @@ impl MerchantConnectorAccountInterface for MockDb {
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
- match self
+ let mca_update_res = self
.merchant_connector_accounts
.lock()
.await
@@ -709,8 +709,9 @@ impl MerchantConnectorAccountInterface for MockDb {
.await
.change_context(errors::StorageError::DecryptionError)
})
- .await
- {
+ .await;
+
+ match mca_update_res {
Some(result) => result,
None => {
return Err(errors::StorageError::ValueNotFound(
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index dd7cbedd0f4..b109d1fe5bd 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -212,7 +212,7 @@ impl PaymentMethodInterface for MockDb {
payment_method: storage::PaymentMethod,
payment_method_update: storage::PaymentMethodUpdate,
) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
- match self
+ let pm_update_res = self
.payment_methods
.lock()
.await
@@ -224,7 +224,9 @@ impl PaymentMethodInterface for MockDb {
.create_payment_method(pm.clone());
*pm = payment_method_updated.clone();
payment_method_updated
- }) {
+ });
+
+ match pm_update_res {
Some(result) => Ok(result),
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method to update".to_string(),
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 5a6ff7e9b67..28405c001eb 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1083,7 +1083,7 @@ where
let start_instant = Instant::now();
logger::info!(tag = ?Tag::BeginRequest, payload = ?payload);
- let res = match metrics::request::record_request_time_metric(
+ let server_wrap_util_res = metrics::request::record_request_time_metric(
server_wrap_util(
&flow,
state.clone(),
@@ -1099,7 +1099,9 @@ where
.map(|response| {
logger::info!(api_response =? response);
response
- }) {
+ });
+
+ let res = match server_wrap_util_res {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 32fd97fca33..f6a340e9d59 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -109,7 +109,7 @@ where
{
Ok(x) => Ok(x),
Err(mut err) => {
- match state
+ let update_res = state
.process_tracker_update_process_status_by_ids(
pt_batch.trackers.iter().map(|process| process.id.clone()).collect(),
storage::ProcessTrackerUpdate::StatusUpdate {
@@ -123,12 +123,14 @@ where
}, |count| {
logger::debug!("Updated status of {count} processes");
Ok(())
- }) {
- Ok(_) => (),
- Err(inner_err) => {
- err.extend_one(inner_err);
- }
- };
+ });
+
+ match update_res {
+ Ok(_) => (),
+ Err(inner_err) => {
+ err.extend_one(inner_err);
+ }
+ };
Err(err)
}
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index a6e0268e2c2..961853548a2 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -56,7 +56,6 @@ where
// Open the file in write mode or create it if it doesn't exist
let mut file = std::fs::OpenOptions::new()
- .write(true)
.append(true)
.create(true)
.open(file_path)?;
| 2024-02-08T17:02:07Z |
## Description
<!-- Describe your changes in detail -->
This PR addresses the clippy lints occurring due to new rust version 1.76
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | dd5630f070db28051a3dd59a66f0a4ee6777e38f |
Rust updation clippy lints are addressed here. So basic sanity test should suffice
| [
"crates/router/src/compatibility/wrap.rs",
"crates/router/src/db/address.rs",
"crates/router/src/db/merchant_connector_account.rs",
"crates/router/src/db/payment_method.rs",
"crates/router/src/services/api.rs",
"crates/scheduler/src/utils.rs",
"crates/test_utils/src/newman_runner.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3595 | Bug: feat(user_role): Transfer ownership api
| diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 3ec30d6bd97..2b8d0221497 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,7 +2,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest,
- ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest,
+ ListRolesResponse, RoleInfoResponse, TransferOrgOwnershipRequest, UpdateUserRoleRequest,
};
common_utils::impl_misc_api_event_type!(
@@ -12,5 +12,6 @@ common_utils::impl_misc_api_event_type!(
AuthorizationInfoResponse,
UpdateUserRoleRequest,
AcceptInvitationRequest,
- DeleteUserRoleRequest
+ DeleteUserRoleRequest,
+ TransferOrgOwnershipRequest
);
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 2672293390e..78df1d6823e 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -108,3 +108,8 @@ pub type AcceptInvitationResponse = DashboardEntryResponse;
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TransferOrgOwnershipRequest {
+ pub email: pii::Email,
+}
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index e67eba64c7c..5e759cf826b 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -54,6 +54,20 @@ impl UserRole {
.await
}
+ pub async fn update_by_user_id_org_id(
+ conn: &PgPooledConn,
+ user_id: String,
+ org_id: String,
+ update: UserRoleUpdate,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::user_id.eq(user_id).and(dsl::org_id.eq(org_id)),
+ UserRoleUpdateInternal::from(update),
+ )
+ .await
+ }
+
pub async fn delete_by_user_id_merchant_id(
conn: &PgPooledConn,
user_id: String,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b48b39eea14..14be9bb6991 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -1,10 +1,11 @@
-use api_models::user_role as user_role_api;
+use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate};
use error_stack::ResultExt;
use masking::ExposeInterface;
use router_env::logger;
use crate::{
+ consts,
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::AppState,
services::{
@@ -135,6 +136,55 @@ pub async fn update_user_role(
Ok(ApplicationResponse::StatusOk)
}
+pub async fn transfer_org_ownership(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+ req: user_role_api::TransferOrgOwnershipRequest,
+) -> UserResponse<user_api::DashboardEntryResponse> {
+ if user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN {
+ return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!(
+ "role_id = {} is not org_admin",
+ user_from_token.role_id
+ ));
+ }
+
+ let user_to_be_updated =
+ utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?)
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)
+ .attach_printable("User not found in our records".to_string())?;
+
+ if user_from_token.user_id == user_to_be_updated.get_user_id() {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("User transferring ownership to themselves".to_string());
+ }
+
+ state
+ .store
+ .transfer_org_ownership_between_users(
+ &user_from_token.user_id,
+ user_to_be_updated.get_user_id(),
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
+ auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
+
+ let user_from_db = domain::UserFromStorage::from(user_from_token.get_user(&state).await?);
+ let user_role = user_from_db
+ .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id)
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)?;
+
+ let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+
+ Ok(ApplicationResponse::Json(
+ utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
+ ))
+}
+
pub async fn accept_invitation(
state: AppState,
user_token: auth::UserWithoutMerchantFromToken,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 029b1a57764..a5e5f216a8b 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1965,6 +1965,17 @@ impl UserRoleInterface for KafkaStore {
.await
}
+ async fn update_user_roles_by_user_id_org_id(
+ &self,
+ user_id: &str,
+ org_id: &str,
+ update: user_storage::UserRoleUpdate,
+ ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ self.diesel_store
+ .update_user_roles_by_user_id_org_id(user_id, org_id, update)
+ .await
+ }
+
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
@@ -1981,6 +1992,17 @@ impl UserRoleInterface for KafkaStore {
) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
self.diesel_store.list_user_roles_by_user_id(user_id).await
}
+
+ async fn transfer_org_ownership_between_users(
+ &self,
+ from_user_id: &str,
+ to_user_id: &str,
+ org_id: &str,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store
+ .transfer_org_ownership_between_users(from_user_id, to_user_id, org_id)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index f02e6d60b3b..12816fa006b 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -1,9 +1,12 @@
-use diesel_models::user_role as storage;
+use std::{collections::HashSet, ops::Not};
+
+use async_bb8_diesel::AsyncConnection;
+use diesel_models::{enums, user_role as storage};
use error_stack::{IntoReport, ResultExt};
use super::MockDb;
use crate::{
- connection,
+ connection, consts,
core::errors::{self, CustomResult},
services::Store,
};
@@ -32,6 +35,14 @@ pub trait UserRoleInterface {
merchant_id: &str,
update: storage::UserRoleUpdate,
) -> CustomResult<storage::UserRole, errors::StorageError>;
+
+ async fn update_user_roles_by_user_id_org_id(
+ &self,
+ user_id: &str,
+ org_id: &str,
+ update: storage::UserRoleUpdate,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
@@ -42,6 +53,13 @@ pub trait UserRoleInterface {
&self,
user_id: &str,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+
+ async fn transfer_org_ownership_between_users(
+ &self,
+ from_user_id: &str,
+ to_user_id: &str,
+ org_id: &str,
+ ) -> CustomResult<(), errors::StorageError>;
}
#[async_trait::async_trait]
@@ -103,6 +121,24 @@ impl UserRoleInterface for Store {
.into_report()
}
+ async fn update_user_roles_by_user_id_org_id(
+ &self,
+ user_id: &str,
+ org_id: &str,
+ update: storage::UserRoleUpdate,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::UserRole::update_by_user_id_org_id(
+ &conn,
+ user_id.to_owned(),
+ org_id.to_owned(),
+ update,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
@@ -129,6 +165,86 @@ impl UserRoleInterface for Store {
.map_err(Into::into)
.into_report()
}
+
+ async fn transfer_org_ownership_between_users(
+ &self,
+ from_user_id: &str,
+ to_user_id: &str,
+ org_id: &str,
+ ) -> CustomResult<(), errors::StorageError> {
+ let conn = connection::pg_connection_write(self)
+ .await
+ .change_context(errors::StorageError::DatabaseConnectionError)?;
+
+ conn.transaction_async(|conn| async move {
+ let old_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id(
+ &conn,
+ from_user_id.to_owned(),
+ org_id.to_owned(),
+ storage::UserRoleUpdate::UpdateRole {
+ role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
+ modified_by: from_user_id.to_owned(),
+ },
+ )
+ .await
+ .map_err(|e| *e.current_context())?;
+
+ let new_org_admin_user_roles = storage::UserRole::update_by_user_id_org_id(
+ &conn,
+ to_user_id.to_owned(),
+ org_id.to_owned(),
+ storage::UserRoleUpdate::UpdateRole {
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ modified_by: from_user_id.to_owned(),
+ },
+ )
+ .await
+ .map_err(|e| *e.current_context())?;
+
+ let new_org_admin_merchant_ids = new_org_admin_user_roles
+ .iter()
+ .map(|user_role| user_role.merchant_id.to_owned())
+ .collect::<HashSet<String>>();
+
+ let now = common_utils::date_time::now();
+
+ let missing_new_user_roles =
+ old_org_admin_user_roles.into_iter().filter_map(|old_role| {
+ new_org_admin_merchant_ids
+ .contains(&old_role.merchant_id)
+ .not()
+ .then_some({
+ storage::UserRoleNew {
+ user_id: to_user_id.to_string(),
+ merchant_id: old_role.merchant_id,
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ org_id: org_id.to_string(),
+ status: enums::UserStatus::Active,
+ created_by: from_user_id.to_string(),
+ last_modified_by: from_user_id.to_string(),
+ created_at: now,
+ last_modified: now,
+ }
+ })
+ });
+
+ futures::future::try_join_all(missing_new_user_roles.map(|user_role| async {
+ user_role
+ .insert(&conn)
+ .await
+ .map_err(|e| *e.current_context())
+ }))
+ .await?;
+
+ Ok::<_, errors::DatabaseError>(())
+ })
+ .await
+ .into_report()
+ .map_err(Into::into)
+ .into_report()?;
+
+ Ok(())
+ }
}
#[async_trait::async_trait]
@@ -241,6 +357,107 @@ impl UserRoleInterface for MockDb {
)
}
+ async fn update_user_roles_by_user_id_org_id(
+ &self,
+ user_id: &str,
+ org_id: &str,
+ update: storage::UserRoleUpdate,
+ ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ let mut user_roles = self.user_roles.lock().await;
+ let mut updated_user_roles = Vec::new();
+ for user_role in user_roles.iter_mut() {
+ if user_role.user_id == user_id && user_role.org_id == org_id {
+ match &update {
+ storage::UserRoleUpdate::UpdateRole {
+ role_id,
+ modified_by,
+ } => {
+ user_role.role_id = role_id.to_string();
+ user_role.last_modified_by = modified_by.to_string();
+ }
+ storage::UserRoleUpdate::UpdateStatus {
+ status,
+ modified_by,
+ } => {
+ user_role.status = status.to_owned();
+ user_role.last_modified_by = modified_by.to_owned();
+ }
+ }
+ updated_user_roles.push(user_role.to_owned());
+ }
+ }
+ if updated_user_roles.is_empty() {
+ Err(errors::StorageError::ValueNotFound(format!(
+ "No user role available for user_id = {user_id} and org_id = {org_id}"
+ ))
+ .into())
+ } else {
+ Ok(updated_user_roles)
+ }
+ }
+
+ async fn transfer_org_ownership_between_users(
+ &self,
+ from_user_id: &str,
+ to_user_id: &str,
+ org_id: &str,
+ ) -> CustomResult<(), errors::StorageError> {
+ let old_org_admin_user_roles = self
+ .update_user_roles_by_user_id_org_id(
+ from_user_id,
+ org_id,
+ storage::UserRoleUpdate::UpdateRole {
+ role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
+ modified_by: from_user_id.to_string(),
+ },
+ )
+ .await?;
+
+ let new_org_admin_user_roles = self
+ .update_user_roles_by_user_id_org_id(
+ to_user_id,
+ org_id,
+ storage::UserRoleUpdate::UpdateRole {
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ modified_by: from_user_id.to_string(),
+ },
+ )
+ .await?;
+
+ let new_org_admin_merchant_ids = new_org_admin_user_roles
+ .iter()
+ .map(|user_role| user_role.merchant_id.to_owned())
+ .collect::<HashSet<String>>();
+
+ let now = common_utils::date_time::now();
+
+ let missing_new_user_roles = old_org_admin_user_roles
+ .into_iter()
+ .filter_map(|old_roles| {
+ if !new_org_admin_merchant_ids.contains(&old_roles.merchant_id) {
+ Some(storage::UserRoleNew {
+ user_id: to_user_id.to_string(),
+ merchant_id: old_roles.merchant_id,
+ role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
+ org_id: org_id.to_string(),
+ status: enums::UserStatus::Active,
+ created_by: from_user_id.to_string(),
+ last_modified_by: from_user_id.to_string(),
+ created_at: now,
+ last_modified: now,
+ })
+ } else {
+ None
+ }
+ });
+
+ for user_role in missing_new_user_roles {
+ self.insert_user_role(user_role).await?;
+ }
+
+ Ok(())
+ }
+
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 651d3c0026f..65caa2b5c04 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1026,6 +1026,10 @@ impl User {
)
.service(web::resource("/invite/accept").route(web::post().to(accept_invitation)))
.service(web::resource("/update_role").route(web::post().to(update_user_role)))
+ .service(
+ web::resource("/transfer_ownership")
+ .route(web::post().to(transfer_org_ownership)),
+ )
.service(web::resource("/delete").route(web::delete().to(delete_user_role))),
);
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 1636ed3a764..02a45408baf 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -196,7 +196,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::AcceptInvitation
- | Flow::DeleteUserRole => Self::UserRole,
+ | Flow::DeleteUserRole
+ | Flow::TransferOrgOwnership => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index ec05db1d615..f84c158332b 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -97,6 +97,25 @@ pub async fn update_user_role(
.await
}
+pub async fn transfer_org_ownership(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_role_api::TransferOrgOwnershipRequest>,
+) -> HttpResponse {
+ let flow = Flow::TransferOrgOwnership;
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload,
+ user_role_core::transfer_org_ownership,
+ &auth::JWTAuth(Permission::UsersWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn accept_invitation(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 4344acf89ff..2f4d48bea74 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -311,6 +311,8 @@ pub enum Flow {
GetRoleFromToken,
/// Update user role
UpdateUserRole,
+ /// Transfer organization ownership
+ TransferOrgOwnership,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Generate Sample Data
| 2024-02-08T13:34:24Z |
## Description
<!-- Describe your changes in detail -->
This PR will add a new api to transfer ownership of an organization to other.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 allow users to change the ownership of an organization.
# | cfa10aa60ef16d2302787f7ecf7c129228fc0549 |
Postman
```
curl --location 'http://localhost:8080/user/user/transfer_ownership' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of org_admin user' \
--data-raw '{
"email": "email of the user who is not org_admin"
}'
```
If the api is successful, it will return the following response.
```
{
"token": "JWT",
"merchant_id": "merchant_id",
"name": "name of old org_admin",
"email": "email of old org_admin",
"verification_days_left": null,
"user_role": "merchant_admin"
}
```
| [
"crates/api_models/src/events/user_role.rs",
"crates/api_models/src/user_role.rs",
"crates/diesel_models/src/query/user_role.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user_role.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/rou... | |
juspay/hyperswitch | juspay__hyperswitch-3537 | Bug: [BUG] Nuvei recurring MIT payment is not handled in Authorize flow
### Bug Description
In the Nuvei Authorize flow implementation, the `get_request_body` method currently utilizes `TryFrom` to construct a `NuveiPaymentsRequest` using `RouterData`. To accommodate `NuveiPaymentsRequest` for each payment method, we have a match statement where `payments::PaymentMethodData::MandatePayment` needs to implement `TryFrom` for building `NuveiPaymentsRequest` specifically for recurring mandates. The logic already present in the `get_card_info` method should be relocated inside the new `TryFrom` implementation for `payments::PaymentMethodData::MandatePayment`
### Expected Behavior
Recurring MIT payments should work with connector_mandate_id for Nuvei connector.
### Actual Behavior
Recurring MIT payment with mandate id through Nuvei is failing saying "Selected payment method through nuvei is not implemented".
### Steps To Reproduce
1. Create CIT payment with nuvei connector.
2. Use mandate_id from the previous CIT payment and create MIT payment
3. Hyperswitch throws 501 http status code in the response
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) | diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index d5dd6e813ae..fe17fae8770 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -20,7 +20,7 @@ use crate::{
consts,
core::errors,
services,
- types::{self, api, storage::enums, transformers::ForeignTryFrom},
+ types::{self, api, storage::enums, transformers::ForeignTryFrom, BrowserInformation},
utils::OptionExt,
};
@@ -75,6 +75,7 @@ pub struct NuveiPaymentsRequest {
pub transaction_type: TransactionType,
pub is_rebilling: Option<String>,
pub payment_option: PaymentOption,
+ pub device_details: Option<DeviceDetails>,
pub checksum: String,
pub billing_address: Option<BillingAddress>,
pub related_transaction_id: Option<String>,
@@ -135,7 +136,6 @@ pub struct PaymentOption {
pub card: Option<Card>,
pub redirect_url: Option<Url>,
pub user_payment_option_id: Option<String>,
- pub device_details: Option<DeviceDetails>,
pub alternative_payment_method: Option<AlternativePaymentMethod>,
pub billing_address: Option<BillingAddress>,
}
@@ -315,7 +315,7 @@ pub struct V2AdditionalParams {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDetails {
- pub ip_address: String,
+ pub ip_address: Secret<String, pii::IpAddress>,
}
impl From<enums::CaptureMethod> for TransactionType {
@@ -746,6 +746,7 @@ impl<F>
let item = data.0;
let request_data = match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => get_card_info(item, &card),
+ api::PaymentMethodData::MandatePayment => Self::try_from(item),
api::PaymentMethodData::Wallet(wallet) => match wallet {
payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data),
payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)),
@@ -845,7 +846,6 @@ impl<F>
payments::PaymentMethodData::BankDebit(_)
| payments::PaymentMethodData::BankTransfer(_)
| payments::PaymentMethodData::Crypto(_)
- | payments::PaymentMethodData::MandatePayment
| payments::PaymentMethodData::Reward
| payments::PaymentMethodData::Upi(_)
| payments::PaymentMethodData::Voucher(_)
@@ -874,6 +874,7 @@ impl<F>
related_transaction_id: request_data.related_transaction_id,
payment_option: request_data.payment_option,
billing_address: request_data.billing_address,
+ device_details: request_data.device_details,
url_details: Some(UrlDetails {
success_url: return_url.clone(),
failure_url: return_url.clone(),
@@ -888,104 +889,110 @@ fn get_card_info<F>(
item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
card_details: &payments::Card,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let browser_info = item.request.get_browser_info()?;
+ let browser_information = item.request.browser_info.clone();
let related_transaction_id = if item.is_three_ds() {
item.request.related_transaction_id.clone()
} else {
None
};
- let connector_mandate_id = &item.request.connector_mandate_id();
- if connector_mandate_id.is_some() {
- Ok(NuveiPaymentsRequest {
- related_transaction_id,
- is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1
- user_token_id: Some(item.request.get_email()?),
- payment_option: PaymentOption {
- user_payment_option_id: connector_mandate_id.clone(),
- ..Default::default()
- },
- ..Default::default()
- })
- } else {
- let (is_rebilling, additional_params, user_token_id) =
- match item.request.setup_mandate_details.clone() {
- Some(mandate_data) => {
- let details = match mandate_data
- .mandate_type
- .get_required_value("mandate_type")
- .change_context(errors::ConnectorError::MissingRequiredField {
- field_name: "mandate_type",
- })? {
- MandateDataType::SingleUse(details) => details,
- MandateDataType::MultiUse(details) => {
- details.ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "mandate_data.mandate_type.multi_use",
- })?
- }
- };
- let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(
- Some(details.get_metadata().ok_or_else(utils::missing_field_err(
- "mandate_data.mandate_type.{multi_use|single_use}.metadata",
- ))?),
- )?;
- (
- Some("0".to_string()), // In case of first installment, rebilling should be 0
- Some(V2AdditionalParams {
- rebill_expiry: Some(
- details
- .get_end_date(date_time::DateFormat::YYYYMMDD)
- .change_context(errors::ConnectorError::DateFormattingFailed)?
- .ok_or_else(utils::missing_field_err(
- "mandate_data.mandate_type.{multi_use|single_use}.end_date",
- ))?,
- ),
- rebill_frequency: Some(mandate_meta.frequency),
- challenge_window_size: None,
- }),
- Some(item.request.get_email()?),
- )
- }
- _ => (None, None, None),
- };
- let three_d = if item.is_three_ds() {
- Some(ThreeD {
- browser_details: Some(BrowserDetails {
- accept_header: browser_info.get_accept_header()?,
- ip: browser_info.get_ip_address()?,
- java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(),
- java_script_enabled: browser_info
- .get_java_script_enabled()?
- .to_string()
- .to_uppercase(),
- language: browser_info.get_language()?,
- screen_height: browser_info.get_screen_height()?,
- screen_width: browser_info.get_screen_width()?,
- color_depth: browser_info.get_color_depth()?,
- user_agent: browser_info.get_user_agent()?,
- time_zone: browser_info.get_time_zone()?,
- }),
- v2_additional_params: additional_params,
- notification_url: item.request.complete_authorize_url.clone(),
- merchant_url: item.return_url.clone(),
- platform_type: Some(PlatformType::Browser),
- method_completion_ind: Some(MethodCompletion::Unavailable),
- ..Default::default()
- })
- } else {
- None
- };
- Ok(NuveiPaymentsRequest {
- related_transaction_id,
- is_rebilling,
- user_token_id,
- payment_option: PaymentOption::from(NuveiCardDetails {
- card: card_details.clone(),
- three_d,
+ let address = item.get_billing_address_details_as_optional();
+
+ let billing_address = match address {
+ Some(address) => Some(BillingAddress {
+ first_name: Some(address.get_first_name()?.clone()),
+ last_name: Some(address.get_last_name()?.clone()),
+ email: item.request.get_email()?,
+ country: item.get_billing_country()?,
+ }),
+ None => None,
+ };
+ let (is_rebilling, additional_params, user_token_id) =
+ match item.request.setup_mandate_details.clone() {
+ Some(mandate_data) => {
+ let details = match mandate_data
+ .mandate_type
+ .get_required_value("mandate_type")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "mandate_type",
+ })? {
+ MandateDataType::SingleUse(details) => details,
+ MandateDataType::MultiUse(details) => {
+ details.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "mandate_data.mandate_type.multi_use",
+ })?
+ }
+ };
+ let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(Some(
+ details.get_metadata().ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.metadata",
+ ))?,
+ ))?;
+ (
+ Some("0".to_string()), // In case of first installment, rebilling should be 0
+ Some(V2AdditionalParams {
+ rebill_expiry: Some(
+ details
+ .get_end_date(date_time::DateFormat::YYYYMMDD)
+ .change_context(errors::ConnectorError::DateFormattingFailed)?
+ .ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.end_date",
+ ))?,
+ ),
+ rebill_frequency: Some(mandate_meta.frequency),
+ challenge_window_size: None,
+ }),
+ Some(item.request.get_email()?),
+ )
+ }
+ _ => (None, None, None),
+ };
+ let three_d = if item.is_three_ds() {
+ let browser_details = match &browser_information {
+ Some(browser_info) => Some(BrowserDetails {
+ accept_header: browser_info.get_accept_header()?,
+ ip: browser_info.get_ip_address()?,
+ java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(),
+ java_script_enabled: browser_info
+ .get_java_script_enabled()?
+ .to_string()
+ .to_uppercase(),
+ language: browser_info.get_language()?,
+ screen_height: browser_info.get_screen_height()?,
+ screen_width: browser_info.get_screen_width()?,
+ color_depth: browser_info.get_color_depth()?,
+ user_agent: browser_info.get_user_agent()?,
+ time_zone: browser_info.get_time_zone()?,
}),
+ None => None,
+ };
+ Some(ThreeD {
+ browser_details,
+ v2_additional_params: additional_params,
+ notification_url: item.request.complete_authorize_url.clone(),
+ merchant_url: item.return_url.clone(),
+ platform_type: Some(PlatformType::Browser),
+ method_completion_ind: Some(MethodCompletion::Unavailable),
..Default::default()
})
- }
+ } else {
+ None
+ };
+
+ Ok(NuveiPaymentsRequest {
+ related_transaction_id,
+ is_rebilling,
+ user_token_id,
+ device_details: Option::<DeviceDetails>::foreign_try_from(
+ &item.request.browser_info.clone(),
+ )?,
+ payment_option: PaymentOption::from(NuveiCardDetails {
+ card: card_details.clone(),
+ three_d,
+ }),
+ billing_address,
+ ..Default::default()
+ })
}
impl From<NuveiCardDetails> for PaymentOption {
fn from(card_details: NuveiCardDetails) -> Self {
@@ -1532,6 +1539,51 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse>
}
}
+impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
+ for NuveiPaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ {
+ let item = data;
+ let connector_mandate_id = &item.request.connector_mandate_id();
+ let related_transaction_id = if item.is_three_ds() {
+ item.request.related_transaction_id.clone()
+ } else {
+ None
+ };
+ Ok(Self {
+ related_transaction_id,
+ device_details: Option::<DeviceDetails>::foreign_try_from(
+ &item.request.browser_info.clone(),
+ )?,
+ is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1
+ user_token_id: Some(item.request.get_email()?),
+ payment_option: PaymentOption {
+ user_payment_option_id: connector_mandate_id.clone(),
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ }
+ }
+}
+
+impl ForeignTryFrom<&Option<BrowserInformation>> for Option<DeviceDetails> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> {
+ let device_details = match browser_info {
+ Some(browser_info) => Some(DeviceDetails {
+ ip_address: browser_info.get_ip_address()?,
+ }),
+ None => None,
+ };
+ Ok(device_details)
+ }
+}
+
fn get_refund_response(
response: NuveiPaymentsResponse,
http_code: u16,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 7951246790f..1e4552d6577 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -86,6 +86,7 @@ pub trait RouterData {
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
+ fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails>;
}
pub trait PaymentResponseRouterData {
@@ -182,6 +183,14 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
.ok_or_else(missing_field_err("billing.address"))
}
+ fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails> {
+ self.address
+ .billing
+ .as_ref()
+ .and_then(|a| a.address.as_ref())
+ .cloned()
+ }
+
fn get_billing_address_with_phone_number(&self) -> Result<&api::Address, Error> {
self.address
.billing
| 2024-02-08T13:05:43Z |
## Description
- Moved mandate logic outside card_info to MandatePayment
- Included Device detail to send IP address to nuvei (mandatory) for both card_info and mandate flow , Ip address is taken from browser info
- Billing address for rawcard payment flow
- Moved broswer info inside three_ds request construction, since its optional for non-3ds card_info flow
https://github.com/juspay/hyperswitch/issues/3537
https://github.com/juspay/hyperswitch/issues/3511
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Open Issues :
https://github.com/juspay/hyperswitch/issues/3537
https://github.com/juspay/hyperswitch/issues/3511
Changes done to support Recurring mandate payments flow for Nuvei and included fix for mandatory detail population, like device_details, billing address and browser_info
# | df739a302b062277647afe5c3888015272fdc2cf |
Added screenshots from testing
Recurring pay with mandate
<img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4">
Payment With and without IP address
<img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e">
<img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9">
| [
"crates/router/src/connector/nuvei/transformers.rs",
"crates/router/src/connector/utils.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3511 | Bug: [BUG] Nuvei Payment request validation issues
### Bug Description
nuvei payments
- browser_info is validated for both non-3ds and 3ds flows, as per nuvei docs browser_info is mandatory only for 3ds flows. The validation should be thrown by gateway instead
- IP address and billing address not sent to Nuvei, which is mandatory by default, hyperswitch is currently not passing these fields. we were not able to use any other nuvei account due to this, These fields can be controlled at nuvei gateway account level, but by default they are mandatory and nuvei recommends these info to be sent.
### Expected Behavior
- browser_info : Gateway should validate if browser info is not provided, payment request should go through even without browser_info for non-3ds
- IP address and billing address should forward these details to nuvei
### Actual Behavior
- browser_info is validated by hyperswitch when not provided, even in cases where its not mandatory
- IP address and billing address is not sent from hyperswitch to nuvei
### Steps To Reproduce
Payment request to reproduce the issue :
```
`curl --location 'http://localhost:8090/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_GHrXsmnL5N4eGiw363ZF6qfzWxjk2UqwQHlkvaE4B03lGV9Vb4ESpCK6aKjYdN9V' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "futurebilling",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "testing",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"setup_future_usage": "off_session",
"payment_method_data": {
"card": {
"card_number": "4000027891380961",
"card_exp_month": "12",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 7000,
"currency": "USD",
"metadata": {
"frequency": "1"
},
"end_date": "2025-05-03T04:07:52.723Z"
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'`
```
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
x-request-id : 018d6035-8137-75c6-8088-4754d80e0701
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index d5dd6e813ae..fe17fae8770 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -20,7 +20,7 @@ use crate::{
consts,
core::errors,
services,
- types::{self, api, storage::enums, transformers::ForeignTryFrom},
+ types::{self, api, storage::enums, transformers::ForeignTryFrom, BrowserInformation},
utils::OptionExt,
};
@@ -75,6 +75,7 @@ pub struct NuveiPaymentsRequest {
pub transaction_type: TransactionType,
pub is_rebilling: Option<String>,
pub payment_option: PaymentOption,
+ pub device_details: Option<DeviceDetails>,
pub checksum: String,
pub billing_address: Option<BillingAddress>,
pub related_transaction_id: Option<String>,
@@ -135,7 +136,6 @@ pub struct PaymentOption {
pub card: Option<Card>,
pub redirect_url: Option<Url>,
pub user_payment_option_id: Option<String>,
- pub device_details: Option<DeviceDetails>,
pub alternative_payment_method: Option<AlternativePaymentMethod>,
pub billing_address: Option<BillingAddress>,
}
@@ -315,7 +315,7 @@ pub struct V2AdditionalParams {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDetails {
- pub ip_address: String,
+ pub ip_address: Secret<String, pii::IpAddress>,
}
impl From<enums::CaptureMethod> for TransactionType {
@@ -746,6 +746,7 @@ impl<F>
let item = data.0;
let request_data = match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => get_card_info(item, &card),
+ api::PaymentMethodData::MandatePayment => Self::try_from(item),
api::PaymentMethodData::Wallet(wallet) => match wallet {
payments::WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data),
payments::WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)),
@@ -845,7 +846,6 @@ impl<F>
payments::PaymentMethodData::BankDebit(_)
| payments::PaymentMethodData::BankTransfer(_)
| payments::PaymentMethodData::Crypto(_)
- | payments::PaymentMethodData::MandatePayment
| payments::PaymentMethodData::Reward
| payments::PaymentMethodData::Upi(_)
| payments::PaymentMethodData::Voucher(_)
@@ -874,6 +874,7 @@ impl<F>
related_transaction_id: request_data.related_transaction_id,
payment_option: request_data.payment_option,
billing_address: request_data.billing_address,
+ device_details: request_data.device_details,
url_details: Some(UrlDetails {
success_url: return_url.clone(),
failure_url: return_url.clone(),
@@ -888,104 +889,110 @@ fn get_card_info<F>(
item: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
card_details: &payments::Card,
) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let browser_info = item.request.get_browser_info()?;
+ let browser_information = item.request.browser_info.clone();
let related_transaction_id = if item.is_three_ds() {
item.request.related_transaction_id.clone()
} else {
None
};
- let connector_mandate_id = &item.request.connector_mandate_id();
- if connector_mandate_id.is_some() {
- Ok(NuveiPaymentsRequest {
- related_transaction_id,
- is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1
- user_token_id: Some(item.request.get_email()?),
- payment_option: PaymentOption {
- user_payment_option_id: connector_mandate_id.clone(),
- ..Default::default()
- },
- ..Default::default()
- })
- } else {
- let (is_rebilling, additional_params, user_token_id) =
- match item.request.setup_mandate_details.clone() {
- Some(mandate_data) => {
- let details = match mandate_data
- .mandate_type
- .get_required_value("mandate_type")
- .change_context(errors::ConnectorError::MissingRequiredField {
- field_name: "mandate_type",
- })? {
- MandateDataType::SingleUse(details) => details,
- MandateDataType::MultiUse(details) => {
- details.ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "mandate_data.mandate_type.multi_use",
- })?
- }
- };
- let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(
- Some(details.get_metadata().ok_or_else(utils::missing_field_err(
- "mandate_data.mandate_type.{multi_use|single_use}.metadata",
- ))?),
- )?;
- (
- Some("0".to_string()), // In case of first installment, rebilling should be 0
- Some(V2AdditionalParams {
- rebill_expiry: Some(
- details
- .get_end_date(date_time::DateFormat::YYYYMMDD)
- .change_context(errors::ConnectorError::DateFormattingFailed)?
- .ok_or_else(utils::missing_field_err(
- "mandate_data.mandate_type.{multi_use|single_use}.end_date",
- ))?,
- ),
- rebill_frequency: Some(mandate_meta.frequency),
- challenge_window_size: None,
- }),
- Some(item.request.get_email()?),
- )
- }
- _ => (None, None, None),
- };
- let three_d = if item.is_three_ds() {
- Some(ThreeD {
- browser_details: Some(BrowserDetails {
- accept_header: browser_info.get_accept_header()?,
- ip: browser_info.get_ip_address()?,
- java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(),
- java_script_enabled: browser_info
- .get_java_script_enabled()?
- .to_string()
- .to_uppercase(),
- language: browser_info.get_language()?,
- screen_height: browser_info.get_screen_height()?,
- screen_width: browser_info.get_screen_width()?,
- color_depth: browser_info.get_color_depth()?,
- user_agent: browser_info.get_user_agent()?,
- time_zone: browser_info.get_time_zone()?,
- }),
- v2_additional_params: additional_params,
- notification_url: item.request.complete_authorize_url.clone(),
- merchant_url: item.return_url.clone(),
- platform_type: Some(PlatformType::Browser),
- method_completion_ind: Some(MethodCompletion::Unavailable),
- ..Default::default()
- })
- } else {
- None
- };
- Ok(NuveiPaymentsRequest {
- related_transaction_id,
- is_rebilling,
- user_token_id,
- payment_option: PaymentOption::from(NuveiCardDetails {
- card: card_details.clone(),
- three_d,
+ let address = item.get_billing_address_details_as_optional();
+
+ let billing_address = match address {
+ Some(address) => Some(BillingAddress {
+ first_name: Some(address.get_first_name()?.clone()),
+ last_name: Some(address.get_last_name()?.clone()),
+ email: item.request.get_email()?,
+ country: item.get_billing_country()?,
+ }),
+ None => None,
+ };
+ let (is_rebilling, additional_params, user_token_id) =
+ match item.request.setup_mandate_details.clone() {
+ Some(mandate_data) => {
+ let details = match mandate_data
+ .mandate_type
+ .get_required_value("mandate_type")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "mandate_type",
+ })? {
+ MandateDataType::SingleUse(details) => details,
+ MandateDataType::MultiUse(details) => {
+ details.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "mandate_data.mandate_type.multi_use",
+ })?
+ }
+ };
+ let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(Some(
+ details.get_metadata().ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.metadata",
+ ))?,
+ ))?;
+ (
+ Some("0".to_string()), // In case of first installment, rebilling should be 0
+ Some(V2AdditionalParams {
+ rebill_expiry: Some(
+ details
+ .get_end_date(date_time::DateFormat::YYYYMMDD)
+ .change_context(errors::ConnectorError::DateFormattingFailed)?
+ .ok_or_else(utils::missing_field_err(
+ "mandate_data.mandate_type.{multi_use|single_use}.end_date",
+ ))?,
+ ),
+ rebill_frequency: Some(mandate_meta.frequency),
+ challenge_window_size: None,
+ }),
+ Some(item.request.get_email()?),
+ )
+ }
+ _ => (None, None, None),
+ };
+ let three_d = if item.is_three_ds() {
+ let browser_details = match &browser_information {
+ Some(browser_info) => Some(BrowserDetails {
+ accept_header: browser_info.get_accept_header()?,
+ ip: browser_info.get_ip_address()?,
+ java_enabled: browser_info.get_java_enabled()?.to_string().to_uppercase(),
+ java_script_enabled: browser_info
+ .get_java_script_enabled()?
+ .to_string()
+ .to_uppercase(),
+ language: browser_info.get_language()?,
+ screen_height: browser_info.get_screen_height()?,
+ screen_width: browser_info.get_screen_width()?,
+ color_depth: browser_info.get_color_depth()?,
+ user_agent: browser_info.get_user_agent()?,
+ time_zone: browser_info.get_time_zone()?,
}),
+ None => None,
+ };
+ Some(ThreeD {
+ browser_details,
+ v2_additional_params: additional_params,
+ notification_url: item.request.complete_authorize_url.clone(),
+ merchant_url: item.return_url.clone(),
+ platform_type: Some(PlatformType::Browser),
+ method_completion_ind: Some(MethodCompletion::Unavailable),
..Default::default()
})
- }
+ } else {
+ None
+ };
+
+ Ok(NuveiPaymentsRequest {
+ related_transaction_id,
+ is_rebilling,
+ user_token_id,
+ device_details: Option::<DeviceDetails>::foreign_try_from(
+ &item.request.browser_info.clone(),
+ )?,
+ payment_option: PaymentOption::from(NuveiCardDetails {
+ card: card_details.clone(),
+ three_d,
+ }),
+ billing_address,
+ ..Default::default()
+ })
}
impl From<NuveiCardDetails> for PaymentOption {
fn from(card_details: NuveiCardDetails) -> Self {
@@ -1532,6 +1539,51 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse>
}
}
+impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
+ for NuveiPaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ {
+ let item = data;
+ let connector_mandate_id = &item.request.connector_mandate_id();
+ let related_transaction_id = if item.is_three_ds() {
+ item.request.related_transaction_id.clone()
+ } else {
+ None
+ };
+ Ok(Self {
+ related_transaction_id,
+ device_details: Option::<DeviceDetails>::foreign_try_from(
+ &item.request.browser_info.clone(),
+ )?,
+ is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1
+ user_token_id: Some(item.request.get_email()?),
+ payment_option: PaymentOption {
+ user_payment_option_id: connector_mandate_id.clone(),
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ }
+ }
+}
+
+impl ForeignTryFrom<&Option<BrowserInformation>> for Option<DeviceDetails> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> {
+ let device_details = match browser_info {
+ Some(browser_info) => Some(DeviceDetails {
+ ip_address: browser_info.get_ip_address()?,
+ }),
+ None => None,
+ };
+ Ok(device_details)
+ }
+}
+
fn get_refund_response(
response: NuveiPaymentsResponse,
http_code: u16,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 7951246790f..1e4552d6577 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -86,6 +86,7 @@ pub trait RouterData {
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
+ fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails>;
}
pub trait PaymentResponseRouterData {
@@ -182,6 +183,14 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
.ok_or_else(missing_field_err("billing.address"))
}
+ fn get_billing_address_details_as_optional(&self) -> Option<api::AddressDetails> {
+ self.address
+ .billing
+ .as_ref()
+ .and_then(|a| a.address.as_ref())
+ .cloned()
+ }
+
fn get_billing_address_with_phone_number(&self) -> Result<&api::Address, Error> {
self.address
.billing
| 2024-02-08T13:05:43Z |
## Description
- Moved mandate logic outside card_info to MandatePayment
- Included Device detail to send IP address to nuvei (mandatory) for both card_info and mandate flow , Ip address is taken from browser info
- Billing address for rawcard payment flow
- Moved broswer info inside three_ds request construction, since its optional for non-3ds card_info flow
https://github.com/juspay/hyperswitch/issues/3537
https://github.com/juspay/hyperswitch/issues/3511
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Open Issues :
https://github.com/juspay/hyperswitch/issues/3537
https://github.com/juspay/hyperswitch/issues/3511
Changes done to support Recurring mandate payments flow for Nuvei and included fix for mandatory detail population, like device_details, billing address and browser_info
# | df739a302b062277647afe5c3888015272fdc2cf |
Added screenshots from testing
Recurring pay with mandate
<img width="1127" alt="Screenshot 2024-02-08 at 6 49 58 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/a6c7997d-c98e-4eb1-b5d3-27a71c26f1c4">
Payment With and without IP address
<img width="1400" alt="Screenshot 2024-02-08 at 6 49 08 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/cab36f5e-2a5d-4a42-8ef2-25e737ae8c7e">
<img width="1417" alt="Screenshot 2024-02-08 at 6 48 30 PM" src="https://github.com/juspay/hyperswitch/assets/97145230/46953001-166e-40b7-ab97-8ed08573d2b9">
| [
"crates/router/src/connector/nuvei/transformers.rs",
"crates/router/src/connector/utils.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3600 | Bug: [Refactor] Send an appropriate error if update_mandate is not supported
### Feature Description
Send an appropriate error if update_mandate is not also add support for allowing the payment with payment_method
_type as None
### Possible Implementation
- Improvise theImplementation if its a Card
- Thorw an appropriate error
### 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/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 7b505e7c01c..b8b0fffe339 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2136,12 +2136,33 @@ pub fn filter_pm_based_on_update_mandate_support_for_connector(
payment_method_type: &api_enums::PaymentMethodType,
connector: api_enums::Connector,
) -> bool {
- supported_payment_methods_for_mandate
- .0
- .get(payment_method)
- .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
- .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
- .unwrap_or(false)
+ if payment_method == &api_enums::PaymentMethod::Card {
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .map(|payment_method_type_hm| {
+ let pm_credit = payment_method_type_hm
+ .0
+ .get(&api_enums::PaymentMethodType::Credit)
+ .map(|conn| conn.connector_list.clone())
+ .unwrap_or_default();
+ let pm_debit = payment_method_type_hm
+ .0
+ .get(&api_enums::PaymentMethodType::Debit)
+ .map(|conn| conn.connector_list.clone())
+ .unwrap_or_default();
+ &pm_credit | &pm_debit
+ })
+ .map(|supported_connectors| supported_connectors.contains(&connector))
+ .unwrap_or(false)
+ } else {
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
+ .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
+ .unwrap_or(false)
+ }
}
fn filter_pm_based_on_supported_payments_for_mandate(
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index a81f97851d9..30918b2fe4e 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -1,3 +1,4 @@
+use api_models::enums::{PaymentMethod, PaymentMethodType};
use async_trait::async_trait;
use error_stack::{IntoReport, ResultExt};
@@ -275,17 +276,33 @@ impl types::SetupMandateRouterData {
let payment_method_type = self.request.payment_method_type;
let payment_method = self.request.payment_method_data.get_payment_method();
- let supported_connectors_config =
- payment_method
- .zip(payment_method_type)
- .map_or(false, |(pm, pmt)| {
+ let supported_connectors_config = payment_method.zip(payment_method_type).map_or_else(
+ || {
+ if payment_method == Some(PaymentMethod::Card) {
cards::filter_pm_based_on_update_mandate_support_for_connector(
supported_connectors_for_update_mandate,
- &pm,
- &pmt,
+ &PaymentMethod::Card,
+ &PaymentMethodType::Credit,
+ connector.connector_name,
+ ) && cards::filter_pm_based_on_update_mandate_support_for_connector(
+ supported_connectors_for_update_mandate,
+ &PaymentMethod::Card,
+ &PaymentMethodType::Debit,
connector.connector_name,
)
- });
+ } else {
+ false
+ }
+ },
+ |(pm, pmt)| {
+ cards::filter_pm_based_on_update_mandate_support_for_connector(
+ supported_connectors_for_update_mandate,
+ &pm,
+ &pmt,
+ connector.connector_name,
+ )
+ },
+ );
if supported_connectors_config {
let connector_integration: services::BoxedConnectorIntegration<
'_,
@@ -378,9 +395,13 @@ impl types::SetupMandateRouterData {
Err(_) => Ok(resp),
}
} else {
- Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable("Update Mandate Flow not implemented for the connector ")?
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Update Mandate flow not implemented for the connector {:?}",
+ connector.connector_name
+ ),
+ })
+ .into_report()
}
}
}
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 14d119768d0..c5232378615 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -256,9 +256,6 @@ bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
-[mandates.update_mandate_supported]
-connector_list = "cybersource"
-
[analytics]
source = "sqlx"
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json
index bc160467bf8..21c079e0ad0 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json
index 9340a493524..1ec9a829a48 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario17-Bank debit-Bacs/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json
index f0066e67bbc..824bfb49230 100644
--- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json
+++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario6-Create Wallet - Paypal/Payments - Create/request.json
@@ -32,7 +32,7 @@
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json
index 792e7c399fc..9778d0ee32b 100644
--- a/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json
+++ b/postman/collection-dir/paypal/Flow Testcases/Happy Cases/Scenario7-Create Wallet - Paypal with confrm false/Payments - Create/request.json
@@ -32,7 +32,7 @@
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json
index 0bf606d869e..7afc6d61c49 100644
--- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json
+++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json
index c2d7c7bf9c0..a6aef6ecb71 100644
--- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json
+++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
index caa19cc5c67..01fa4013653 100644
--- a/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
+++ b/postman/collection-dir/zen/Flow Testcases/Happy Cases/Scenario5-Create 3DS payment with confrm false/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json
index c2d7c7bf9c0..a6aef6ecb71 100644
--- a/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json
+++ b/postman/collection-dir/zen/Flow Testcases/Variation Cases/Scenario2-Confirming the payment without PMD/Payments - Create/request.json
@@ -31,7 +31,7 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"billing": {
"address": {
"line1": "1467",
| 2024-02-08T12:17:35Z |
## Description
Send an appropriate error if update_mandate is not also add support for allowing the payment with payment_method
_type as None and also fix the failing postman collection
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 96f82cb21233677968aade844db91f91e3918843 | - Create a MA and an MCA with Cybersource
> Make a UpdateMandatePayment with `payment_method_type` as null
>Payment would succeed

- Create a MA and an MCA with Cybersource
- >Make a Payment , would throw a 4xx
| [
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payments/flows/setup_mandate_flow.rs",
"loadtest/config/development.toml",
"postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario16-Bank debit-ach/Payments - Create/request.json",
"postman/collection-dir/adyen_uk/Flow T... | |
juspay/hyperswitch | juspay__hyperswitch-3599 | Bug: permission-info Order change
Change the ordering of the [ThreeDsDecisionManagerWrite , ThreeDsDecisionManagerRead] and [SurchargeDecisionManagerWrite, SurchargeDecisionManagerRead] of permissionInfo API.
| diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 99e4f1b6c09..450a5a738c3 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -159,8 +159,8 @@ impl ModuleInfo {
module: module_name,
description,
permissions: PermissionInfo::new(&[
- Permission::ThreeDsDecisionManagerWrite,
Permission::ThreeDsDecisionManagerRead,
+ Permission::ThreeDsDecisionManagerWrite,
]),
},
@@ -168,8 +168,8 @@ impl ModuleInfo {
module: module_name,
description,
permissions: PermissionInfo::new(&[
- Permission::SurchargeDecisionManagerWrite,
Permission::SurchargeDecisionManagerRead,
+ Permission::SurchargeDecisionManagerWrite,
]),
},
PermissionModule::AccountCreate => Self {
| 2024-02-08T09:02:32Z |
## Description
<!-- Describe your changes in detail -->
Change the ordering of the [ThreeDsDecisionManagerWrite , ThreeDsDecisionManagerRead] and [SurchargeDecisionManagerWrite, SurchargeDecisionManagerRead] of permissionInfo API.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
```
Previous
{
"module": "ThreeDsDecisionManager",
"description": "View and configure 3DS decision rules configured for a merchant",
"permissions": [
{
"enum_name": "ThreeDsDecisionManagerWrite",
"description": "Create and update 3DS decision rules"
},
{
"enum_name": "ThreeDsDecisionManagerRead",
"description": "View all 3DS decision rules configured for a merchant"
}
]
}
Now
{
"module": "ThreeDsDecisionManager",
"description": "View and configure 3DS decision rules configured for a merchant",
"permissions": [
{
"enum_name": "ThreeDsDecisionManagerRead",
"description": "View all 3DS decision rules configured for a merchant"
},
{
"enum_name": "ThreeDsDecisionManagerWrite",
"description": "Create and update 3DS decision rules"
}
]
}
```
# | 3a869a2d5731a2393a687ed7773eda5344bd8e3f |
```
curl --location 'http://localhost:8080/user/permission_info' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer <JWT> \
--header 'content-type: application/json' \
```
| [
"crates/router/src/services/authorization/info.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3593 | Bug: [FEATURE]:(doc) Add list mandates for customer in api reference
### Feature Description
Add `list mandates for customer` docs in api reference
### Possible Implementation
Add in open_api spec
### 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/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 1936300ee14..dc38181a683 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -114,6 +114,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::customers::customers_list,
routes::customers::customers_update,
routes::customers::customers_delete,
+ routes::customers::customers_mandates_list,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs
index 7517cdc61a0..19901cbbeb9 100644
--- a/crates/openapi/src/routes/customers.rs
+++ b/crates/openapi/src/routes/customers.rs
@@ -100,3 +100,19 @@ pub async fn customers_delete() {}
security(("api_key" = []))
)]
pub async fn customers_list() {}
+
+/// Customers - Mandates List
+///
+/// Lists all the mandates for a particular customer id.
+#[utoipa::path(
+ post,
+ path = "/customers/{customer_id}/mandates",
+ responses(
+ (status = 200, description = "List of retrieved mandates for a customer", body = Vec<MandateResponse>),
+ (status = 400, description = "Invalid Data"),
+ ),
+ tag = "Customers Mandates List",
+ operation_id = "List all Mandates for a Customer",
+ security(("api_key" = []))
+)]
+pub async fn customers_mandates_list() {}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 2803141b38b..be011422e03 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -1608,6 +1608,39 @@
]
}
},
+ "/customers/{customer_id}/mandates": {
+ "post": {
+ "tags": [
+ "Customers Mandates List"
+ ],
+ "summary": "Customers - Mandates List",
+ "description": "Customers - Mandates List\n\nLists all the mandates for a particular customer id.",
+ "operationId": "List all Mandates for a Customer",
+ "responses": {
+ "200": {
+ "description": "List of retrieved mandates for a customer",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/MandateResponse"
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/customers/{customer_id}/payment_methods": {
"get": {
"tags": [
| 2024-02-08T07:59:52Z |
## Description
<!-- Describe your changes in detail -->
add list mandates for customer
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | c2b2b65b9cfc43b5999888635c7b03b1d2de78b3 |
Can't be tested as this is a doc update PR
| [
"crates/openapi/src/openapi.rs",
"crates/openapi/src/routes/customers.rs",
"openapi/openapi_spec.json"
] | |
juspay/hyperswitch | juspay__hyperswitch-3585 | Bug: refactor: change list roles api to also send inactive merchants
| diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 41a407bd670..70c3eb6673b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -945,10 +945,13 @@ pub async fn create_merchant_account(
pub async fn list_merchant_ids_for_user(
state: AppState,
- user: auth::UserFromToken,
+ user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
- let user_roles =
- utils::user_role::get_active_user_roles_for_user(&state, &user.user_id).await?;
+ let user_roles = state
+ .store
+ .list_user_roles_by_user_id(user_from_token.user_id.as_str())
+ .await
+ .change_context(UserErrors::InternalServerError)?;
let merchant_accounts = state
.store
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 7ca06aeda0d..462d3d01d79 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,11 +1,8 @@
use api_models::user_role as user_role_api;
-use diesel_models::{enums::UserStatus, user_role::UserRole};
-use error_stack::ResultExt;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
- routes::AppState,
services::authorization::{
permissions::Permission,
predefined_permissions::{self, RoleInfo},
@@ -17,20 +14,6 @@ pub fn is_internal_role(role_id: &str) -> bool {
|| role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER
}
-pub async fn get_active_user_roles_for_user(
- state: &AppState,
- user_id: &str,
-) -> UserResult<Vec<UserRole>> {
- Ok(state
- .store
- .list_user_roles_by_user_id(user_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter(|ele| ele.status == UserStatus::Active)
- .collect())
-}
-
pub fn validate_role_id(role_id: &str) -> UserResult<()> {
if predefined_permissions::is_role_invitable(role_id) {
return Ok(());
| 2024-02-07T12:48:41Z |
## Description
<!-- Describe your changes in detail -->
Changed switch list api to also send inactive merchants in the response.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 use this in this api to get all the merchant details
# | fbe84b2a334cfb744ae4f27b1eadc892c7f9b164 |
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer JWT'
```
This api will send merchants with `is_active`: `false` in the response from now on.
```
[
{
"merchant_id": "merchant_1",
"merchant_name": null,
"is_active": false
},
{
"merchant_id": "merchant_2",
"merchant_name": null,
"is_active": true
}
]
```
| [
"crates/router/src/core/user.rs",
"crates/router/src/utils/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3582 | Bug: Logging framework - add connector name for all payment CRUD API calls
Add connector name labels for payment CRUD (create/confirm/void/redirect/update/retrieve) API’s to ES
| diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 3730c5bf9a4..feaa59485d6 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -265,7 +265,7 @@ pub enum CaptureSyncMethod {
/// Handle the flow by interacting with connector module
/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
/// In other cases, It will be created if required, even if it is not passed
-#[instrument(skip_all, fields(payment_method))]
+#[instrument(skip_all, fields(connector_name, payment_method))]
pub async fn execute_connector_processing_step<
'b,
'a,
@@ -285,6 +285,7 @@ where
{
// If needed add an error stack as follows
// connector_integration.build_request(req).attach_printable("Failed to build request");
+ tracing::Span::current().record("connector_name", &req.connector);
tracing::Span::current().record("payment_method", &req.payment_method.to_string());
logger::debug!(connector_request=?connector_request);
let mut router_data = req.clone();
| 2024-02-07T12:22:20Z |
## Description
<!-- Describe your changes in detail -->
Adding connector_name from the moment its available into logs for better search on ELS/Loki
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | c5343dfcc20f1000e319c62fa0341c46701595ff |
make a payment confirm api call
check for `connector_name` field in golden_log_line (can search loki with `{golden_log_line="true"}` query and find the log with request_id)
Impacted Area -> Application IO level logs

| [
"crates/router/src/services/api.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3577 | Bug: [BUG] : store connector mandate id in complete auth
### Bug Description
Connector_reference in TransactionResponse of Complete auth call not saved in the DB
### Expected Behavior
Store the connector_reference, when it is sent in Complete auth call.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index e564e4a733e..d58eae371e8 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -1,7 +1,7 @@
pub mod helpers;
pub mod utils;
use api_models::payments;
-use common_utils::{ext_traits::Encode, pii};
+use common_utils::ext_traits::Encode;
use diesel_models::{enums as storage_enums, Mandate};
use error_stack::{report, IntoReport, ResultExt};
use futures::future;
@@ -24,7 +24,7 @@ use crate::{
ConnectorData, GetToken,
},
domain, storage,
- transformers::ForeignTryFrom,
+ transformers::ForeignFrom,
},
utils::OptionExt,
};
@@ -154,25 +154,46 @@ pub async fn revoke_mandate(
pub async fn update_connector_mandate_id(
db: &dyn StorageInterface,
merchant_account: String,
- mandate_ids_opt: Option<api_models::payments::MandateIds>,
+ mandate_ids_opt: Option<String>,
+ payment_method_id: Option<String>,
resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
) -> RouterResponse<mandates::MandateResponse> {
- let connector_mandate_id = Option::foreign_try_from(resp)?;
+ let mandate_details = Option::foreign_from(resp);
+ let connector_mandate_id = mandate_details
+ .clone()
+ .map(|md| {
+ Encode::<types::MandateReference>::encode_to_value(&md)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .map(masking::Secret::new)
+ })
+ .transpose()?;
+
//Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present
- if let Some((mandate_ids, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
- let mandate_id = &mandate_ids.mandate_id;
+ if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
let mandate = db
- .find_mandate_by_merchant_id_mandate_id(&merchant_account, mandate_id)
+ .find_mandate_by_merchant_id_mandate_id(&merchant_account, &mandate_id)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound)?;
+
+ let update_mandate_details = match payment_method_id {
+ Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate {
+ connector_mandate_id: mandate_details
+ .and_then(|mandate_reference| mandate_reference.connector_mandate_id),
+ connector_mandate_ids: Some(connector_id),
+ payment_method_id: pmd_id,
+ original_payment_id: None,
+ },
+ None => storage::MandateUpdate::ConnectorReferenceUpdate {
+ connector_mandate_ids: Some(connector_id),
+ },
+ };
+
// only update the connector_mandate_id if existing is none
if mandate.connector_mandate_id.is_none() {
db.update_mandate_by_merchant_id_mandate_id(
&merchant_account,
- mandate_id,
- storage::MandateUpdate::ConnectorReferenceUpdate {
- connector_mandate_ids: Some(connector_id),
- },
+ &mandate_id,
+ update_mandate_details,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
@@ -454,27 +475,16 @@ pub async fn retrieve_mandates_list(
Ok(services::ApplicationResponse::Json(mandates_list))
}
-impl ForeignTryFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
- for Option<pii::SecretSerdeValue>
+impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
+ for Option<types::MandateReference>
{
- type Error = error_stack::Report<errors::ApiErrorResponse>;
- fn foreign_try_from(
- resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
- ) -> errors::RouterResult<Self> {
- let mandate_details = match resp {
+ fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self {
+ match resp {
Ok(types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
}) => mandate_reference,
_ => None,
- };
-
- mandate_details
- .map(|md| {
- Encode::<types::MandateReference>::encode_to_value(&md)
- .change_context(errors::ApiErrorResponse::MandateNotFound)
- .map(masking::Secret::new)
- })
- .transpose()
+ }
}
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index e5552f0d156..0666c921422 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -819,17 +819,27 @@ 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 during Psync
+ // 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_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_router_data_merchant_id = router_data.merchant_id.clone();
- let m_payment_data_mandate_id = payment_data.mandate_id.clone();
+ let m_payment_data_mandate_id =
+ payment_data
+ .payment_attempt
+ .mandate_id
+ .clone()
+ .or(payment_data
+ .mandate_id
+ .clone()
+ .map(|mandate_ids| mandate_ids.mandate_id));
let m_router_data_response = router_data.response.clone();
let mandate_update_fut = tokio::spawn(
async move {
mandate::update_connector_mandate_id(
m_db.as_ref(),
- m_router_data_merchant_id,
+ m_router_data_merchant_id.clone(),
m_payment_data_mandate_id,
+ m_payment_method_id,
m_router_data_response,
)
.await
| 2024-02-07T09:46:28Z |
## Description
<!-- Describe your changes in detail -->
In this PR we store the connector_reference, when it is sent in Complete auth call.
## Test Case
1. Make a 3ds mandate payment with Cybersource
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 0,
"currency": "PLN",
"confirm": true,
"business_country": "US",
"business_label": "default",
"capture_method": "automatic",
"customer_id": "abc",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"email": "sdh@xyz.in",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4622943127013705",
"card_exp_month": "12",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "CA",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "New York",
"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"
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 3200,
"account_name": "transaction_processing"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
, "mandate_type": {
"multi_use": {
"amount": 700,
"currency": "USD"
}
}
}
}'
```
<img width="1138" alt="Screenshot 2024-02-07 at 3 08 57 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/f25a3624-f6e7-477f-8a1f-28c569a770b9">
mandate id should be stored in the mandate table
<img width="1380" alt="Screenshot 2024-02-07 at 3 09 18 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/60033b46-11db-45e9-ad52-84729862b646">
DB Query
```
SELECT * FROM mandate WHERE mandate.original_payment_id = '{payment_id}';
```
## Flows Impacted
1. Normal payment
2. Setup mandate
3. Recurring mandate (both customer initiated and merchant initiated)
4. Flows where connector mandate reference is updated in the psync call or after redirection complete (Cybersource 3ds) | 5fb3c001b5dc371f81fe1708fd9a6c6978fb726e | [
"crates/router/src/core/mandate.rs",
"crates/router/src/core/payments/operations/payment_response.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3573 | Bug: feat: force password for user
Support to have a check whether for newly invited users, whether the password has been changed once or not. This will be limited to users with email feature flag disabled. | diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs
index 11588bbfbaf..66831c7aeb8 100644
--- a/crates/api_models/src/user/dashboard_metadata.rs
+++ b/crates/api_models/src/user/dashboard_metadata.rs
@@ -24,6 +24,8 @@ pub enum SetMetaDataRequest {
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
+ #[serde(skip)]
+ IsChangePasswordRequired,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -110,6 +112,7 @@ pub enum GetMetaDataRequest {
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
+ IsChangePasswordRequired,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -146,4 +149,5 @@ pub enum GetMetaDataResponse {
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
+ IsChangePasswordRequired(bool),
}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index babffdbc4a8..93a98dc824b 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -511,4 +511,5 @@ pub enum DashboardMetadata {
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
+ IsChangePasswordRequired,
}
diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs
index b1cb034eb1f..d91a4078128 100644
--- a/crates/diesel_models/src/query/dashboard_metadata.rs
+++ b/crates/diesel_models/src/query/dashboard_metadata.rs
@@ -105,7 +105,7 @@ impl DashboardMetadata {
.await
}
- pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id(
+ pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
conn: &PgPooledConn,
user_id: String,
merchant_id: String,
@@ -118,4 +118,20 @@ impl DashboardMetadata {
)
.await
}
+
+ pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ conn: &PgPooledConn,
+ user_id: String,
+ merchant_id: String,
+ data_key: enums::DashboardMetadata,
+ ) -> StorageResult<Self> {
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::user_id
+ .eq(user_id)
+ .and(dsl::merchant_id.eq(merchant_id))
+ .and(dsl::data_key.eq(data_key)),
+ )
+ .await
+ }
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 41a407bd670..58d702cbac1 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -8,8 +8,9 @@ use error_stack::ResultExt;
use masking::ExposeInterface;
#[cfg(feature = "email")]
use router_env::env;
-#[cfg(feature = "email")]
use router_env::logger;
+#[cfg(not(feature = "email"))]
+use user_api::dashboard_metadata::SetMetaDataRequest;
use super::errors::{UserErrors, UserResponse, UserResult};
#[cfg(feature = "email")]
@@ -308,6 +309,20 @@ pub async fn change_password(
.await
.change_context(UserErrors::InternalServerError)?;
+ #[cfg(not(feature = "email"))]
+ {
+ state
+ .store
+ .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ &user_from_token.user_id,
+ &user_from_token.merchant_id,
+ diesel_models::enums::DashboardMetadata::IsChangePasswordRequired,
+ )
+ .await
+ .map_err(|e| logger::error!("Error while deleting dashboard metadata {}", e))
+ .ok();
+ }
+
Ok(ApplicationResponse::StatusOk)
}
@@ -475,8 +490,8 @@ pub async fn invite_user(
.insert_user_role(UserRoleNew {
user_id: new_user.get_user_id().to_owned(),
merchant_id: user_from_token.merchant_id.clone(),
- role_id: request.role_id,
- org_id: user_from_token.org_id,
+ role_id: request.role_id.clone(),
+ org_id: user_from_token.org_id.clone(),
status: invitation_status,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
@@ -515,6 +530,20 @@ pub async fn invite_user(
#[cfg(not(feature = "email"))]
{
is_email_sent = false;
+ let invited_user_token = auth::UserFromToken {
+ user_id: new_user.get_user_id(),
+ merchant_id: user_from_token.merchant_id,
+ org_id: user_from_token.org_id,
+ role_id: request.role_id,
+ };
+
+ let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
+ dashboard_metadata::set_metadata(
+ state.clone(),
+ invited_user_token,
+ set_metadata_request,
+ )
+ .await?;
}
Ok(ApplicationResponse::Json(user_api::InviteUserResponse {
@@ -692,6 +721,17 @@ async fn handle_new_user_invitation(
#[cfg(not(feature = "email"))]
{
is_email_sent = false;
+
+ let invited_user_token = auth::UserFromToken {
+ user_id: new_user.get_user_id(),
+ merchant_id: user_from_token.merchant_id.clone(),
+ org_id: user_from_token.org_id.clone(),
+ role_id: request.role_id.clone(),
+ };
+
+ let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
+ dashboard_metadata::set_metadata(state.clone(), invited_user_token, set_metadata_request)
+ .await?;
}
Ok(InviteMultipleUserResponse {
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index 24ff292870e..82f95564768 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -105,6 +105,9 @@ fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::Me
api::SetMetaDataRequest::IsMultipleConfiguration => {
Ok(types::MetaData::IsMultipleConfiguration(true))
}
+ api::SetMetaDataRequest::IsChangePasswordRequired => {
+ Ok(types::MetaData::IsChangePasswordRequired(true))
+ }
}
}
@@ -131,6 +134,7 @@ fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum {
api::GetMetaDataRequest::ConfigureWoocom => DBEnum::ConfigureWoocom,
api::GetMetaDataRequest::SetupWoocomWebhook => DBEnum::SetupWoocomWebhook,
api::GetMetaDataRequest::IsMultipleConfiguration => DBEnum::IsMultipleConfiguration,
+ api::GetMetaDataRequest::IsChangePasswordRequired => DBEnum::IsChangePasswordRequired,
}
}
@@ -207,6 +211,9 @@ fn into_response(
DBEnum::IsMultipleConfiguration => Ok(api::GetMetaDataResponse::IsMultipleConfiguration(
data.is_some(),
)),
+ DBEnum::IsChangePasswordRequired => Ok(api::GetMetaDataResponse::IsChangePasswordRequired(
+ data.is_some(),
+ )),
}
}
@@ -520,6 +527,17 @@ async fn insert_metadata(
)
.await
}
+ types::MetaData::IsChangePasswordRequired(data) => {
+ utils::insert_user_scoped_metadata_to_db(
+ state,
+ user.user_id,
+ user.merchant_id,
+ user.org_id,
+ metadata_key,
+ data,
+ )
+ .await
+ }
}
}
diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs
index 8e2ac0b6ad3..49dd43313c4 100644
--- a/crates/router/src/db/dashboard_metadata.rs
+++ b/crates/router/src/db/dashboard_metadata.rs
@@ -14,6 +14,7 @@ pub trait DashboardMetadataInterface {
&self,
metadata: storage::DashboardMetadataNew,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
+
async fn update_metadata(
&self,
user_id: Option<String>,
@@ -30,6 +31,7 @@ pub trait DashboardMetadataInterface {
org_id: &str,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
+
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &str,
@@ -37,11 +39,18 @@ pub trait DashboardMetadataInterface {
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
- async fn delete_user_scoped_dashboard_metadata_by_merchant_id(
+ async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &str,
) -> CustomResult<bool, errors::StorageError>;
+
+ async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ &self,
+ user_id: &str,
+ merchant_id: &str,
+ data_key: enums::DashboardMetadata,
+ ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -117,16 +126,34 @@ impl DashboardMetadataInterface for Store {
.map_err(Into::into)
.into_report()
}
- async fn delete_user_scoped_dashboard_metadata_by_merchant_id(
+ async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id(
+ storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id(
+ &conn,
+ user_id.to_owned(),
+ merchant_id.to_owned(),
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ &self,
+ user_id: &str,
+ merchant_id: &str,
+ data_key: enums::DashboardMetadata,
+ ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&conn,
user_id.to_owned(),
merchant_id.to_owned(),
+ data_key,
)
.await
.map_err(Into::into)
@@ -267,7 +294,7 @@ impl DashboardMetadataInterface for MockDb {
}
Ok(query_result)
}
- async fn delete_user_scoped_dashboard_metadata_by_merchant_id(
+ async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &str,
@@ -294,4 +321,31 @@ impl DashboardMetadataInterface for MockDb {
Ok(true)
}
+
+ async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ &self,
+ user_id: &str,
+ merchant_id: &str,
+ data_key: enums::DashboardMetadata,
+ ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
+ let mut dashboard_metadata = self.dashboard_metadata.lock().await;
+
+ let index_to_remove = dashboard_metadata
+ .iter()
+ .position(|metadata_inner| {
+ metadata_inner
+ .user_id
+ .as_deref()
+ .map_or(false, |user_id_inner| user_id_inner == user_id)
+ && metadata_inner.merchant_id == merchant_id
+ && metadata_inner.data_key == data_key
+ })
+ .ok_or(errors::StorageError::ValueNotFound(
+ "No data found".to_string(),
+ ))?;
+
+ let deleted_value = dashboard_metadata.swap_remove(index_to_remove);
+
+ Ok(deleted_value)
+ }
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0a9030bae29..029b1a57764 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1964,6 +1964,7 @@ impl UserRoleInterface for KafkaStore {
.update_user_role_by_user_id_merchant_id(user_id, merchant_id, update)
.await
}
+
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
@@ -2021,6 +2022,7 @@ impl DashboardMetadataInterface for KafkaStore {
.find_user_scoped_dashboard_metadata(user_id, merchant_id, org_id, data_keys)
.await
}
+
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &str,
@@ -2032,13 +2034,28 @@ impl DashboardMetadataInterface for KafkaStore {
.await
}
- async fn delete_user_scoped_dashboard_metadata_by_merchant_id(
+ async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
- .delete_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id)
+ .delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id)
+ .await
+ }
+
+ async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ &self,
+ user_id: &str,
+ merchant_id: &str,
+ data_key: enums::DashboardMetadata,
+ ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
+ self.diesel_store
+ .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
+ user_id,
+ merchant_id,
+ data_key,
+ )
.await
}
}
diff --git a/crates/router/src/types/domain/user/dashboard_metadata.rs b/crates/router/src/types/domain/user/dashboard_metadata.rs
index 5e4017a3cb1..9c00809238e 100644
--- a/crates/router/src/types/domain/user/dashboard_metadata.rs
+++ b/crates/router/src/types/domain/user/dashboard_metadata.rs
@@ -25,6 +25,7 @@ pub enum MetaData {
ConfigureWoocom(bool),
SetupWoocomWebhook(bool),
IsMultipleConfiguration(bool),
+ IsChangePasswordRequired(bool),
}
impl From<&MetaData> for DBEnum {
@@ -51,6 +52,7 @@ impl From<&MetaData> for DBEnum {
MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom,
MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook,
MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration,
+ MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired,
}
}
}
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index bcf270010ea..ac3d918a34f 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -219,7 +219,9 @@ pub fn separate_metadata_type_based_on_scope(
| DBEnum::ConfigureWoocom
| DBEnum::SetupWoocomWebhook
| DBEnum::IsMultipleConfiguration => merchant_scoped.push(key),
- DBEnum::Feedback | DBEnum::ProdIntent => user_scoped.push(key),
+ DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => {
+ user_scoped.push(key)
+ }
}
}
(merchant_scoped, user_scoped)
| 2024-02-07T08:25:39Z |
## Description
For newly invited users, add support to have check for whether password has been changed once or not.
- Use enum `IsChangePasswordRequired` to have this check.
## Motivation and Context
For users with email feature flag disabled, there is no support to know whether the newly invited user has change password or not.
# | 3af6aaf28e92780679eb0314eb3e95803b9c3113 | For Test
Invite user
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "test_force@gmail.com",
"name": "test3",
"role_id": "merchant_admin"
}
'
```
Invited user signin
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=JWT' \
--data-raw '{
"email": "test_force@gmail.com",
"password": "926fc057-df2e-42af-aada-5e403487f3aa"
}'
```
Check value of Enum `IsChangePasswordRequired`
```
curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '
'
```
Response:
```
[
{
"IsChangePasswordRequired": true
}
]
```
Change Password:
```
curl --location 'http://localhost:8080/user/change_password' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
"old_password": "926fc057-df2e-42af-aada-5e403487f3aa",
"new_password": "test"
}
'
```
Again checking the value of enum after login:
```
curl --location --request GET 'http://localhost:8080/user/data?keys=IsChangePasswordRequired' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '
'
```
Response should be:
```
[
{
"IsChangePasswordRequired": false
}
]
```
| [
"crates/api_models/src/user/dashboard_metadata.rs",
"crates/diesel_models/src/enums.rs",
"crates/diesel_models/src/query/dashboard_metadata.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user/dashboard_metadata.rs",
"crates/router/src/db/dashboard_metadata.rs",
"crates/router/src/db/kafk... | |
juspay/hyperswitch | juspay__hyperswitch-3538 | Bug: [FEATURE] Decide Flow based on setup_future_usage param
### Feature Description
The setup_future_usage has two fields on_session and off_session. The flow, i.e. either SaveCard/Mandate, will be decided on the basis of these fields.
### Possible Implementation
In our current flow there's no specific SaveCard Flow implementation based on the setup_future_usage. So to have specific implementation and distinction between different flows, there would be appropriate usage of the fields of setup_future_usage as:
- If the field is on_session, there would be a normal save card flow
- if the field is off_session and customer_acceptance field is passed , there would be a mandate flow
- If the field is off_session and no customer_acceptance field is passed, there would be a One Time 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/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index b29f4e0d0c3..7c20a902d28 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -77,6 +77,9 @@ pub struct MandateCardDetails {
pub card_network: Option<api_enums::CardNetwork>,
/// The type of the payment card
pub card_type: Option<String>,
+ /// The nick_name of the card holder
+ #[schema(value_type = Option<String>)]
+ pub nick_name: Option<Secret<String>>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index c6de222f7d8..c64912195ed 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -103,6 +103,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
merchant_account,
self.request.payment_method_type,
key_store,
+ is_mandate,
))
.await?;
Ok(mandate::mandate_procedure(
@@ -134,6 +135,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
&merchant_account,
self.request.payment_method_type,
&key_store,
+ is_mandate,
))
.await;
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 8b0b54158fd..712184308dd 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -76,6 +76,9 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
)
.await
.to_setup_mandate_failed_response()?;
+
+ let is_mandate = resp.request.setup_mandate_details.is_some();
+
let pm_id = Box::pin(tokenization::save_payment_method(
state,
connector,
@@ -84,6 +87,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
merchant_account,
self.request.payment_method_type,
key_store,
+ is_mandate,
))
.await?;
@@ -280,6 +284,8 @@ impl types::SetupMandateRouterData {
let payment_method_type = self.request.payment_method_type;
+ let is_mandate = resp.request.setup_mandate_details.is_some();
+
let pm_id = Box::pin(tokenization::save_payment_method(
state,
connector,
@@ -288,6 +294,7 @@ impl types::SetupMandateRouterData {
merchant_account,
payment_method_type,
key_store,
+ is_mandate,
))
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 378cbb25467..9117dcb9966 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -8,7 +8,7 @@ use data_models::{
payments::payment_attempt::PaymentAttempt,
};
use diesel_models::ephemeral_key;
-use error_stack::{self, ResultExt};
+use error_stack::{self, report, ResultExt};
use masking::PeekInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
@@ -619,6 +619,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
+ if request.mandate_data.is_none()
+ && request
+ .setup_future_usage
+ .map(|fut_usage| fut_usage == enums::FutureUsage::OffSession)
+ .unwrap_or(false)
+ {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "`setup_future_usage` cannot be `off_session` for normal payments".into()
+ }))?
+ }
+
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 664fce820a0..b29696a2f10 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -672,6 +672,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
+ if request.mandate_data.is_none()
+ && request
+ .setup_future_usage
+ .map(|fut_usage| fut_usage == storage_enums::FutureUsage::OffSession)
+ .unwrap_or(false)
+ {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "`setup_future_usage` cannot be `off_session` for normal payments".into()
+ }))?
+ }
+
let mandate_type = helpers::validate_mandate(request, false)?;
Ok((
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index f52bce46d8e..1b9f512d842 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -22,6 +22,7 @@ use crate::{
};
#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
pub async fn save_payment_method<F: Clone, FData>(
state: &AppState,
connector: &api::ConnectorData,
@@ -30,6 +31,7 @@ pub async fn save_payment_method<F: Clone, FData>(
merchant_account: &domain::MerchantAccount,
payment_method_type: Option<storage_enums::PaymentMethodType>,
key_store: &domain::MerchantKeyStore,
+ is_mandate: bool,
) -> RouterResult<Option<String>>
where
FData: mandate::MandateBehaviour,
@@ -62,8 +64,16 @@ where
} else {
None
};
+ let future_usage_validation = resp
+ .request
+ .get_setup_future_usage()
+ .map(|future_usage| {
+ (future_usage == storage_enums::FutureUsage::OffSession && is_mandate)
+ || (future_usage == storage_enums::FutureUsage::OnSession && !is_mandate)
+ })
+ .unwrap_or(false);
- let pm_id = if resp.request.get_setup_future_usage().is_some() {
+ let pm_id = if future_usage_validation {
let customer = maybe_customer.to_owned().get_required_value("customer")?;
let payment_method_create_request = helpers::get_payment_method_create_request(
Some(&resp.request.get_payment_method_data()),
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index f6b2d7bba93..051547dfa92 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -112,6 +112,7 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker.card_type,
+ nick_name: card_details_from_locker.nick_name,
}
.into()
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 98cfaecf6b8..9627d32ef9e 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -9059,6 +9059,11 @@
"type": "string",
"description": "The type of the payment card",
"nullable": true
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "The nick_name of the card holder",
+ "nullable": true
}
}
},
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
index 4d4486b1d43..5b0c090f2be 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
@@ -62,7 +62,7 @@
"card_cvc": "737"
}
},
- "setup_future_usage": "off_session",
+ "setup_future_usage": "on_session",
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
@@ -79,14 +79,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
| 2024-02-06T18:00:28Z |
## Description
decide flow based on setup_future_usage
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 0a97a1eb6382a1aa465ac5a1dc792ea4e763511a | - Create an MA and MCA
- Change the setup future usage field on the basis of following cases :
> If the field is on_session, there would be a normal save card flow
> if the field is off_session and customer_acceptance field is passed , there would be a mandate flow
> If the field is off_session and no customer_acceptance field is passed, there would be a One Time Payment
> If the field is null it'll be a one Time Payment
| [
"crates/api_models/src/mandates.rs",
"crates/router/src/core/payments/flows/authorize_flow.rs",
"crates/router/src/core/payments/flows/setup_mandate_flow.rs",
"crates/router/src/core/payments/operations/payment_create.rs",
"crates/router/src/core/payments/operations/payment_update.rs",
"crates/router/src/... | |
juspay/hyperswitch | juspay__hyperswitch-3467 | Bug: [FEATURE]: Api for enable/disable Blocklist guard
This Api mentioned will be for toggling the `blocklist-guard` for a particular merchant. So the changes will be as mentioned:
> It will try to find a config associated with that merchant (guard_blocklist_for_{merchant_id}) which in tern is a boolean config.
> If present it will enable/disable it accordingly.
> If not present it will create a config and assign it appropriate value.
## So what happens if the guard is enabled for a particular merchant:
He will have the ability to block certain payment instruments on basis of
>fingerprint
>card-bins
>extended-bins.
Moreover, if guard is enabled, fingerprint generation for each and every payment attempt is insured and every payment will be tested against the blocklist of the merchant.
## If guard is disabled:
None of the above steps will be valid and every payment attempt will have fingerprint as null.
## Testing
The curl for the above mentioned api is as follows:
`POST /blocklist/toggle?status=true`
```
curl --location --request POST 'http://127.0.0.1:8080/blocklist/toggle?status=false' \
--header 'api-key: dev_xiikraRGPeYjPzsef71DjOllw0hy4M9feqqSBCdzJc9XT2kPay3MJnY4o6Ui93jS'
```
Enabled response:
```
{
"blocklist_guard_status": "blocklist guard is enabled"
}
```
Disabled response:
```
{
"blocklist_guard_status": "blocklist guard is disabled"
}
``` | diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs
index 888b9106ccc..9672b6de6ee 100644
--- a/crates/api_models/src/blocklist.rs
+++ b/crates/api_models/src/blocklist.rs
@@ -22,6 +22,11 @@ pub struct BlocklistResponse {
pub created_at: time::PrimitiveDateTime,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ToggleBlocklistResponse {
+ pub blocklist_guard_status: String,
+}
+
pub type AddToBlocklistResponse = BlocklistResponse;
pub type DeleteFromBlocklistResponse = BlocklistResponse;
@@ -39,6 +44,14 @@ fn default_list_limit() -> u16 {
10
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ToggleBlocklistQuery {
+ #[schema(value_type = BlocklistDataKind)]
+ pub status: bool,
+}
+
impl ApiEventMetric for BlocklistRequest {}
impl ApiEventMetric for BlocklistResponse {}
+impl ApiEventMetric for ToggleBlocklistResponse {}
impl ApiEventMetric for ListBlocklistQuery {}
+impl ApiEventMetric for ToggleBlocklistQuery {}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 982072e8c09..1936300ee14 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -151,6 +151,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::blocklist::remove_entry_from_blocklist,
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
+ routes::blocklist::toggle_blocklist_guard,
// Routes for payouts
routes::payouts::payouts_create,
@@ -450,6 +451,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
+ api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind
)),
diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rs
index bf683259e08..741925b93d2 100644
--- a/crates/openapi/src/routes/blocklist.rs
+++ b/crates/openapi/src/routes/blocklist.rs
@@ -1,3 +1,19 @@
+#[utoipa::path(
+ post,
+ path = "/blocklist/toggle",
+ params (
+ ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
+ ),
+ responses(
+ (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
+ (status = 400, description = "Invalid Data")
+ ),
+ tag = "Blocklist",
+ operation_id = "Toggle blocklist guard for a particular merchant",
+ security(("api_key" = []))
+)]
+pub async fn toggle_blocklist_guard() {}
+
#[utoipa::path(
post,
path = "/blocklist",
diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs
index 85845602449..12a0802517c 100644
--- a/crates/router/src/core/blocklist.rs
+++ b/crates/router/src/core/blocklist.rs
@@ -39,3 +39,13 @@ pub async fn list_blocklist_entries(
.await
.map(services::ApplicationResponse::Json)
}
+
+pub async fn toggle_blocklist_guard(
+ state: AppState,
+ merchant_account: domain::MerchantAccount,
+ query: api_blocklist::ToggleBlocklistQuery,
+) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> {
+ utils::toggle_blocklist_guard_for_merchant(&state, merchant_account.merchant_id, query)
+ .await
+ .map(services::ApplicationResponse::Json)
+}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index bc0a7335f1e..43701c80786 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -4,6 +4,7 @@ use common_utils::{
crypto::{self, SignMessage},
errors::CustomResult,
};
+use diesel_models::configs;
use error_stack::{IntoReport, ResultExt};
#[cfg(feature = "aws_kms")]
use external_services::aws_kms;
@@ -85,6 +86,56 @@ pub async fn delete_entry_from_blocklist(
Ok(blocklist_entry.foreign_into())
}
+pub async fn toggle_blocklist_guard_for_merchant(
+ state: &AppState,
+ merchant_id: String,
+ query: api_blocklist::ToggleBlocklistQuery,
+) -> CustomResult<api_blocklist::ToggleBlocklistResponse, errors::ApiErrorResponse> {
+ let key = get_blocklist_guard_key(merchant_id.as_str());
+ let maybe_guard = state.store.find_config_by_key(&key).await;
+ let new_config = configs::ConfigNew {
+ key: key.clone(),
+ config: query.status.to_string(),
+ };
+ match maybe_guard {
+ Ok(_config) => {
+ let updated_config = configs::ConfigUpdate::Update {
+ config: Some(query.status.to_string()),
+ };
+ state
+ .store
+ .update_config_by_key(&key, updated_config)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error enabling the blocklist guard")?;
+ }
+ Err(e) if e.current_context().is_db_not_found() => {
+ state
+ .store
+ .insert_config(new_config)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error enabling the blocklist guard")?;
+ }
+ Err(e) => {
+ logger::error!(error=?e);
+ Err(e)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error enabling the blocklist guard")?;
+ }
+ };
+ let guard_status = if query.status { "enabled" } else { "disabled" };
+ Ok(api_blocklist::ToggleBlocklistResponse {
+ blocklist_guard_status: guard_status.to_string(),
+ })
+}
+
+/// Provides the identifier for the specific merchant's blocklist guard config
+#[inline(always)]
+pub fn get_blocklist_guard_key(merchant_id: &str) -> String {
+ format!("guard_blocklist_for_{merchant_id}")
+}
+
pub async fn list_blocklist_entries_for_merchant(
state: &AppState,
merchant_id: String,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index f71592c5448..651d3c0026f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -658,6 +658,9 @@ impl Blocklist {
.route(web::post().to(blocklist::add_entry_to_blocklist))
.route(web::delete().to(blocklist::remove_entry_from_blocklist)),
)
+ .service(
+ web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)),
+ )
}
}
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index 9c93f49ab83..87072d2c777 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -117,3 +117,41 @@ pub async fn list_blocked_payment_methods(
))
.await
}
+
+#[utoipa::path(
+ post,
+ path = "/blocklist/toggle",
+ params (
+ ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
+ ),
+ responses(
+ (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
+ (status = 400, description = "Invalid Data")
+ ),
+ tag = "Blocklist",
+ operation_id = "Toggle blocklist guard for a particular merchant",
+ security(("api_key" = []))
+)]
+pub async fn toggle_blocklist_guard(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>,
+) -> HttpResponse {
+ let flow = Flow::ListBlocklist;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_payload.into_inner(),
+ |state, auth: auth::AuthenticationData, query| {
+ blocklist::toggle_blocklist_guard(state, auth.merchant_account, query)
+ },
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::MerchantAccountWrite),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 042e89fdd52..1636ed3a764 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -63,6 +63,7 @@ impl From<Flow> for ApiIdentifier {
Flow::AddToBlocklist => Self::Blocklist,
Flow::DeleteFromBlocklist => Self::Blocklist,
Flow::ListBlocklist => Self::Blocklist,
+ Flow::ToggleBlocklistGuard => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 11e6f9c0ed8..4344acf89ff 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -201,6 +201,8 @@ pub enum Flow {
DeleteFromBlocklist,
/// List entries from blocklist
ListBlocklist,
+ /// Toggle blocklist for merchant
+ ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Validate payment method flow
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 7f234661b51..b6531771e11 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -1233,6 +1233,45 @@
]
}
},
+ "/blocklist/toggle": {
+ "post": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Toggle blocklist guard for a particular merchant",
+ "parameters": [
+ {
+ "name": "status",
+ "in": "query",
+ "description": "Boolean value to enable/disable blocklist",
+ "required": true,
+ "schema": {
+ "type": "boolean"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Blocklist guard enabled/disabled",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleBlocklistResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/customers": {
"post": {
"tags": [
@@ -16114,6 +16153,17 @@
}
}
},
+ "ToggleBlocklistResponse": {
+ "type": "object",
+ "required": [
+ "blocklist_guard_status"
+ ],
+ "properties": {
+ "blocklist_guard_status": {
+ "type": "string"
+ }
+ }
+ },
"TouchNGoRedirection": {
"type": "object"
},
| 2024-02-06T14:08:09Z |
## Description
<!-- Describe your changes in detail -->
This Api mentioned will be for toggling the `blocklist-guard` for a particular merchant. So the changes will be as mentioned:
> It will try to find a config associated with that merchant (guard_blocklist_for_{merchant_id}) which in tern is a boolean config.
> If present it will enable/disable it accordingly.
> If not present it will create a config and assign it appropriate value.
More in the linked issue.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | a15e7ae9b156659e61de752ca94b6f43932d9de5 |
This can be found out in the linked issue.
| [
"crates/api_models/src/blocklist.rs",
"crates/openapi/src/openapi.rs",
"crates/openapi/src/routes/blocklist.rs",
"crates/router/src/core/blocklist.rs",
"crates/router/src/core/blocklist/utils.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/blocklist.rs",
"crates/router/src/routes/loc... | |
juspay/hyperswitch | juspay__hyperswitch-3517 | Bug: feat(EVENT_VIEWER): Add masking for connector responses in connector events
Currently connector responses are being logged without masking.
In order to protect PII data we need to add masking for the connector responses in connector events & logs | diff --git a/.cargo/config.toml b/.cargo/config.toml
index 5b27955262a..c372e06f927 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,6 +1,7 @@
[target.'cfg(all())']
rustflags = [
"-Funsafe_code",
+ "-Aclippy::option_map_unit_fn",
"-Wclippy::as_conversions",
"-Wclippy::expect_used",
"-Wclippy::index_refutable_slice",
diff --git a/add_connector.md b/add_connector.md
index 7fc3dcb27d1..93a9c8d7b99 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -9,14 +9,13 @@ This is a guide to contributing new connector to Router. This guide includes ins
- Understanding of the Connector APIs which you wish to integrate with Router
- Setup of Router repository and running it on local
- Access to API credentials for testing the Connector API (you can quickly sign up for sandbox/uat credentials by visiting the website of the connector you wish to integrate)
-- Ensure that you have the nightly toolchain installed because the connector template script includes code formatting.
+- Ensure that you have the nightly toolchain installed because the connector template script includes code formatting.
- Install it using `rustup`:
-
- ```bash
- rustup toolchain install nightly
- ```
+Install it using `rustup`:
+```bash
+ rustup toolchain install nightly
+```
In Router, there are Connectors and Payment Methods, examples of both are shown below from which the difference is apparent.
@@ -28,7 +27,7 @@ A connector is an integration to fulfill payments. Related use cases could be an
- Fraud and Risk management platform (like Signifyd, Riskified etc.,)
- Payment network (Visa, Master)
- Payment authentication services (Cardinal etc.,)
-Currently, the router is compatible with 'Payment Processors' and 'Fraud and Risk Management' platforms. Support for additional categories will be expanded in the near future.
+ Currently, the router is compatible with 'Payment Processors' and 'Fraud and Risk Management' platforms. Support for additional categories will be expanded in the near future.
### What is a Payment Method ?
@@ -127,11 +126,13 @@ Let's define `PaymentSource`
For request types that involve an amount, the implementation of `TryFrom<&ConnectorRouterData<&T>>` is required:
```rust
-impl TryFrom<&CheckoutRouterData<&T>> for PaymentsRequest
+impl TryFrom<&CheckoutRouterData<&T>> for PaymentsRequest
```
-else
+
+else
+
```rust
-impl TryFrom<T> for PaymentsRequest
+impl TryFrom<T> for PaymentsRequest
```
where `T` is a generic type which can be `types::PaymentsAuthorizeRouterData`, `types::PaymentsCaptureRouterData`, etc.
@@ -214,6 +215,7 @@ impl ForeignFrom<(CheckoutPaymentStatus, Option<Balances>)> for enums::AttemptSt
}
}
```
+
If you're converting ConnectorPaymentStatus to AttemptStatus without any additional conditions, you can employ the `impl From<ConnectorPaymentStatus> for enums::AttemptStatus`.
Note: A payment intent can have multiple payment attempts. `enums::AttemptStatus` represents the status of a payment attempt.
@@ -334,26 +336,27 @@ Some recommended fields that needs to be set on connector request and response
```rust
reference: item.router_data.connector_request_reference_id.clone(),
```
+
- **connector_response_reference_id :** Merchants might face ambiguity when deciding which ID to use in the connector dashboard for payment identification. It is essential to populate the connector_response_reference_id with the appropriate reference ID, allowing merchants to recognize the transaction. This field can be linked to either `merchant_reference` or `connector_transaction_id`, depending on the field that the connector dashboard search functionality supports.
```rust
connector_response_reference_id: item.response.reference.or(Some(item.response.id))
```
-- **resource_id :** The connector assigns an identifier to a payment attempt, referred to as `connector_transaction_id`. This identifier is represented as an enum variant for the `resource_id`. If the connector does not provide a `connector_transaction_id`, the resource_id is set to `NoResponseId`.
+- **resource_id :** The connector assigns an identifier to a payment attempt, referred to as `connector_transaction_id`. This identifier is represented as an enum variant for the `resource_id`. If the connector does not provide a `connector_transaction_id`, the resource_id is set to `NoResponseId`.
```rust
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
```
+
- **redirection_data :** For the implementation of a redirection flow (3D Secure, bank redirects, etc.), assign the redirection link to the `redirection_data`.
-```rust
+```rust
let redirection_data = item.response.links.redirect.map(|href| {
services::RedirectForm::from((href.redirection_url, services::Method::Get))
});
```
-
And finally the error type implementation
```rust
@@ -379,100 +382,110 @@ The following trait implementations are mandatory
Within the `ConnectorCommon` trait, you'll find the following methods :
- - `id` method corresponds directly to the connector name.
- ```rust
- fn id(&self) -> &'static str {
- "checkout"
- }
- ```
- - `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector.
- ```rust
- fn get_currency_unit(&self) -> api::CurrencyUnit {
- api::CurrencyUnit::Minor
- }
- ```
- - `common_get_content_type` method requires you to provide the accepted content type for the connector API.
- ```rust
- fn common_get_content_type(&self) -> &'static str {
- "application/json"
- }
- ```
- - `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows.
- ```rust
- fn get_auth_header(
- &self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth: checkout::CheckoutAuthType = auth_type
- .try_into()
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- format!("Bearer {}", auth.api_secret.peek()).into_masked(),
- )])
- }
- ```
+- `id` method corresponds directly to the connector name.
- - `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs.
- ```rust
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
- connectors.checkout.base_url.as_ref()
- }
- ```
- - `build_error_response` method is common error response handling for a connector if it is same in all cases
+```rust
+ fn id(&self) -> &'static str {
+ "checkout"
+ }
+```
- ```rust
- fn build_error_response(
- &self,
- res: types::Response,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: checkout::ErrorResponse = if res.response.is_empty() {
- let (error_codes, error_type) = if res.status_code == 401 {
- (
- Some(vec!["Invalid api key".to_string()]),
- Some("invalid_api_key".to_string()),
- )
- } else {
- (None, None)
- };
- checkout::ErrorResponse {
- request_id: None,
- error_codes,
- error_type,
- }
- } else {
- res.response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?
- };
+- `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector.
- router_env::logger::info!(error_response=?response);
- let errors_list = response.error_codes.clone().unwrap_or_default();
- let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority(
- self.clone(),
- errors_list
- .into_iter()
- .map(|errors| errors.into())
- .collect(),
- );
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: option_error_code_message
- .clone()
- .map(|error_code_message| error_code_message.error_code)
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: option_error_code_message
- .map(|error_code_message| error_code_message.error_message)
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason: response
- .error_codes
- .map(|errors| errors.join(" & "))
- .or(response.error_type),
- attempt_status: None,
- connector_transaction_id: None,
- })
- }
- ```
+```rust
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+```
+
+- `common_get_content_type` method requires you to provide the accepted content type for the connector API.
+
+```rust
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+```
+
+- `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows.
+
+```rust
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let auth: checkout::CheckoutAuthType = auth_type
+ .try_into()
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", auth.api_secret.peek()).into_masked(),
+ )])
+ }
+```
+
+- `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs.
+
+```rust
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.checkout.base_url.as_ref()
+ }
+```
+
+- `build_error_response` method is common error response handling for a connector if it is same in all cases
+
+```rust
+ fn build_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ let response: checkout::ErrorResponse = if res.response.is_empty() {
+ let (error_codes, error_type) = if res.status_code == 401 {
+ (
+ Some(vec!["Invalid api key".to_string()]),
+ Some("invalid_api_key".to_string()),
+ )
+ } else {
+ (None, None)
+ };
+ checkout::ErrorResponse {
+ request_id: None,
+ error_codes,
+ error_type,
+ }
+ } else {
+ res.response
+ .parse_struct("ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?
+ };
+
+ router_env::logger::info!(error_response=?response);
+ let errors_list = response.error_codes.clone().unwrap_or_default();
+ let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority(
+ self.clone(),
+ errors_list
+ .into_iter()
+ .map(|errors| errors.into())
+ .collect(),
+ );
+ Ok(types::ErrorResponse {
+ status_code: res.status_code,
+ code: option_error_code_message
+ .clone()
+ .map(|error_code_message| error_code_message.error_code)
+ .unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ message: option_error_code_message
+ .map(|error_code_message| error_code_message.error_message)
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: response
+ .error_codes
+ .map(|errors| errors.join(" & "))
+ .or(response.error_type),
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+```
**ConnectorIntegration :** For every api endpoint contains the url, using request transform and response transform and headers.
Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow):
@@ -488,6 +501,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
Ok(format!("{}{}", self.base_url(connectors), "payments"))
}
```
+
- `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows.
```rust
@@ -525,6 +539,7 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
```
- `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters.
+
```rust
fn build_request(
&self,
@@ -552,17 +567,22 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
))
}
```
+
- `handle_response` method calls transformers where connector response data is transformed into hyperswitch response.
+
```rust
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -571,18 +591,22 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
```
+
- `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait.
+
```rust
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
```
+
**ConnectorCommonExt :** An enhanced trait for `ConnectorCommon` that enables functions with a generic type. This trait includes the `build_headers` method, responsible for constructing both the common headers and the Authorization headers (retrieved from the `get_auth_header` method), returning them as a vector.
-```rust
+```rust
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
@@ -604,11 +628,11 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
**Payment :** This trait includes several other traits and is meant to represent the functionality related to payments.
-**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization.
+**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization.
-**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture.
+**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture.
-**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve.
+**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve.
**Refund :** This trait includes several other traits and is meant to represent the functionality related to Refunds.
@@ -616,7 +640,6 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple
**RefundSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds retrieve.
-
And the below derive traits
- **Debug**
@@ -629,9 +652,10 @@ Refer to other connector code for trait implementations. Mostly the rust compile
Feel free to connect with us in case of any queries and if you want to confirm the status mapping.
### **Set the currency Unit**
+
The `get_currency_unit` function, part of the ConnectorCommon trait, enables connectors to specify their accepted currency unit as either `Base` or `Minor`. For instance, Paypal designates its currency in the base unit (for example, USD), whereas Hyperswitch processes amounts in the minor unit (for example, cents). If a connector accepts amounts in the base unit, conversion is required, as illustrated.
-``` rust
+```rust
impl<T>
TryFrom<(
&types::api::CurrencyUnit,
@@ -722,8 +746,9 @@ Prior to executing tests in the shell, ensure that the API keys are configured i
```rust
export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"
- cargo test --package router --test connectors -- checkout --test-threads=1
+ cargo test --package router --test connectors -- checkout --test-threads=1
```
+
All tests should pass and add appropriate tests for connector specific payment flows.
### **Build payment request and response from json schema**
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index c64ce431968..987f6a8742f 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -5,6 +5,7 @@ use error_stack::{ResultExt, IntoReport};
use masking::ExposeInterface;
use crate::{
+ events::connector_api_logs::ConnectorEvent,
configs::settings,
utils::{self, BytesExt},
core::{
@@ -95,12 +96,16 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}ErrorResponse = res
.response
.parse_struct("{{project-name | downcase | pascal_case}}ErrorResponse")
.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,
@@ -194,9 +199,12 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData,errors::ConnectorError> {
let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("{{project-name | downcase | pascal_case}} 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 {
response,
data: data.clone(),
@@ -204,8 +212,8 @@ impl
})
}
- fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> {
- self.build_error_response(res)
+ fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
}
}
@@ -251,24 +259,28 @@ impl
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase}} 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 {
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)
+ self.build_error_response(res, event_builder)
}
}
@@ -328,12 +340,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res
.response
.parse_struct("{{project-name | downcase | pascal_case}} PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -344,8 +359,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -401,9 +417,12 @@ impl
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>,errors::ConnectorError> {
let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} 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 {
response,
data: data.clone(),
@@ -411,8 +430,8 @@ impl
})
}
- fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> {
- self.build_error_response(res)
+ fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
}
}
@@ -449,9 +468,12 @@ impl
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData,errors::ConnectorError,> {
let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} 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 {
response,
data: data.clone(),
@@ -459,8 +481,8 @@ impl
})
}
- fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> {
- self.build_error_response(res)
+ fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/README.md b/crates/analytics/docs/clickhouse/cluster_setup/README.md
deleted file mode 100644
index cd5f2dfeb02..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/README.md
+++ /dev/null
@@ -1,347 +0,0 @@
-# Tutorial for set up clickhouse server
-
-
-## Single server with docker
-
-
-- Run server
-
-```
-docker run -d --name clickhouse-server -p 9000:9000 --ulimit nofile=262144:262144 yandex/clickhouse-server
-
-```
-
-- Run client
-
-```
-docker run -it --rm --link clickhouse-server:clickhouse-server yandex/clickhouse-client --host clickhouse-server
-```
-
-Now you can see if it success setup or not.
-
-
-## Setup Cluster
-
-
-This part we will setup
-
-- 1 cluster, with 3 shards
-- Each shard has 2 replica server
-- Use ReplicatedMergeTree & Distributed table to setup our table.
-
-
-### Cluster
-
-Let's see our docker-compose.yml first.
-
-```
-version: '3'
-
-services:
- clickhouse-zookeeper:
- image: zookeeper
- ports:
- - "2181:2181"
- - "2182:2182"
- container_name: clickhouse-zookeeper
- hostname: clickhouse-zookeeper
-
- clickhouse-01:
- image: yandex/clickhouse-server
- hostname: clickhouse-01
- container_name: clickhouse-01
- ports:
- - 9001:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-01:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-02:
- image: yandex/clickhouse-server
- hostname: clickhouse-02
- container_name: clickhouse-02
- ports:
- - 9002:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-02:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-03:
- image: yandex/clickhouse-server
- hostname: clickhouse-03
- container_name: clickhouse-03
- ports:
- - 9003:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-03:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-04:
- image: yandex/clickhouse-server
- hostname: clickhouse-04
- container_name: clickhouse-04
- ports:
- - 9004:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-04:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-05:
- image: yandex/clickhouse-server
- hostname: clickhouse-05
- container_name: clickhouse-05
- ports:
- - 9005:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-05:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-06:
- image: yandex/clickhouse-server
- hostname: clickhouse-06
- container_name: clickhouse-06
- ports:
- - 9006:9000
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml
- # - ./data/server-06:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-networks:
- default:
- external:
- name: clickhouse-net
-```
-
-
-We have 6 clickhouse server container and one zookeeper container.
-
-
-**To enable replication ZooKeeper is required. ClickHouse will take care of data consistency on all replicas and run restore procedure after failure automatically. It's recommended to deploy ZooKeeper cluster to separate servers.**
-
-**ZooKeeper is not a requirement — in some simple cases you can duplicate the data by writing it into all the replicas from your application code. This approach is not recommended — in this case ClickHouse is not able to guarantee data consistency on all replicas. This remains the responsibility of your application.**
-
-
-Let's see config file.
-
-`./config/clickhouse_config.xml` is the default config file in docker, we copy it out and add this line
-
-```
- <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file.
- By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element.
- Values for substitutions are specified in /yandex/name_of_substitution elements in that file.
- -->
- <include_from>/etc/clickhouse-server/metrika.xml</include_from>
-```
-
-
-So lets see `clickhouse_metrika.xml`
-
-```
-<yandex>
- <clickhouse_remote_servers>
- <cluster_1>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
- <replica>
- <host>clickhouse-01</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-06</host>
- <port>9000</port>
- </replica>
- </shard>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
- <replica>
- <host>clickhouse-02</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-03</host>
- <port>9000</port>
- </replica>
- </shard>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
-
- <replica>
- <host>clickhouse-04</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-05</host>
- <port>9000</port>
- </replica>
- </shard>
- </cluster_1>
- </clickhouse_remote_servers>
- <zookeeper-servers>
- <node index="1">
- <host>clickhouse-zookeeper</host>
- <port>2181</port>
- </node>
- </zookeeper-servers>
- <networks>
- <ip>::/0</ip>
- </networks>
- <clickhouse_compression>
- <case>
- <min_part_size>10000000000</min_part_size>
- <min_part_size_ratio>0.01</min_part_size_ratio>
- <method>lz4</method>
- </case>
- </clickhouse_compression>
-</yandex>
-```
-
-and macros.xml, each instances has there own macros settings, like server 1:
-
-```
-<yandex>
- <macros>
- <replica>clickhouse-01</replica>
- <shard>01</shard>
- <layer>01</layer>
- </macros>
-</yandex>
-```
-
-
-**Make sure your macros settings is equal to remote server settings in metrika.xml**
-
-So now you can start the server.
-
-```
-docker network create clickhouse-net
-docker-compose up -d
-```
-
-Conn to server and see if the cluster settings fine;
-
-```
-docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server
-```
-
-```sql
-clickhouse-01 :) select * from system.clusters;
-
-SELECT *
-FROM system.clusters
-
-┌─cluster─────────────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name─────┬─host_address─┬─port─┬─is_local─┬─user────┬─default_database─┐
-│ cluster_1 │ 1 │ 1 │ 1 │ clickhouse-01 │ 172.21.0.4 │ 9000 │ 1 │ default │ │
-│ cluster_1 │ 1 │ 1 │ 2 │ clickhouse-06 │ 172.21.0.5 │ 9000 │ 1 │ default │ │
-│ cluster_1 │ 2 │ 1 │ 1 │ clickhouse-02 │ 172.21.0.8 │ 9000 │ 0 │ default │ │
-│ cluster_1 │ 2 │ 1 │ 2 │ clickhouse-03 │ 172.21.0.6 │ 9000 │ 0 │ default │ │
-│ cluster_1 │ 3 │ 1 │ 1 │ clickhouse-04 │ 172.21.0.7 │ 9000 │ 0 │ default │ │
-│ cluster_1 │ 3 │ 1 │ 2 │ clickhouse-05 │ 172.21.0.3 │ 9000 │ 0 │ default │ │
-│ test_shard_localhost │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9000 │ 1 │ default │ │
-│ test_shard_localhost_secure │ 1 │ 1 │ 1 │ localhost │ 127.0.0.1 │ 9440 │ 0 │ default │ │
-└─────────────────────────────┴───────────┴──────────────┴─────────────┴───────────────┴──────────────┴──────┴──────────┴─────────┴──────────────────┘
-```
-
-If you see this, it means cluster's settings work well(but not conn fine).
-
-
-### Replica Table
-
-So now we have a cluster and replica settings. For clickhouse, we need to create ReplicatedMergeTree Table as a local table in every server.
-
-```sql
-CREATE TABLE ttt (id Int32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/ttt', '{replica}') PARTITION BY id ORDER BY id
-```
-
-and Create Distributed Table conn to local table
-
-```sql
-CREATE TABLE ttt_all as ttt ENGINE = Distributed(cluster_1, default, ttt, rand());
-```
-
-
-### Insert and test
-
-gen some data and test.
-
-
-```
-# docker exec into client server 1 and
-for ((idx=1;idx<=100;++idx)); do clickhouse-client --host clickhouse-server --query "Insert into default.ttt_all values ($idx)"; done;
-```
-
-For Distributed table.
-
-```
-select count(*) from ttt_all;
-```
-
-For loacl table.
-
-```
-select count(*) from ttt;
-```
-
-
-## Authentication
-
-Please see config/users.xml
-
-
-- Conn
-```bash
-docker run -it --rm --network="clickhouse-net" --link clickhouse-01:clickhouse-server yandex/clickhouse-client --host clickhouse-server -u user1 --password 123456
-```
-
-## Source
-
-- https://clickhouse.yandex/docs/en/operations/table_engines/replication/#creating-replicated-tables
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml
deleted file mode 100644
index 94c854dc273..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml
+++ /dev/null
@@ -1,370 +0,0 @@
-<?xml version="1.0"?>
-<yandex>
- <logger>
- <!-- Possible levels: https://github.com/pocoproject/poco/blob/develop/Foundation/include/Poco/Logger.h#L105 -->
- <level>error</level>
- <size>1000M</size>
- <console>1</console>
- <count>10</count>
- <!-- <console>1</console> --> <!-- Default behavior is autodetection (log to console if not daemon mode and is tty) -->
- </logger>
- <!--display_name>production</display_name--> <!-- It is the name that will be shown in the client -->
- <http_port>8123</http_port>
- <tcp_port>9000</tcp_port>
-
- <!-- For HTTPS and SSL over native protocol. -->
- <!--
- <https_port>8443</https_port>
- <tcp_port_secure>9440</tcp_port_secure>
- -->
-
- <!-- Used with https_port and tcp_port_secure. Full ssl options list: https://github.com/ClickHouse-Extras/poco/blob/master/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#L71 -->
- <openSSL>
- <server> <!-- Used for https server AND secure tcp port -->
- <!-- openssl req -subj "/CN=localhost" -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout /etc/clickhouse-server/server.key -out /etc/clickhouse-server/server.crt -->
- <certificateFile>/etc/clickhouse-server/server.crt</certificateFile>
- <privateKeyFile>/etc/clickhouse-server/server.key</privateKeyFile>
- <!-- openssl dhparam -out /etc/clickhouse-server/dhparam.pem 4096 -->
- <dhParamsFile>/etc/clickhouse-server/dhparam.pem</dhParamsFile>
- <verificationMode>none</verificationMode>
- <loadDefaultCAFile>true</loadDefaultCAFile>
- <cacheSessions>true</cacheSessions>
- <disableProtocols>sslv2,sslv3</disableProtocols>
- <preferServerCiphers>true</preferServerCiphers>
- </server>
-
- <client> <!-- Used for connecting to https dictionary source -->
- <loadDefaultCAFile>true</loadDefaultCAFile>
- <cacheSessions>true</cacheSessions>
- <disableProtocols>sslv2,sslv3</disableProtocols>
- <preferServerCiphers>true</preferServerCiphers>
- <!-- Use for self-signed: <verificationMode>none</verificationMode> -->
- <invalidCertificateHandler>
- <!-- Use for self-signed: <name>AcceptCertificateHandler</name> -->
- <name>RejectCertificateHandler</name>
- </invalidCertificateHandler>
- </client>
- </openSSL>
-
- <!-- Default root page on http[s] server. For example load UI from https://tabix.io/ when opening http://localhost:8123 -->
- <!--
- <http_server_default_response><![CDATA[<html ng-app="SMI2"><head><base href="http://ui.tabix.io/"></head><body><div ui-view="" class="content-ui"></div><script src="http://loader.tabix.io/master.js"></script></body></html>]]></http_server_default_response>
- -->
-
- <!-- Port for communication between replicas. Used for data exchange. -->
- <interserver_http_port>9009</interserver_http_port>
-
- <!-- Hostname that is used by other replicas to request this server.
- If not specified, than it is determined analogous to 'hostname -f' command.
- This setting could be used to switch replication to another network interface.
- -->
- <!--
- <interserver_http_host>example.yandex.ru</interserver_http_host>
- -->
-
- <!-- Listen specified host. use :: (wildcard IPv6 address), if you want to accept connections both with IPv4 and IPv6 from everywhere. -->
- <!-- <listen_host>::</listen_host> -->
- <!-- Same for hosts with disabled ipv6: -->
- <!-- <listen_host>0.0.0.0</listen_host> -->
-
- <!-- Default values - try listen localhost on ipv4 and ipv6: -->
- <!--
- <listen_host>::1</listen_host>
- <listen_host>127.0.0.1</listen_host>
- -->
- <!-- Don't exit if ipv6 or ipv4 unavailable, but listen_host with this protocol specified -->
- <!-- <listen_try>0</listen_try> -->
-
- <!-- Allow listen on same address:port -->
- <!-- <listen_reuse_port>0</listen_reuse_port> -->
-
- <!-- <listen_backlog>64</listen_backlog> -->
-
- <max_connections>4096</max_connections>
- <keep_alive_timeout>3</keep_alive_timeout>
-
- <!-- Maximum number of concurrent queries. -->
- <max_concurrent_queries>100</max_concurrent_queries>
-
- <!-- Set limit on number of open files (default: maximum). This setting makes sense on Mac OS X because getrlimit() fails to retrieve
- correct maximum value. -->
- <!-- <max_open_files>262144</max_open_files> -->
-
- <!-- Size of cache of uncompressed blocks of data, used in tables of MergeTree family.
- In bytes. Cache is single for server. Memory is allocated only on demand.
- Cache is used when 'use_uncompressed_cache' user setting turned on (off by default).
- Uncompressed cache is advantageous only for very short queries and in rare cases.
- -->
- <uncompressed_cache_size>8589934592</uncompressed_cache_size>
-
- <!-- Approximate size of mark cache, used in tables of MergeTree family.
- In bytes. Cache is single for server. Memory is allocated only on demand.
- You should not lower this value.
- -->
- <mark_cache_size>5368709120</mark_cache_size>
-
-
- <!-- Path to data directory, with trailing slash. -->
- <path>/var/lib/clickhouse/</path>
-
- <!-- Path to temporary data for processing hard queries. -->
- <tmp_path>/var/lib/clickhouse/tmp/</tmp_path>
-
- <!-- Directory with user provided files that are accessible by 'file' table function. -->
- <user_files_path>/var/lib/clickhouse/user_files/</user_files_path>
-
- <!-- Path to configuration file with users, access rights, profiles of settings, quotas. -->
- <users_config>users.xml</users_config>
-
- <!-- Default profile of settings. -->
- <default_profile>default</default_profile>
-
- <!-- System profile of settings. This settings are used by internal processes (Buffer storage, Distributed DDL worker and so on). -->
- <!-- <system_profile>default</system_profile> -->
-
- <!-- Default database. -->
- <default_database>default</default_database>
-
- <!-- Server time zone could be set here.
-
- Time zone is used when converting between String and DateTime types,
- when printing DateTime in text formats and parsing DateTime from text,
- it is used in date and time related functions, if specific time zone was not passed as an argument.
-
- Time zone is specified as identifier from IANA time zone database, like UTC or Africa/Abidjan.
- If not specified, system time zone at server startup is used.
-
- Please note, that server could display time zone alias instead of specified name.
- Example: W-SU is an alias for Europe/Moscow and Zulu is an alias for UTC.
- -->
- <!-- <timezone>Europe/Moscow</timezone> -->
-
- <!-- You can specify umask here (see "man umask"). Server will apply it on startup.
- Number is always parsed as octal. Default umask is 027 (other users cannot read logs, data files, etc; group can only read).
- -->
- <!-- <umask>022</umask> -->
-
- <!-- Configuration of clusters that could be used in Distributed tables.
- https://clickhouse.yandex/docs/en/table_engines/distributed/
- -->
- <remote_servers incl="clickhouse_remote_servers" >
- <!-- Test only shard config for testing distributed storage -->
- <test_shard_localhost>
- <shard>
- <replica>
- <host>localhost</host>
- <port>9000</port>
- </replica>
- </shard>
- </test_shard_localhost>
- <test_shard_localhost_secure>
- <shard>
- <replica>
- <host>localhost</host>
- <port>9440</port>
- <secure>1</secure>
- </replica>
- </shard>
- </test_shard_localhost_secure>
- </remote_servers>
-
-
- <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file.
- By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element.
- Values for substitutions are specified in /yandex/name_of_substitution elements in that file.
- -->
- <include_from>/etc/clickhouse-server/metrika.xml</include_from>
- <!-- ZooKeeper is used to store metadata about replicas, when using Replicated tables.
- Optional. If you don't use replicated tables, you could omit that.
-
- See https://clickhouse.yandex/docs/en/table_engines/replication/
- -->
- <zookeeper incl="zookeeper-servers" optional="true" />
-
- <!-- Substitutions for parameters of replicated tables.
- Optional. If you don't use replicated tables, you could omit that.
-
- See https://clickhouse.yandex/docs/en/table_engines/replication/#creating-replicated-tables
- -->
- <macros incl="macros" optional="true" />
-
-
- <!-- Reloading interval for embedded dictionaries, in seconds. Default: 3600. -->
- <builtin_dictionaries_reload_interval>3600</builtin_dictionaries_reload_interval>
-
-
- <!-- Maximum session timeout, in seconds. Default: 3600. -->
- <max_session_timeout>3600</max_session_timeout>
-
- <!-- Default session timeout, in seconds. Default: 60. -->
- <default_session_timeout>60</default_session_timeout>
-
- <!-- Sending data to Graphite for monitoring. Several sections can be defined. -->
- <!--
- interval - send every X second
- root_path - prefix for keys
- hostname_in_path - append hostname to root_path (default = true)
- metrics - send data from table system.metrics
- events - send data from table system.events
- asynchronous_metrics - send data from table system.asynchronous_metrics
- -->
- <!--
- <graphite>
- <host>localhost</host>
- <port>42000</port>
- <timeout>0.1</timeout>
- <interval>60</interval>
- <root_path>one_min</root_path>
- <hostname_in_path>true</hostname_in_path>
-
- <metrics>true</metrics>
- <events>true</events>
- <asynchronous_metrics>true</asynchronous_metrics>
- </graphite>
- <graphite>
- <host>localhost</host>
- <port>42000</port>
- <timeout>0.1</timeout>
- <interval>1</interval>
- <root_path>one_sec</root_path>
-
- <metrics>true</metrics>
- <events>true</events>
- <asynchronous_metrics>false</asynchronous_metrics>
- </graphite>
- -->
-
-
- <!-- Query log. Used only for queries with setting log_queries = 1. -->
- <query_log>
- <!-- What table to insert data. If table is not exist, it will be created.
- When query log structure is changed after system update,
- then old table will be renamed and new table will be created automatically.
- -->
- <database>system</database>
- <table>query_log</table>
- <!--
- PARTITION BY expr https://clickhouse.yandex/docs/en/table_engines/custom_partitioning_key/
- Example:
- event_date
- toMonday(event_date)
- toYYYYMM(event_date)
- toStartOfHour(event_time)
- -->
- <partition_by>toYYYYMM(event_date)</partition_by>
- <!-- Interval of flushing data. -->
- <flush_interval_milliseconds>7500</flush_interval_milliseconds>
- </query_log>
-
-
- <!-- Uncomment if use part_log
- <part_log>
- <database>system</database>
- <table>part_log</table>
-
- <flush_interval_milliseconds>7500</flush_interval_milliseconds>
- </part_log>
- -->
-
-
- <!-- Parameters for embedded dictionaries, used in Yandex.Metrica.
- See https://clickhouse.yandex/docs/en/dicts/internal_dicts/
- -->
-
- <!-- Path to file with region hierarchy. -->
- <!-- <path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt</path_to_regions_hierarchy_file> -->
-
- <!-- Path to directory with files containing names of regions -->
- <!-- <path_to_regions_names_files>/opt/geo/</path_to_regions_names_files> -->
-
-
- <!-- Configuration of external dictionaries. See:
- https://clickhouse.yandex/docs/en/dicts/external_dicts/
- -->
- <dictionaries_config>*_dictionary.xml</dictionaries_config>
-
- <!-- Uncomment if you want data to be compressed 30-100% better.
- Don't do that if you just started using ClickHouse.
- -->
- <compression incl="clickhouse_compression">
- <!--
- <!- - Set of variants. Checked in order. Last matching case wins. If nothing matches, lz4 will be used. - ->
- <case>
-
- <!- - Conditions. All must be satisfied. Some conditions may be omitted. - ->
- <min_part_size>10000000000</min_part_size> <!- - Min part size in bytes. - ->
- <min_part_size_ratio>0.01</min_part_size_ratio> <!- - Min size of part relative to whole table size. - ->
-
- <!- - What compression method to use. - ->
- <method>zstd</method>
- </case>
- -->
- </compression>
-
- <!-- Allow to execute distributed DDL queries (CREATE, DROP, ALTER, RENAME) on cluster.
- Works only if ZooKeeper is enabled. Comment it if such functionality isn't required. -->
- <distributed_ddl>
- <!-- Path in ZooKeeper to queue with DDL queries -->
- <path>/clickhouse/task_queue/ddl</path>
-
- <!-- Settings from this profile will be used to execute DDL queries -->
- <!-- <profile>default</profile> -->
- </distributed_ddl>
-
- <!-- Settings to fine tune MergeTree tables. See documentation in source code, in MergeTreeSettings.h -->
- <!--
- <merge_tree>
- <max_suspicious_broken_parts>5</max_suspicious_broken_parts>
- </merge_tree>
- -->
-
- <!-- Protection from accidental DROP.
- If size of a MergeTree table is greater than max_table_size_to_drop (in bytes) than table could not be dropped with any DROP query.
- If you want do delete one table and don't want to restart clickhouse-server, you could create special file <clickhouse-path>/flags/force_drop_table and make DROP once.
- By default max_table_size_to_drop is 50GB; max_table_size_to_drop=0 allows to DROP any tables.
- The same for max_partition_size_to_drop.
- Uncomment to disable protection.
- -->
- <!-- <max_table_size_to_drop>0</max_table_size_to_drop> -->
- <!-- <max_partition_size_to_drop>0</max_partition_size_to_drop> -->
-
- <!-- Example of parameters for GraphiteMergeTree table engine -->
- <graphite_rollup_example>
- <pattern>
- <regexp>click_cost</regexp>
- <function>any</function>
- <retention>
- <age>0</age>
- <precision>3600</precision>
- </retention>
- <retention>
- <age>86400</age>
- <precision>60</precision>
- </retention>
- </pattern>
- <default>
- <function>max</function>
- <retention>
- <age>0</age>
- <precision>60</precision>
- </retention>
- <retention>
- <age>3600</age>
- <precision>300</precision>
- </retention>
- <retention>
- <age>86400</age>
- <precision>3600</precision>
- </retention>
- </default>
- </graphite_rollup_example>
-
- <!-- Directory in <clickhouse-path> containing schema files for various input formats.
- The directory will be created if it doesn't exist.
- -->
- <format_schema_path>/var/lib/clickhouse/format_schemas/</format_schema_path>
-
- <!-- Uncomment to disable ClickHouse internal DNS caching. -->
- <!-- <disable_internal_dns_cache>1</disable_internal_dns_cache> -->
-</yandex>
-
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml
deleted file mode 100644
index b58ffc34bc2..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<yandex>
- <clickhouse_remote_servers>
- <cluster_1>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
- <replica>
- <host>clickhouse-01</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-06</host>
- <port>9000</port>
- </replica>
- </shard>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
- <replica>
- <host>clickhouse-02</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-03</host>
- <port>9000</port>
- </replica>
- </shard>
- <shard>
- <weight>1</weight>
- <internal_replication>true</internal_replication>
-
- <replica>
- <host>clickhouse-04</host>
- <port>9000</port>
- </replica>
- <replica>
- <host>clickhouse-05</host>
- <port>9000</port>
- </replica>
- </shard>
- </cluster_1>
- </clickhouse_remote_servers>
- <zookeeper-servers>
- <node index="1">
- <host>clickhouse-zookeeper</host>
- <port>2181</port>
- </node>
- </zookeeper-servers>
- <networks>
- <ip>::/0</ip>
- </networks>
- <clickhouse_compression>
- <case>
- <min_part_size>10000000000</min_part_size>
- <min_part_size_ratio>0.01</min_part_size_ratio>
- <method>lz4</method>
- </case>
- </clickhouse_compression>
-</yandex>
-
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml
deleted file mode 100644
index 75df1c5916e..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-01.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-01</replica>
- <shard>01</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml
deleted file mode 100644
index 67e4a545b30..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-02.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-02</replica>
- <shard>02</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml
deleted file mode 100644
index e9278191b80..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-03.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-03</replica>
- <shard>02</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml
deleted file mode 100644
index 033c0ad1152..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-04.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-04</replica>
- <shard>03</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml
deleted file mode 100644
index c63314c5ace..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-05.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-05</replica>
- <shard>03</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml
deleted file mode 100644
index 4b01bda9948..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/macros/macros-06.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<yandex>
- <macros>
- <replica>clickhouse-06</replica>
- <shard>01</shard>
- <layer>01</layer>
- <installation>data</installation>
- <cluster>cluster_1</cluster>
- </macros>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml b/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml
deleted file mode 100644
index e1b8de78e37..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/config/users.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<?xml version="1.0"?>
-<yandex>
- <!-- Profiles of settings. -->
- <profiles>
- <!-- Default settings. -->
- <default>
- <!-- Maximum memory usage for processing single query, in bytes. -->
- <max_memory_usage>10000000000</max_memory_usage>
-
- <!-- Use cache of uncompressed blocks of data. Meaningful only for processing many of very short queries. -->
- <use_uncompressed_cache>0</use_uncompressed_cache>
-
- <!-- How to choose between replicas during distributed query processing.
- random - choose random replica from set of replicas with minimum number of errors
- nearest_hostname - from set of replicas with minimum number of errors, choose replica
- with minimum number of different symbols between replica's hostname and local hostname
- (Hamming distance).
- in_order - first live replica is chosen in specified order.
- -->
- <load_balancing>random</load_balancing>
- </default>
-
- <!-- Profile that allows only read queries. -->
- <readonly>
- <readonly>1</readonly>
- </readonly>
- </profiles>
-
- <!-- Users and ACL. -->
- <users>
- <user1>
- <password>123456</password>
- <networks incl="networks" replace="replace">
- <ip>::/0</ip>
- </networks>
- <profile>default</profile>
- <quota>default</quota>
- </user1>
- <!-- If user name was not specified, 'default' user is used. -->
- <default>
- <!-- Password could be specified in plaintext or in SHA256 (in hex format).
-
- If you want to specify password in plaintext (not recommended), place it in 'password' element.
- Example: <password>qwerty</password>.
- Password could be empty.
-
- If you want to specify SHA256, place it in 'password_sha256_hex' element.
- Example: <password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex>
-
- How to generate decent password:
- Execute: PASSWORD=$(base64 < /dev/urandom | head -c8); echo "$PASSWORD"; echo -n "$PASSWORD" | sha256sum | tr -d '-'
- In first line will be password and in second - corresponding SHA256.
- -->
- <password></password>
-
- <!-- List of networks with open access.
-
- To open access from everywhere, specify:
- <ip>::/0</ip>
-
- To open access only from localhost, specify:
- <ip>::1</ip>
- <ip>127.0.0.1</ip>
-
- Each element of list has one of the following forms:
- <ip> IP-address or network mask. Examples: 213.180.204.3 or 10.0.0.1/8 or 10.0.0.1/255.255.255.0
- 2a02:6b8::3 or 2a02:6b8::3/64 or 2a02:6b8::3/ffff:ffff:ffff:ffff::.
- <host> Hostname. Example: server01.yandex.ru.
- To check access, DNS query is performed, and all received addresses compared to peer address.
- <host_regexp> Regular expression for host names. Example, ^server\d\d-\d\d-\d\.yandex\.ru$
- To check access, DNS PTR query is performed for peer address and then regexp is applied.
- Then, for result of PTR query, another DNS query is performed and all received addresses compared to peer address.
- Strongly recommended that regexp is ends with $
- All results of DNS requests are cached till server restart.
- -->
- <networks incl="networks" replace="replace">
- <ip>::/0</ip>
- </networks>
-
- <!-- Settings profile for user. -->
- <profile>default</profile>
-
- <!-- Quota for user. -->
- <quota>default</quota>
- </default>
-
- <!-- Example of user with readonly access. -->
- <readonly>
- <password></password>
- <networks incl="networks" replace="replace">
- <ip>::1</ip>
- <ip>127.0.0.1</ip>
- </networks>
- <profile>readonly</profile>
- <quota>default</quota>
- </readonly>
- </users>
-
- <!-- Quotas. -->
- <quotas>
- <!-- Name of quota. -->
- <default>
- <!-- Limits for time interval. You could specify many intervals with different limits. -->
- <interval>
- <!-- Length of interval. -->
- <duration>3600</duration>
-
- <!-- No limits. Just calculate resource usage for time interval. -->
- <queries>0</queries>
- <errors>0</errors>
- <result_rows>0</result_rows>
- <read_rows>0</read_rows>
- <execution_time>0</execution_time>
- </interval>
- </default>
- </quotas>
-</yandex>
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml b/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml
deleted file mode 100644
index 96d7618b47e..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/docker-compose.yml
+++ /dev/null
@@ -1,198 +0,0 @@
-version: '3'
-
-networks:
- ckh_net:
-
-services:
- clickhouse-zookeeper:
- image: zookeeper
- ports:
- - "2181:2181"
- - "2182:2182"
- container_name: clickhouse-zookeeper
- hostname: clickhouse-zookeeper
- networks:
- - ckh_net
-
- clickhouse-01:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-01
- container_name: clickhouse-01
- networks:
- - ckh_net
- ports:
- - 9001:9000
- - 8124:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-01.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-01:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-02:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-02
- container_name: clickhouse-02
- networks:
- - ckh_net
- ports:
- - 9002:9000
- - 8125:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-02.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-02:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-03:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-03
- container_name: clickhouse-03
- networks:
- - ckh_net
- ports:
- - 9003:9000
- - 8126:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-03.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-03:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-04:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-04
- container_name: clickhouse-04
- networks:
- - ckh_net
- ports:
- - 9004:9000
- - 8127:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-04.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-04:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-05:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-05
- container_name: clickhouse-05
- networks:
- - ckh_net
- ports:
- - 9005:9000
- - 8128:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-05.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-05:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- clickhouse-06:
- image: clickhouse/clickhouse-server
- hostname: clickhouse-06
- container_name: clickhouse-06
- networks:
- - ckh_net
- ports:
- - 9006:9000
- - 8129:8123
- volumes:
- - ./config/clickhouse_config.xml:/etc/clickhouse-server/config.xml
- - ./config/clickhouse_metrika.xml:/etc/clickhouse-server/metrika.xml
- - ./config/macros/macros-06.xml:/etc/clickhouse-server/config.d/macros.xml
- - ./config/users.xml:/etc/clickhouse-server/users.xml
- # - ./data/server-06:/var/lib/clickhouse
- ulimits:
- nofile:
- soft: 262144
- hard: 262144
- depends_on:
- - "clickhouse-zookeeper"
-
- kafka0:
- image: confluentinc/cp-kafka:7.0.5
- hostname: kafka0
- container_name: kafka0
- ports:
- - 9092:9092
- - 9093
- - 9997
- - 29092
- environment:
- KAFKA_BROKER_ID: 1
- KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
- KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka0:29092,PLAINTEXT_HOST://localhost:9092
- KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
- KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
- KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
- KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
- KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
- KAFKA_PROCESS_ROLES: 'broker,controller'
- KAFKA_NODE_ID: 1
- KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka0:29093'
- KAFKA_LISTENERS: 'PLAINTEXT://kafka0:29092,CONTROLLER://kafka0:29093,PLAINTEXT_HOST://0.0.0.0:9092'
- KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
- KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs'
- JMX_PORT: 9997
- KAFKA_JMX_OPTS: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka0 -Dcom.sun.management.jmxremote.rmi.port=9997
- volumes:
- - ./kafka-script.sh:/tmp/update_run.sh
- command: "bash -c 'if [ ! -f /tmp/update_run.sh ]; then echo \"ERROR: Did you forget the update_run.sh file that came with this docker-compose.yml file?\" && exit 1 ; else /tmp/update_run.sh && /etc/confluent/docker/run ; fi'"
- networks:
- ckh_net:
- aliases:
- - hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local
-
-
- # Kafka UI for debugging kafka queues
- kafka-ui:
- container_name: kafka-ui
- image: provectuslabs/kafka-ui:latest
- ports:
- - 8090:8080
- depends_on:
- - kafka0
- networks:
- - ckh_net
- environment:
- KAFKA_CLUSTERS_0_NAME: local
- KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092
- KAFKA_CLUSTERS_0_JMXPORT: 9997
-
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh b/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh
deleted file mode 100755
index 023c832b4e1..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/kafka-script.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-# This script is required to run kafka cluster (without zookeeper)
-#!/bin/sh
-
-# Docker workaround: Remove check for KAFKA_ZOOKEEPER_CONNECT parameter
-sed -i '/KAFKA_ZOOKEEPER_CONNECT/d' /etc/confluent/docker/configure
-
-# Docker workaround: Ignore cub zk-ready
-sed -i 's/cub zk-ready/echo ignore zk-ready/' /etc/confluent/docker/ensure
-
-# KRaft required step: Format the storage directory with a new cluster ID
-echo "kafka-storage format --ignore-formatted -t $(kafka-storage random-uuid) -c /etc/kafka/kafka.properties" >> /etc/confluent/docker/ensure
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql
deleted file mode 100644
index ad0fe6d778f..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql
+++ /dev/null
@@ -1,242 +0,0 @@
-CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' (
- `merchant_id` String,
- `payment_id` Nullable(String),
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `customer_id` Nullable(String),
- `user_id` Nullable(String),
- `request_id` String,
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `url_path` LowCardinality(Nullable(String)),
- `event_type` LowCardinality(Nullable(String)),
- `created_at` DateTime CODEC(T64, LZ4),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- `dispute_id` Nullable(String)
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092',
-kafka_topic_list = 'hyperswitch-api-log-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-
-CREATE TABLE hyperswitch.api_events_clustered on cluster '{cluster}' (
- `merchant_id` String,
- `payment_id` Nullable(String),
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `customer_id` Nullable(String),
- `user_id` Nullable(String),
- `request_id` Nullable(String),
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1,
- INDEX apiIndex api_name TYPE bloom_filter GRANULARITY 1,
- INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_events_clustered',
- '{replica}'
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, flow_type, status_code, api_name)
-TTL created_at + toIntervalMonth(6)
-;
-
-
-CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' (
- `merchant_id` String,
- `payment_id` Nullable(String),
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `customer_id` Nullable(String),
- `user_id` Nullable(String),
- `request_id` Nullable(String),
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `url_path` LowCardinality(Nullable(String)),
- `event_type` LowCardinality(Nullable(String)),
- `inserted_at` DateTime64(3),
- `created_at` DateTime64(3),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- `dispute_id` Nullable(String)
-) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand());
-
-CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist (
- `merchant_id` String,
- `payment_id` Nullable(String),
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `customer_id` Nullable(String),
- `user_id` Nullable(String),
- `request_id` Nullable(String),
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `url_path` LowCardinality(Nullable(String)),
- `event_type` LowCardinality(Nullable(String)),
- `inserted_at` DateTime64(3),
- `created_at` DateTime64(3),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- `dispute_id` Nullable(String)
-) AS
-SELECT
- merchant_id,
- payment_id,
- refund_id,
- payment_method_id,
- payment_method,
- payment_method_type,
- customer_id,
- user_id,
- request_id,
- flow_type,
- api_name,
- request,
- response,
- status_code,
- url_path,
- event_type,
- now() as inserted_at,
- created_at,
- latency,
- user_agent,
- ip_addr
-FROM
- hyperswitch.api_events_queue
-WHERE length(_error) = 0;
-
-
-CREATE MATERIALIZED VIEW hyperswitch.api_events_parse_errors on cluster '{cluster}'
-(
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-)
-ENGINE = MergeTree
-ORDER BY (topic, partition, offset)
-SETTINGS index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM hyperswitch.api_events_queue
-WHERE length(_error) > 0
-;
-
-
-ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String));
-ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String));
-ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `dispute_id` Nullable(String);
-
-CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' (
- `merchant_id` LowCardinality(String),
- `payment_id` String,
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `user_id` Nullable(String),
- `request_id` Nullable(String),
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- `url_path` LowCardinality(Nullable(String)),
- `event_type` LowCardinality(Nullable(String)),
- `customer_id` LowCardinality(Nullable(String))
-) ENGINE = ReplicatedMergeTree( '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/api_audit_log', '{replica}' ) PARTITION BY merchant_id
-ORDER BY (merchant_id, payment_id)
-TTL created_at + toIntervalMonth(18)
-SETTINGS index_granularity = 8192
-
-
-CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO hyperswitch.api_audit_log(
- `merchant_id` LowCardinality(String),
- `payment_id` String,
- `refund_id` Nullable(String),
- `payment_method_id` Nullable(String),
- `payment_method` Nullable(String),
- `payment_method_type` Nullable(String),
- `customer_id` Nullable(String),
- `user_id` Nullable(String),
- `request_id` Nullable(String),
- `flow_type` LowCardinality(String),
- `api_name` LowCardinality(String),
- `request` String,
- `response` String,
- `status_code` UInt32,
- `url_path` LowCardinality(Nullable(String)),
- `event_type` LowCardinality(Nullable(String)),
- `inserted_at` DateTime64(3),
- `created_at` DateTime64(3),
- `latency` Nullable(UInt128),
- `user_agent` Nullable(String),
- `ip_addr` Nullable(String),
- `dispute_id` Nullable(String)
-) AS
-SELECT
- merchant_id,
- multiIf(payment_id IS NULL, '', payment_id) AS payment_id,
- refund_id,
- payment_method_id,
- payment_method,
- payment_method_type,
- customer_id,
- user_id,
- request_id,
- flow_type,
- api_name,
- request,
- response,
- status_code,
- url_path,
- api_event_type AS event_type,
- now() AS inserted_at,
- created_at,
- latency,
- user_agent,
- ip_addr,
- dispute_id
-FROM hyperswitch.api_events_queue
-WHERE length(_error) = 0
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql
deleted file mode 100644
index 3a6281ae905..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_attempts.sql
+++ /dev/null
@@ -1,217 +0,0 @@
-CREATE TABLE hyperswitch.payment_attempt_queue on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `attempt_id` String,
- `status` LowCardinality(String),
- `amount` Nullable(UInt32),
- `currency` LowCardinality(Nullable(String)),
- `connector` LowCardinality(Nullable(String)),
- `save_to_locker` Nullable(Bool),
- `error_message` Nullable(String),
- `offer_amount` Nullable(UInt32),
- `surcharge_amount` Nullable(UInt32),
- `tax_amount` Nullable(UInt32),
- `payment_method_id` Nullable(String),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_method_type` LowCardinality(Nullable(String)),
- `connector_transaction_id` Nullable(String),
- `capture_method` LowCardinality(Nullable(String)),
- `capture_on` Nullable(DateTime) CODEC(T64, LZ4),
- `confirm` Bool,
- `authentication_type` LowCardinality(Nullable(String)),
- `cancellation_reason` Nullable(String),
- `amount_to_capture` Nullable(UInt32),
- `mandate_id` Nullable(String),
- `browser_info` Nullable(String),
- `error_code` Nullable(String),
- `connector_metadata` Nullable(String),
- `payment_experience` Nullable(String),
- `created_at` DateTime CODEC(T64, LZ4),
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `modified_at` DateTime CODEC(T64, LZ4),
- `sign_flag` Int8
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
-kafka_topic_list = 'hyperswitch-payment-attempt-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-
-CREATE TABLE hyperswitch.payment_attempt_dist on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `attempt_id` String,
- `status` LowCardinality(String),
- `amount` Nullable(UInt32),
- `currency` LowCardinality(Nullable(String)),
- `connector` LowCardinality(Nullable(String)),
- `save_to_locker` Nullable(Bool),
- `error_message` Nullable(String),
- `offer_amount` Nullable(UInt32),
- `surcharge_amount` Nullable(UInt32),
- `tax_amount` Nullable(UInt32),
- `payment_method_id` Nullable(String),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_method_type` LowCardinality(Nullable(String)),
- `connector_transaction_id` Nullable(String),
- `capture_method` Nullable(String),
- `capture_on` Nullable(DateTime) CODEC(T64, LZ4),
- `confirm` Bool,
- `authentication_type` LowCardinality(Nullable(String)),
- `cancellation_reason` Nullable(String),
- `amount_to_capture` Nullable(UInt32),
- `mandate_id` Nullable(String),
- `browser_info` Nullable(String),
- `error_code` Nullable(String),
- `connector_metadata` Nullable(String),
- `payment_experience` Nullable(String),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8
-) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_attempt_clustered', cityHash64(attempt_id));
-
-
-
-CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_mv on cluster '{cluster}' TO hyperswitch.payment_attempt_dist (
- `payment_id` String,
- `merchant_id` String,
- `attempt_id` String,
- `status` LowCardinality(String),
- `amount` Nullable(UInt32),
- `currency` LowCardinality(Nullable(String)),
- `connector` LowCardinality(Nullable(String)),
- `save_to_locker` Nullable(Bool),
- `error_message` Nullable(String),
- `offer_amount` Nullable(UInt32),
- `surcharge_amount` Nullable(UInt32),
- `tax_amount` Nullable(UInt32),
- `payment_method_id` Nullable(String),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_method_type` LowCardinality(Nullable(String)),
- `connector_transaction_id` Nullable(String),
- `capture_method` Nullable(String),
- `confirm` Bool,
- `authentication_type` LowCardinality(Nullable(String)),
- `cancellation_reason` Nullable(String),
- `amount_to_capture` Nullable(UInt32),
- `mandate_id` Nullable(String),
- `browser_info` Nullable(String),
- `error_code` Nullable(String),
- `connector_metadata` Nullable(String),
- `payment_experience` Nullable(String),
- `created_at` DateTime64(3),
- `capture_on` Nullable(DateTime64(3)),
- `last_synced` Nullable(DateTime64(3)),
- `modified_at` DateTime64(3),
- `inserted_at` DateTime64(3),
- `sign_flag` Int8
-) AS
-SELECT
- payment_id,
- merchant_id,
- attempt_id,
- status,
- amount,
- currency,
- connector,
- save_to_locker,
- error_message,
- offer_amount,
- surcharge_amount,
- tax_amount,
- payment_method_id,
- payment_method,
- payment_method_type,
- connector_transaction_id,
- capture_method,
- confirm,
- authentication_type,
- cancellation_reason,
- amount_to_capture,
- mandate_id,
- browser_info,
- error_code,
- connector_metadata,
- payment_experience,
- created_at,
- capture_on,
- last_synced,
- modified_at,
- now() as inserted_at,
- sign_flag
-FROM
- hyperswitch.payment_attempt_queue
-WHERE length(_error) = 0;
-
-
-CREATE TABLE hyperswitch.payment_attempt_clustered on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `attempt_id` String,
- `status` LowCardinality(String),
- `amount` Nullable(UInt32),
- `currency` LowCardinality(Nullable(String)),
- `connector` LowCardinality(Nullable(String)),
- `save_to_locker` Nullable(Bool),
- `error_message` Nullable(String),
- `offer_amount` Nullable(UInt32),
- `surcharge_amount` Nullable(UInt32),
- `tax_amount` Nullable(UInt32),
- `payment_method_id` Nullable(String),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_method_type` LowCardinality(Nullable(String)),
- `connector_transaction_id` Nullable(String),
- `capture_method` Nullable(String),
- `capture_on` Nullable(DateTime) CODEC(T64, LZ4),
- `confirm` Bool,
- `authentication_type` LowCardinality(Nullable(String)),
- `cancellation_reason` Nullable(String),
- `amount_to_capture` Nullable(UInt32),
- `mandate_id` Nullable(String),
- `browser_info` Nullable(String),
- `error_code` Nullable(String),
- `connector_metadata` Nullable(String),
- `payment_experience` Nullable(String),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8,
- INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
- INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
- INDEX authenticationTypeIndex authentication_type TYPE bloom_filter GRANULARITY 1,
- INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1,
- INDEX statusIndex status TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedCollapsingMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_attempt_clustered',
- '{replica}',
- sign_flag
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, attempt_id)
-TTL created_at + toIntervalMonth(6)
-;
-
-CREATE MATERIALIZED VIEW hyperswitch.payment_attempt_parse_errors on cluster '{cluster}'
-(
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-)
-ENGINE = MergeTree
-ORDER BY (topic, partition, offset)
-SETTINGS index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM hyperswitch.payment_attempt_queue
-WHERE length(_error) > 0
-;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql
deleted file mode 100644
index eb2d83140e9..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/payment_intents.sql
+++ /dev/null
@@ -1,165 +0,0 @@
-CREATE TABLE hyperswitch.payment_intents_queue on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `status` LowCardinality(String),
- `amount` UInt32,
- `currency` LowCardinality(Nullable(String)),
- `amount_captured` Nullable(UInt32),
- `customer_id` Nullable(String),
- `description` Nullable(String),
- `return_url` Nullable(String),
- `connector_id` LowCardinality(Nullable(String)),
- `statement_descriptor_name` Nullable(String),
- `statement_descriptor_suffix` Nullable(String),
- `setup_future_usage` LowCardinality(Nullable(String)),
- `off_session` Nullable(Bool),
- `client_secret` Nullable(String),
- `active_attempt_id` String,
- `business_country` String,
- `business_label` String,
- `modified_at` DateTime,
- `created_at` DateTime,
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `sign_flag` Int8
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
-kafka_topic_list = 'hyperswitch-payment-intent-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-CREATE TABLE hyperswitch.payment_intents_dist on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `status` LowCardinality(String),
- `amount` UInt32,
- `currency` LowCardinality(Nullable(String)),
- `amount_captured` Nullable(UInt32),
- `customer_id` Nullable(String),
- `description` Nullable(String),
- `return_url` Nullable(String),
- `connector_id` LowCardinality(Nullable(String)),
- `statement_descriptor_name` Nullable(String),
- `statement_descriptor_suffix` Nullable(String),
- `setup_future_usage` LowCardinality(Nullable(String)),
- `off_session` Nullable(Bool),
- `client_secret` Nullable(String),
- `active_attempt_id` String,
- `business_country` LowCardinality(String),
- `business_label` String,
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8
-) ENGINE = Distributed('{cluster}', 'hyperswitch', 'payment_intents_clustered', cityHash64(payment_id));
-
-CREATE TABLE hyperswitch.payment_intents_clustered on cluster '{cluster}' (
- `payment_id` String,
- `merchant_id` String,
- `status` LowCardinality(String),
- `amount` UInt32,
- `currency` LowCardinality(Nullable(String)),
- `amount_captured` Nullable(UInt32),
- `customer_id` Nullable(String),
- `description` Nullable(String),
- `return_url` Nullable(String),
- `connector_id` LowCardinality(Nullable(String)),
- `statement_descriptor_name` Nullable(String),
- `statement_descriptor_suffix` Nullable(String),
- `setup_future_usage` LowCardinality(Nullable(String)),
- `off_session` Nullable(Bool),
- `client_secret` Nullable(String),
- `active_attempt_id` String,
- `business_country` LowCardinality(String),
- `business_label` String,
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `last_synced` Nullable(DateTime) CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8,
- INDEX connectorIndex connector_id TYPE bloom_filter GRANULARITY 1,
- INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1,
- INDEX statusIndex status TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedCollapsingMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/payment_intents_clustered',
- '{replica}',
- sign_flag
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, payment_id)
-TTL created_at + toIntervalMonth(6)
-;
-
-CREATE MATERIALIZED VIEW hyperswitch.payment_intent_mv on cluster '{cluster}' TO hyperswitch.payment_intents_dist (
- `payment_id` String,
- `merchant_id` String,
- `status` LowCardinality(String),
- `amount` UInt32,
- `currency` LowCardinality(Nullable(String)),
- `amount_captured` Nullable(UInt32),
- `customer_id` Nullable(String),
- `description` Nullable(String),
- `return_url` Nullable(String),
- `connector_id` LowCardinality(Nullable(String)),
- `statement_descriptor_name` Nullable(String),
- `statement_descriptor_suffix` Nullable(String),
- `setup_future_usage` LowCardinality(Nullable(String)),
- `off_session` Nullable(Bool),
- `client_secret` Nullable(String),
- `active_attempt_id` String,
- `business_country` LowCardinality(String),
- `business_label` String,
- `modified_at` DateTime64(3),
- `created_at` DateTime64(3),
- `last_synced` Nullable(DateTime64(3)),
- `inserted_at` DateTime64(3),
- `sign_flag` Int8
-) AS
-SELECT
- payment_id,
- merchant_id,
- status,
- amount,
- currency,
- amount_captured,
- customer_id,
- description,
- return_url,
- connector_id,
- statement_descriptor_name,
- statement_descriptor_suffix,
- setup_future_usage,
- off_session,
- client_secret,
- active_attempt_id,
- business_country,
- business_label,
- modified_at,
- created_at,
- last_synced,
- now() as inserted_at,
- sign_flag
-FROM hyperswitch.payment_intents_queue
-WHERE length(_error) = 0;
-
-CREATE MATERIALIZED VIEW hyperswitch.payment_intent_parse_errors on cluster '{cluster}'
-(
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-)
-ENGINE = MergeTree
-ORDER BY (topic, partition, offset)
-SETTINGS index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM hyperswitch.payment_intents_queue
-WHERE length(_error) > 0
-;
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql
deleted file mode 100644
index bf5f6e0e240..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/refund_analytics.sql
+++ /dev/null
@@ -1,173 +0,0 @@
-CREATE TABLE hyperswitch.refund_queue on cluster '{cluster}' (
- `internal_reference_id` String,
- `refund_id` String,
- `payment_id` String,
- `merchant_id` String,
- `connector_transaction_id` String,
- `connector` LowCardinality(Nullable(String)),
- `connector_refund_id` Nullable(String),
- `external_reference_id` Nullable(String),
- `refund_type` LowCardinality(String),
- `total_amount` Nullable(UInt32),
- `currency` LowCardinality(String),
- `refund_amount` Nullable(UInt32),
- `refund_status` LowCardinality(String),
- `sent_to_gateway` Bool,
- `refund_error_message` Nullable(String),
- `refund_arn` Nullable(String),
- `attempt_id` String,
- `description` Nullable(String),
- `refund_reason` Nullable(String),
- `refund_error_code` Nullable(String),
- `created_at` DateTime,
- `modified_at` DateTime,
- `sign_flag` Int8
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
-kafka_topic_list = 'hyperswitch-refund-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-CREATE TABLE hyperswitch.refund_dist on cluster '{cluster}' (
- `internal_reference_id` String,
- `refund_id` String,
- `payment_id` String,
- `merchant_id` String,
- `connector_transaction_id` String,
- `connector` LowCardinality(Nullable(String)),
- `connector_refund_id` Nullable(String),
- `external_reference_id` Nullable(String),
- `refund_type` LowCardinality(String),
- `total_amount` Nullable(UInt32),
- `currency` LowCardinality(String),
- `refund_amount` Nullable(UInt32),
- `refund_status` LowCardinality(String),
- `sent_to_gateway` Bool,
- `refund_error_message` Nullable(String),
- `refund_arn` Nullable(String),
- `attempt_id` String,
- `description` Nullable(String),
- `refund_reason` Nullable(String),
- `refund_error_code` Nullable(String),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8
-) ENGINE = Distributed('{cluster}', 'hyperswitch', 'refund_clustered', cityHash64(refund_id));
-
-
-
-CREATE TABLE hyperswitch.refund_clustered on cluster '{cluster}' (
- `internal_reference_id` String,
- `refund_id` String,
- `payment_id` String,
- `merchant_id` String,
- `connector_transaction_id` String,
- `connector` LowCardinality(Nullable(String)),
- `connector_refund_id` Nullable(String),
- `external_reference_id` Nullable(String),
- `refund_type` LowCardinality(String),
- `total_amount` Nullable(UInt32),
- `currency` LowCardinality(String),
- `refund_amount` Nullable(UInt32),
- `refund_status` LowCardinality(String),
- `sent_to_gateway` Bool,
- `refund_error_message` Nullable(String),
- `refund_arn` Nullable(String),
- `attempt_id` String,
- `description` Nullable(String),
- `refund_reason` Nullable(String),
- `refund_error_code` Nullable(String),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8,
- INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
- INDEX refundTypeIndex refund_type TYPE bloom_filter GRANULARITY 1,
- INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1,
- INDEX statusIndex refund_status TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedCollapsingMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/refund_clustered',
- '{replica}',
- sign_flag
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, refund_id)
-TTL created_at + toIntervalMonth(6)
-;
-
-CREATE MATERIALIZED VIEW hyperswitch.kafka_parse_refund on cluster '{cluster}' TO hyperswitch.refund_dist (
- `internal_reference_id` String,
- `refund_id` String,
- `payment_id` String,
- `merchant_id` String,
- `connector_transaction_id` String,
- `connector` LowCardinality(Nullable(String)),
- `connector_refund_id` Nullable(String),
- `external_reference_id` Nullable(String),
- `refund_type` LowCardinality(String),
- `total_amount` Nullable(UInt32),
- `currency` LowCardinality(String),
- `refund_amount` Nullable(UInt32),
- `refund_status` LowCardinality(String),
- `sent_to_gateway` Bool,
- `refund_error_message` Nullable(String),
- `refund_arn` Nullable(String),
- `attempt_id` String,
- `description` Nullable(String),
- `refund_reason` Nullable(String),
- `refund_error_code` Nullable(String),
- `created_at` DateTime64(3),
- `modified_at` DateTime64(3),
- `inserted_at` DateTime64(3),
- `sign_flag` Int8
-) AS
-SELECT
- internal_reference_id,
- refund_id,
- payment_id,
- merchant_id,
- connector_transaction_id,
- connector,
- connector_refund_id,
- external_reference_id,
- refund_type,
- total_amount,
- currency,
- refund_amount,
- refund_status,
- sent_to_gateway,
- refund_error_message,
- refund_arn,
- attempt_id,
- description,
- refund_reason,
- refund_error_code,
- created_at,
- modified_at,
- now() as inserted_at,
- sign_flag
-FROM hyperswitch.refund_queue
-WHERE length(_error) = 0;
-
-CREATE MATERIALIZED VIEW hyperswitch.refund_parse_errors on cluster '{cluster}'
-(
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-)
-ENGINE = MergeTree
-ORDER BY (topic, partition, offset)
-SETTINGS index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM hyperswitch.refund_queue
-WHERE length(_error) > 0
-;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql
deleted file mode 100644
index 37766392bc7..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/sdk_events.sql
+++ /dev/null
@@ -1,156 +0,0 @@
-CREATE TABLE hyperswitch.sdk_events_queue on cluster '{cluster}' (
- `payment_id` Nullable(String),
- `merchant_id` String,
- `remote_ip` Nullable(String),
- `log_type` LowCardinality(Nullable(String)),
- `event_name` LowCardinality(Nullable(String)),
- `first_event` LowCardinality(Nullable(String)),
- `latency` Nullable(UInt32),
- `timestamp` String,
- `browser_name` LowCardinality(Nullable(String)),
- `browser_version` Nullable(String),
- `platform` LowCardinality(Nullable(String)),
- `source` LowCardinality(Nullable(String)),
- `category` LowCardinality(Nullable(String)),
- `version` LowCardinality(Nullable(String)),
- `value` Nullable(String),
- `component` LowCardinality(Nullable(String)),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_experience` LowCardinality(Nullable(String))
-) ENGINE = Kafka SETTINGS
- kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092',
- kafka_topic_list = 'hyper-sdk-logs',
- kafka_group_name = 'hyper-c1',
- kafka_format = 'JSONEachRow',
- kafka_handle_error_mode = 'stream';
-
-CREATE TABLE hyperswitch.sdk_events_clustered on cluster '{cluster}' (
- `payment_id` Nullable(String),
- `merchant_id` String,
- `remote_ip` Nullable(String),
- `log_type` LowCardinality(Nullable(String)),
- `event_name` LowCardinality(Nullable(String)),
- `first_event` Bool DEFAULT 1,
- `browser_name` LowCardinality(Nullable(String)),
- `browser_version` Nullable(String),
- `platform` LowCardinality(Nullable(String)),
- `source` LowCardinality(Nullable(String)),
- `category` LowCardinality(Nullable(String)),
- `version` LowCardinality(Nullable(String)),
- `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` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4),
- `latency` Nullable(UInt32) DEFAULT 0,
- INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
- INDEX eventIndex event_name TYPE bloom_filter GRANULARITY 1,
- INDEX platformIndex platform TYPE bloom_filter GRANULARITY 1,
- INDEX logTypeIndex log_type TYPE bloom_filter GRANULARITY 1,
- INDEX categoryIndex category TYPE bloom_filter GRANULARITY 1,
- INDEX sourceIndex source TYPE bloom_filter GRANULARITY 1,
- INDEX componentIndex component TYPE bloom_filter GRANULARITY 1,
- INDEX firstEventIndex first_event TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/sdk_events_clustered', '{replica}'
-)
-PARTITION BY
- toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id)
-TTL
- toDateTime(created_at) + toIntervalMonth(6)
-SETTINGS
- index_granularity = 8192
-;
-
-CREATE TABLE hyperswitch.sdk_events_dist on cluster '{cluster}' (
- `payment_id` Nullable(String),
- `merchant_id` String,
- `remote_ip` Nullable(String),
- `log_type` LowCardinality(Nullable(String)),
- `event_name` LowCardinality(Nullable(String)),
- `first_event` Bool DEFAULT 1,
- `browser_name` LowCardinality(Nullable(String)),
- `browser_version` Nullable(String),
- `platform` LowCardinality(Nullable(String)),
- `source` LowCardinality(Nullable(String)),
- `category` LowCardinality(Nullable(String)),
- `version` LowCardinality(Nullable(String)),
- `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` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4),
- `latency` Nullable(UInt32) DEFAULT 0
-) ENGINE = Distributed(
- '{cluster}', 'hyperswitch', 'sdk_events_clustered', rand()
-);
-
-CREATE MATERIALIZED VIEW hyperswitch.sdk_events_mv on cluster '{cluster}' TO hyperswitch.sdk_events_dist (
- `payment_id` Nullable(String),
- `merchant_id` String,
- `remote_ip` Nullable(String),
- `log_type` LowCardinality(Nullable(String)),
- `event_name` LowCardinality(Nullable(String)),
- `first_event` Bool,
- `latency` Nullable(UInt32),
- `browser_name` LowCardinality(Nullable(String)),
- `browser_version` Nullable(String),
- `platform` LowCardinality(Nullable(String)),
- `source` LowCardinality(Nullable(String)),
- `category` LowCardinality(Nullable(String)),
- `version` LowCardinality(Nullable(String)),
- `value` Nullable(String),
- `component` LowCardinality(Nullable(String)),
- `payment_method` LowCardinality(Nullable(String)),
- `payment_experience` LowCardinality(Nullable(String)),
- `created_at` DateTime64(3)
-) AS
-SELECT
- payment_id,
- merchant_id,
- remote_ip,
- log_type,
- event_name,
- multiIf(first_event = 'true', 1, 0) AS first_event,
- latency,
- browser_name,
- browser_version,
- platform,
- source,
- category,
- version,
- value,
- component,
- payment_method,
- payment_experience,
- toDateTime64(timestamp, 3) AS created_at
-FROM
- hyperswitch.sdk_events_queue
-WHERE length(_error) = 0
-;
-
-CREATE MATERIALIZED VIEW hyperswitch.sdk_parse_errors on cluster '{cluster}' (
- `topic` String,
- `partition` Int64,
- `offset` Int64,
- `raw` String,
- `error` String
-) ENGINE = MergeTree
- ORDER BY (topic, partition, offset)
-SETTINGS
- index_granularity = 8192 AS
-SELECT
- _topic AS topic,
- _partition AS partition,
- _offset AS offset,
- _raw_message AS raw,
- _error AS error
-FROM
- hyperswitch.sdk_events_queue
-WHERE
- length(_error) > 0
-;
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql
deleted file mode 100644
index 202b94ac604..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/seed_scripts.sql
+++ /dev/null
@@ -1 +0,0 @@
-create database hyperswitch on cluster '{cluster}';
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/connector_events.sql b/crates/analytics/docs/clickhouse/scripts/connector_events.sql
index 4a53f9edb0b..47bbd7aec00 100644
--- a/crates/analytics/docs/clickhouse/scripts/connector_events.sql
+++ b/crates/analytics/docs/clickhouse/scripts/connector_events.sql
@@ -6,6 +6,7 @@ CREATE TABLE connector_events_queue (
`flow` LowCardinality(String),
`request` String,
`response` Nullable(String),
+ `masked_response` Nullable(String),
`error` Nullable(String),
`status_code` UInt32,
`created_at` DateTime64(3),
@@ -28,22 +29,23 @@ CREATE TABLE connector_events_dist (
`flow` LowCardinality(String),
`request` String,
`response` Nullable(String),
+ `masked_response` Nullable(String),
`error` Nullable(String),
`status_code` UInt32,
`created_at` DateTime64(3),
- `inserted_at` DateTime64(3),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`latency` UInt128,
`method` LowCardinality(String),
`refund_id` Nullable(String),
`dispute_id` Nullable(String),
- INDEX flowIndex flowTYPE bloom_filter GRANULARITY 1,
+ INDEX flowIndex flow TYPE bloom_filter GRANULARITY 1,
INDEX connectorIndex connector_name TYPE bloom_filter GRANULARITY 1,
INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1
) ENGINE = MergeTree
PARTITION BY toStartOfDay(created_at)
ORDER BY
- (created_at, merchant_id, flow_type, status_code, api_flow)
-TTL created_at + toIntervalMonth(6)
+ (created_at, merchant_id, connector_name, flow)
+TTL inserted_at + toIntervalMonth(6)
;
CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist (
@@ -54,6 +56,7 @@ CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist (
`flow` LowCardinality(String),
`request` String,
`response` Nullable(String),
+ `masked_response` Nullable(String),
`error` Nullable(String),
`status_code` UInt32,
`created_at` DateTime64(3),
@@ -70,6 +73,7 @@ SELECT
flow,
request,
response,
+ masked_response,
error,
status_code,
created_at,
diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs
index 47044811a8b..0a13074d729 100644
--- a/crates/analytics/src/connector_events/events.rs
+++ b/crates/analytics/src/connector_events/events.rs
@@ -62,6 +62,7 @@ pub struct ConnectorEventsResult {
pub request_id: Option<String>,
pub flow: String,
pub request: String,
+ #[serde(rename = "masked_response")]
pub response: Option<String>,
pub error: Option<String>,
pub status_code: u16,
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs
index bbb88209b27..b20b27f0228 100644
--- a/crates/router/src/connector/aci.rs
+++ b/crates/router/src/connector/aci.rs
@@ -11,6 +11,7 @@ use super::utils::PaymentsAuthorizeRequestData;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -58,11 +59,14 @@ impl ConnectorCommon for Aci {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: aci::AciErrorResponse = res
.response
.parse_struct("AciErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response.result.code,
@@ -221,6 +225,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError>
where
@@ -231,6 +236,8 @@ impl
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -242,8 +249,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -335,12 +343,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: aci::AciPaymentsResponse =
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -352,8 +363,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -422,12 +434,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: aci::AciPaymentsResponse =
res.response
.parse_struct("AciPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -439,8 +454,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -522,12 +538,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: aci::AciRefundResponse = res
.response
.parse_struct("AciRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -538,8 +558,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 92c7e164c4c..ed56fc5f524 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -653,7 +653,7 @@ impl FromStr for AciPaymentStatus {
}
}
-#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
@@ -666,7 +666,7 @@ pub struct AciPaymentsResponse {
pub(super) redirect: Option<AciRedirectionData>,
}
-#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciErrorResponse {
ndc: String,
@@ -675,7 +675,7 @@ pub struct AciErrorResponse {
pub(super) result: ResultCode,
}
-#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRedirectionData {
method: Option<services::Method>,
@@ -683,13 +683,13 @@ pub struct AciRedirectionData {
url: Url,
}
-#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
name: String,
value: String,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultCode {
pub(super) code: String,
@@ -697,7 +697,7 @@ pub struct ResultCode {
pub(super) parameter_errors: Option<Vec<ErrorParameters>>,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
@@ -824,7 +824,7 @@ impl From<AciRefundStatus> for enums::RefundStatus {
}
#[allow(dead_code)]
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRefundResponse {
id: String,
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index fa9a5617ffb..554de564b68 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -16,6 +16,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -61,11 +62,16 @@ impl ConnectorCommon for Adyen {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: adyen::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response.error_code,
@@ -207,6 +213,7 @@ impl
fn handle_response(
&self,
data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
@@ -225,6 +232,8 @@ impl
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -240,19 +249,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
}
@@ -338,13 +337,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: adyen::AdyenCaptureResponse = res
.response
.parse_struct("AdyenCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -355,19 +356,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("adyen::ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
}
@@ -488,6 +479,7 @@ impl
fn handle_response(
&self,
data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
logger::debug!(payment_sync_response=?res);
@@ -495,6 +487,8 @@ impl
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
let is_multiple_capture_sync = match data.request.sync_type {
types::SyncRequestType::MultipleCaptureSync(_) => true,
types::SyncRequestType::SinglePaymentSync => false,
@@ -515,19 +509,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
fn get_multiple_capture_sync_method(
@@ -615,12 +599,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: adyen::AdyenPaymentResponse = res
.response
.parse_struct("AdyenPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -637,19 +624,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
}
@@ -724,12 +701,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: adyen::AdyenBalanceResponse = res
.response
.parse_struct("AdyenBalanceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
let currency = match data.request.currency {
Some(currency) => currency,
@@ -769,8 +749,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -840,12 +821,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: adyen::AdyenCancelResponse = res
.response
.parse_struct("AdyenCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -857,19 +841,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
}
@@ -950,12 +924,15 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCancel>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -966,8 +943,9 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1039,12 +1017,15 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCreate>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1055,8 +1036,9 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1133,12 +1115,15 @@ impl
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoEligibility>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoEligibility>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1149,8 +1134,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1239,12 +1225,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoFulfill>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
let response: adyen::AdyenPayoutResponse = res
.response
.parse_struct("AdyenPayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1255,8 +1244,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1336,12 +1326,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: adyen::AdyenRefundResponse = res
.response
.parse_struct("AdyenRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1353,19 +1346,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: adyen::ErrorResponse = res
- .response
- .parse_struct("ErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
- status_code: res.status_code,
- code: response.error_code,
- message: response.message,
- reason: None,
- attempt_status: None,
- connector_transaction_id: None,
- })
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 0d8343b0c86..a79826e2f19 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -208,7 +208,7 @@ pub struct AdyenBalanceRequest<'a> {
pub merchant_account: Secret<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBalanceResponse {
pub psp_reference: String,
@@ -297,7 +297,7 @@ pub struct AdyenThreeDS {
pub result_code: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum AdyenPaymentResponse {
Response(Box<Response>),
@@ -328,7 +328,7 @@ pub struct RedirectionErrorResponse {
refusal_reason: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionResponse {
result_code: AdyenStatus,
@@ -337,7 +337,7 @@ pub struct RedirectionResponse {
refusal_reason_code: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PresentToShopperResponse {
psp_reference: Option<String>,
@@ -347,7 +347,7 @@ pub struct PresentToShopperResponse {
refusal_reason_code: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QrCodeResponseResponse {
result_code: AdyenStatus,
@@ -1077,14 +1077,14 @@ pub struct AdyenCancelRequest {
reference: String,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCancelResponse {
psp_reference: String,
status: CancelStatus,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CancelStatus {
Received,
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index 19d69b688c9..103c5852ac4 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -18,6 +18,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers, logger, routes,
services::{
self,
@@ -83,6 +84,7 @@ impl ConnectorCommon for Airwallex {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
logger::debug!(payu_error_response=?res);
let response: airwallex::AirwallexErrorResponse = res
@@ -90,6 +92,9 @@ impl ConnectorCommon for Airwallex {
.parse_struct("Airwallex ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
@@ -205,6 +210,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
logger::debug!(access_token_response=?res);
@@ -213,6 +219,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("airwallex AirwallexAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -225,9 +234,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- logger::debug!(access_token_error_response=?res);
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -292,13 +301,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsInitRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> {
let response: airwallex::AirwallexPaymentsResponse = res
.response
.parse_struct("airwallex AirwallexPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(nuvei_session_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -311,8 +324,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -420,13 +434,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: airwallex::AirwallexPaymentsResponse = res
.response
.parse_struct("AirwallexPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(airwallexpayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -439,8 +455,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -496,6 +513,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
logger::debug!(payment_sync_response=?res);
@@ -503,6 +521,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("airwallex AirwallexPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::PaymentsSyncRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -514,8 +534,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -584,12 +605,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: airwallex::AirwallexPaymentsResponse = res
.response
.parse_struct("AirwallexPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -601,8 +625,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -669,13 +694,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: airwallex::AirwallexPaymentsResponse = res
.response
.parse_struct("Airwallex PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(airwallexpayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -688,8 +715,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -743,13 +771,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: airwallex::AirwallexPaymentsResponse = res
.response
.parse_struct("Airwallex PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(airwallexpayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -780,8 +810,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -853,6 +884,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
logger::debug!(target: "router::connector::airwallex", response=?res);
@@ -860,6 +892,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("airwallex RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -872,8 +906,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -923,6 +958,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
logger::debug!(target: "router::connector::airwallex", response=?res);
@@ -930,6 +966,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("airwallex RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -942,8 +980,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 2de7f6fe00f..692458715f7 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -259,7 +259,7 @@ fn get_wallet_details(
Ok(wallet_details)
}
-#[derive(Deserialize)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct AirwallexAuthUpdateResponse {
#[serde(with = "common_utils::custom_serde::iso8601")]
expires_at: PrimitiveDateTime,
@@ -368,7 +368,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelReques
}
// PaymentsResponse
-#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AirwallexPaymentStatus {
Succeeded,
@@ -413,7 +413,7 @@ pub enum AirwallexNextActionStage {
WaitingUserInfoInput,
}
-#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexRedirectFormData {
#[serde(rename = "JWT")]
jwt: Option<String>,
@@ -424,7 +424,7 @@ pub struct AirwallexRedirectFormData {
version: Option<String>,
}
-#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsNextAction {
url: Url,
method: services::Method,
@@ -432,7 +432,7 @@ pub struct AirwallexPaymentsNextAction {
stage: AirwallexNextActionStage,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsResponse {
status: AirwallexPaymentStatus,
//Unique identifier for the PaymentIntent
@@ -443,7 +443,7 @@ pub struct AirwallexPaymentsResponse {
next_action: Option<AirwallexPaymentsNextAction>,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct AirwallexPaymentsSyncResponse {
status: AirwallexPaymentStatus,
//Unique identifier for the PaymentIntent
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 0686ee6a3b8..e8ef9195d02 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -15,6 +15,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
@@ -196,6 +197,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
use bytes::Buf;
@@ -209,7 +211,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -220,8 +223,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -279,6 +283,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
use bytes::Buf;
@@ -292,7 +297,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response
.parse_struct("AuthorizedotnetSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -303,8 +309,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -378,6 +385,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
@@ -391,6 +399,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -401,8 +411,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -459,6 +470,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
use bytes::Buf;
@@ -472,7 +484,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
let response: authorizedotnet::AuthorizedotnetVoidResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -483,8 +496,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -554,6 +568,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
use bytes::Buf;
@@ -567,7 +582,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
let response: authorizedotnet::AuthorizedotnetRefundResponse = intermediate_response
.parse_struct("AuthorizedotnetRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -578,8 +594,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -644,6 +661,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundsRouterData<api::RSync>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
use bytes::Buf;
@@ -657,6 +675,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response
.parse_struct("AuthorizedotnetSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -667,8 +687,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -742,6 +763,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
@@ -755,7 +777,8 @@ impl
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = intermediate_response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -766,8 +789,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- get_error_response(res)
+ get_error_response(res, event_builder)
}
}
@@ -873,11 +897,15 @@ fn get_error_response(
status_code,
..
}: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
match response.transaction_response {
Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponse(
payment_response,
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 96cf3b6ffc5..3377457f38a 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -388,7 +388,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>>
}
}
-#[derive(Debug, Clone, Default, serde::Deserialize)]
+#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub enum AuthorizedotnetPaymentStatus {
#[serde(rename = "1")]
Approved,
@@ -403,7 +403,7 @@ pub enum AuthorizedotnetPaymentStatus {
RequiresAction,
}
-#[derive(Debug, Clone, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Deserialize, Serialize)]
pub enum AuthorizedotnetRefundStatus {
#[serde(rename = "1")]
Approved,
@@ -448,27 +448,27 @@ pub struct ResponseMessages {
pub message: Vec<ResponseMessage>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorMessage {
pub error_code: String,
pub error_text: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TransactionResponse {
AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>),
AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AuthorizedotnetTransactionResponseError {
_supplemental_data_qualification_indicator: i64,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
@@ -480,7 +480,7 @@ pub struct AuthorizedotnetTransactionResponse {
secure_acceptance: Option<SecureAcceptance>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
response_code: AuthorizedotnetRefundStatus,
@@ -492,27 +492,27 @@ pub struct RefundResponse {
pub errors: Option<Vec<ErrorMessage>>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct SecureAcceptance {
secure_acceptance_url: Option<url::Url>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsResponse {
pub transaction_response: Option<TransactionResponse>,
pub messages: ResponseMessages,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetVoidResponse {
pub transaction_response: Option<VoidResponse>,
pub messages: ResponseMessages,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
response_code: AuthorizedotnetVoidStatus,
@@ -523,7 +523,7 @@ pub struct VoidResponse {
pub errors: Option<Vec<ErrorMessage>>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AuthorizedotnetVoidStatus {
#[serde(rename = "1")]
Approved,
@@ -773,7 +773,7 @@ impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundResponse {
pub transaction_response: RefundResponse,
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index 37c6ae6cd6b..df078e895d0 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -18,7 +18,8 @@ use crate::{
errors::{self, CustomResult},
payments,
},
- headers, logger,
+ events::connector_api_logs::ConnectorEvent,
+ headers,
services::{
self,
request::{self, Mask},
@@ -85,12 +86,16 @@ impl ConnectorCommon for Bambora {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bambora::BamboraErrorResponse = res
.response
.parse_struct("BamboraErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
@@ -215,12 +220,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -235,8 +243,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -299,19 +308,23 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -384,13 +397,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(bamborapayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -405,8 +420,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -478,13 +494,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(bamborapayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -499,8 +518,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -569,12 +589,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RefundsRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -586,8 +609,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -637,12 +661,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora 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 {
response,
data: data.clone(),
@@ -654,8 +681,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -774,13 +802,16 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(bamborapayments_create_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from((
types::ResponseRouterData {
response,
@@ -795,7 +826,8 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 8f18ca272dd..d2c99bbaca0 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -272,14 +272,14 @@ where
Ok(res)
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BamboraResponse {
NormalTransaction(Box<BamboraPaymentsResponse>),
ThreeDsResponse(Box<Bambora3DsResponse>),
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct BamboraPaymentsResponse {
#[serde(deserialize_with = "str_or_i32")]
id: String,
@@ -309,7 +309,7 @@ pub struct BamboraPaymentsResponse {
risk_score: Option<f32>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Bambora3DsResponse {
#[serde(rename = "3d_session_data")]
three_d_session_data: String,
@@ -332,7 +332,7 @@ pub struct CardResponse {
pub(crate) cres: Option<common_utils::pii::SecretSerdeValue>,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct CardData {
name: Option<String>,
expiry_month: Option<String>,
@@ -466,7 +466,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
#[serde(deserialize_with = "str_or_i32")]
pub id: String,
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs
index 589852c6b56..8a72e65f976 100644
--- a/crates/router/src/connector/bankofamerica.rs
+++ b/crates/router/src/connector/bankofamerica.rs
@@ -18,6 +18,7 @@ use crate::{
connector::{utils as connector_utils, utils::RefundsRequestData},
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -197,12 +198,16 @@ impl ConnectorCommon for Bankofamerica {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaErrorResponse = res
.response
.parse_struct("BankOfAmerica ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_message = if res.status_code == 401 {
consts::CONNECTOR_UNAUTHORIZED_ERROR
} else {
@@ -390,12 +395,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaPreProcessingResponse = res
.response
.parse_struct("BankOfAmerica 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 {
response,
data: data.clone(),
@@ -406,8 +414,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -488,6 +497,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
if data.is_three_ds() && data.request.is_card() {
@@ -495,6 +505,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Bankofamerica AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -505,6 +517,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.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 {
response,
data: data.clone(),
@@ -516,18 +530,24 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
@@ -612,12 +632,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, 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 {
response,
data: data.clone(),
@@ -628,18 +651,24 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
@@ -713,12 +742,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -729,8 +761,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -800,12 +833,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -816,19 +852,24 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
@@ -915,12 +956,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -931,19 +975,24 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaServerErrorResponse = res
.response
.parse_struct("BankOfAmericaServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
@@ -1022,12 +1071,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaRefundResponse = res
.response
.parse_struct("bankofamerica 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 {
response,
data: data.clone(),
@@ -1038,8 +1090,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1092,12 +1145,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -1108,8 +1164,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 0b8158c10af..de53b991d89 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -427,13 +427,13 @@ pub struct ClientProcessorInformation {
avs: Option<Avs>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: String,
}
@@ -825,7 +825,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaPaymentStatus {
Authorized,
@@ -886,7 +886,7 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformationResponse {
access_token: String,
@@ -894,7 +894,7 @@ pub struct BankOfAmericaConsumerAuthInformationResponse {
reference_id: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthSetupInfoResponse {
id: String,
@@ -902,21 +902,21 @@ pub struct ClientAuthSetupInfoResponse {
consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaAuthSetupResponse {
ClientAuthSetupInfo(ClientAuthSetupInfoResponse),
ErrorInformation(BankOfAmericaErrorInformationResponse),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaPaymentsResponse {
ClientReferenceInformation(BankOfAmericaClientReferenceResponse),
ErrorInformation(BankOfAmericaErrorInformationResponse),
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaClientReferenceResponse {
id: String,
@@ -927,14 +927,14 @@ pub struct BankOfAmericaClientReferenceResponse {
error_information: Option<BankOfAmericaErrorInformation>,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaErrorInformationResponse {
id: String,
error_information: BankOfAmericaErrorInformation,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BankOfAmericaErrorInformation {
reason: Option<String>,
message: Option<String>,
@@ -1310,7 +1310,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterDat
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankOfAmericaAuthEnrollmentStatus {
PendingAuthentication,
@@ -1334,7 +1334,7 @@ pub struct BankOfAmericaThreeDSMetadata {
three_ds_data: BankOfAmericaConsumerAuthValidateResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse {
access_token: Option<String>,
@@ -1344,7 +1344,7 @@ pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse {
validate_response: BankOfAmericaConsumerAuthValidateResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
@@ -1354,7 +1354,7 @@ pub struct ClientAuthCheckInfoResponse {
error_information: Option<BankOfAmericaErrorInformation>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaPreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
@@ -1644,14 +1644,14 @@ impl<F>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaTransactionResponse {
ApplicationInformation(BankOfAmericaApplicationInfoResponse),
ErrorInformation(BankOfAmericaErrorInformationResponse),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaApplicationInfoResponse {
id: String,
@@ -1660,7 +1660,7 @@ pub struct BankOfAmericaApplicationInfoResponse {
error_information: Option<BankOfAmericaErrorInformation>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: BankofamericaPaymentStatus,
@@ -1879,7 +1879,7 @@ impl From<BankofamericaRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRefundResponse {
id: String,
@@ -1903,7 +1903,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundR
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankofamericaRefundStatus {
Succeeded,
@@ -1913,13 +1913,13 @@ pub enum BankofamericaRefundStatus {
Voided,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: BankofamericaRefundStatus,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaRsyncResponse {
id: String,
@@ -1945,7 +1945,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
@@ -1955,7 +1955,7 @@ pub struct BankOfAmericaStandardErrorResponse {
pub details: Option<Vec<Details>>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaServerErrorResponse {
pub status: Option<String>,
@@ -1963,7 +1963,7 @@ pub struct BankOfAmericaServerErrorResponse {
pub reason: Option<Reason>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
@@ -1971,32 +1971,32 @@ pub enum Reason {
ServiceTimeout,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct BankOfAmericaAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BankOfAmericaErrorResponse {
AuthenticationError(BankOfAmericaAuthenticationErrorResponse),
StandardError(BankOfAmericaStandardErrorResponse),
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs
index 4a8108d04b8..61e8cb03a27 100644
--- a/crates/router/src/connector/bitpay.rs
+++ b/crates/router/src/connector/bitpay.rs
@@ -12,6 +12,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -109,10 +110,14 @@ impl ConnectorCommon for Bitpay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: bitpay::BitpayErrorResponse =
res.response.parse_struct("BitpayErrorResponse").switch()?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response
@@ -226,12 +231,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("Bitpay PaymentsAuthorizeResponse")
.switch()?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -242,8 +250,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -300,12 +309,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: bitpay::BitpayPaymentsResponse = res
.response
.parse_struct("bitpay PaymentsSyncResponse")
.switch()?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -316,8 +328,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index 0ddf2dbf913..148a5a45636 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -266,7 +266,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct BitpayErrorResponse {
pub error: String,
pub code: Option<String>,
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
index e54d8320d0f..824a073136f 100644
--- a/crates/router/src/connector/bluesnap.rs
+++ b/crates/router/src/connector/bluesnap.rs
@@ -24,6 +24,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -96,13 +97,16 @@ impl ConnectorCommon for Bluesnap {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
logger::debug!(bluesnap_error_response=?res);
let response: bluesnap::BluesnapErrors = res
.response
.parse_struct("BluesnapErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
let response_error_message = match response {
bluesnap::BluesnapErrors::Payment(error_response) => {
@@ -307,12 +311,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -325,8 +331,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -399,19 +406,22 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -487,12 +497,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("Bluesnap BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -505,8 +517,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -572,13 +585,15 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsSessionRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapWalletTokenResponse = res
.response
.parse_struct("BluesnapWalletTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(connector_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -589,8 +604,9 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -681,6 +697,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
match (data.is_three_ds() && data.request.is_card(), res.headers) {
@@ -692,6 +709,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
+
+ let response =
+ serde_json::json!({"payment_fields_token": payment_fields_token.clone()});
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::RouterData {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -713,6 +737,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -726,8 +751,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -799,12 +825,14 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -817,8 +845,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -891,12 +920,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: bluesnap::RefundResponse = res
.response
.parse_struct("bluesnap 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 {
response,
@@ -909,8 +940,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -974,12 +1006,14 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: bluesnap::BluesnapPaymentsResponse = res
.response
.parse_struct("bluesnap BluesnapPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -992,8 +1026,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index e98b98e874a..f1c27d72749 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -926,14 +926,14 @@ impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapR
}
}
-#[derive(Debug, Clone, Default, Deserialize)]
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapRefundStatus {
Success,
#[default]
Pending,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_transaction_id: i32,
@@ -1122,13 +1122,13 @@ pub struct ErrorDetails {
pub error_name: Option<String>,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapErrorResponse {
pub message: Vec<ErrorDetails>,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapAuthErrorResponse {
pub error_code: String,
@@ -1136,7 +1136,7 @@ pub struct BluesnapAuthErrorResponse {
pub error_name: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BluesnapErrors {
Payment(BluesnapErrorResponse),
diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rs
index 39566e08d47..7b470593e7f 100644
--- a/crates/router/src/connector/boku.rs
+++ b/crates/router/src/connector/boku.rs
@@ -15,6 +15,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
routes::metrics,
services::{
@@ -117,6 +118,7 @@ impl ConnectorCommon for Boku {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response_data: Result<boku::BokuErrorResponse, Report<errors::ConnectorError>> = res
.response
@@ -124,15 +126,19 @@ impl ConnectorCommon for Boku {
.change_context(errors::ConnectorError::ResponseDeserializationFailed);
match response_data {
- Ok(response) => Ok(ErrorResponse {
- status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
- attempt_status: None,
- connector_transaction_id: None,
- }),
- Err(_) => get_xml_deserialized(res),
+ Ok(response) => {
+ 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,
+ })
+ }
+ Err(_) => get_xml_deserialized(res, event_builder),
}
}
}
@@ -252,6 +258,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
@@ -262,7 +269,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.parse_xml::<boku::BokuResponse>()
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -273,8 +281,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -336,6 +345,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
@@ -346,7 +356,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.parse_xml::<boku::BokuResponse>()
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -357,8 +368,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -416,6 +428,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
@@ -426,7 +439,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.parse_xml::<boku::BokuResponse>()
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -437,8 +451,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -504,12 +519,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: boku::RefundResponse = res
.response
.parse_struct("boku RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -520,8 +540,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -581,12 +602,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: boku::BokuRsyncResponse = res
.response
.parse_struct("boku BokuRsyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -597,8 +621,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -638,7 +663,10 @@ fn get_country_url(
}
// validate xml format for the error
-fn get_xml_deserialized(res: Response) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+fn get_xml_deserialized(
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+) -> CustomResult<ErrorResponse, errors::ConnectorError> {
metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
&metrics::CONTEXT,
1,
@@ -649,6 +677,9 @@ fn get_xml_deserialized(res: Response) -> CustomResult<ErrorResponse, errors::Co
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response_data));
+ router_env::logger::info!(connector_response=?response_data);
+
// check for whether the response is in xml format
match roxmltree::Document::parse(&response_data) {
// in case of unexpected response but in xml format
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index 6d830f85110..5f36225fd40 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -225,14 +225,14 @@ pub struct BokuMetaData {
pub(super) country: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuResponse {
BeginSingleChargeResponse(BokuPaymentsResponse),
QueryChargeResponse(BokuPsyncResponse),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct BokuPaymentsResponse {
charge_status: String, // xml parse only string to fields
@@ -240,26 +240,26 @@ pub struct BokuPaymentsResponse {
hosted: Option<HostedUrlResponse>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct HostedUrlResponse {
redirect_url: Option<Url>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-charge-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncResponse {
charges: ChargeResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ChargeResponseData {
charge: SingleChargeResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeResponseData {
charge_status: String,
@@ -368,7 +368,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for BokuRefundRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "refund-charge-response")]
pub struct RefundResponse {
charge_id: String,
@@ -424,20 +424,20 @@ impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-refund-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncResponse {
refunds: RefundResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RefundResponseData {
refund: SingleRefundResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleRefundResponseData {
refund_status: String, // quick-xml only parse string as a field
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 4f2686abb13..629a9661033 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -20,6 +20,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -103,12 +104,16 @@ impl ConnectorCommon for Braintree {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<braintree::ErrorResponse, Report<common_utils::errors::ParsingError>> =
res.response.parse_struct("Braintree Error Response");
match response {
Ok(braintree::ErrorResponse::BraintreeApiErrorResponse(response)) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_object = response.api_error_response.errors;
let error = error_object.errors.first().or(error_object
.transaction
@@ -135,15 +140,21 @@ impl ConnectorCommon for Braintree {
connector_transaction_id: None,
})
}
- Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => Ok(ErrorResponse {
- status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
- message: consts::NO_ERROR_MESSAGE.to_string(),
- reason: Some(response.errors),
- attempt_status: None,
- connector_transaction_id: None,
- }),
+ Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => {
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: consts::NO_ERROR_MESSAGE.to_string(),
+ reason: Some(response.errors),
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
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})));
logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "braintree".to_owned())
}
@@ -256,8 +267,9 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_request_body(
@@ -272,12 +284,15 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsSessionRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
let response: braintree::BraintreeSessionTokenResponse = res
.response
.parse_struct("braintree SessionTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -355,6 +370,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -364,6 +380,8 @@ impl
.response
.parse_struct("BraintreeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -374,8 +392,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -505,12 +524,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: braintree_graphql_transformers::BraintreeCaptureResponse = res
.response
.parse_struct("Braintree PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -521,8 +543,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -646,6 +669,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let connector_api_version = &data.connector_api_version;
@@ -655,6 +679,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("Braintree 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 {
response,
data: data.clone(),
@@ -666,6 +692,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -678,8 +706,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -796,6 +825,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let connector_api_version = &data.connector_api_version;
@@ -806,6 +836,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -817,6 +849,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -829,6 +863,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -841,8 +877,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -947,6 +984,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let connector_api_version = &data.connector_api_version;
@@ -956,6 +994,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.response
.parse_struct("Braintree VoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -967,6 +1007,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.response
.parse_struct("Braintree PaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -979,8 +1021,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1103,6 +1146,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let connector_api_version = &data.connector_api_version;
@@ -1112,6 +1156,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("Braintree 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 {
response,
data: data.clone(),
@@ -1123,6 +1169,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("Braintree 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 {
response,
data: data.clone(),
@@ -1135,8 +1183,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1221,6 +1270,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
@@ -1233,6 +1283,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("Braintree 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 {
response,
data: data.clone(),
@@ -1244,6 +1296,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("Braintree 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 {
response,
data: data.clone(),
@@ -1255,8 +1309,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1626,6 +1681,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
match connector_utils::PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)?
@@ -1635,6 +1691,7 @@ impl
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -1647,6 +1704,8 @@ impl
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1659,7 +1718,8 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index e0baf034f72..436cd8dfa36 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -182,12 +182,12 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthResponse {
data: DataAuthResponse,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeAuthResponse {
AuthResponse(Box<AuthResponse>),
@@ -195,26 +195,26 @@ pub enum BraintreeAuthResponse {
ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCompleteAuthResponse {
AuthResponse(Box<AuthResponse>),
ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TransactionAuthChargeResponseBody {
id: String,
status: BraintreePaymentStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataAuthResponse {
authorize_credit_card: AuthChargeCreditCard,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthChargeCreditCard {
transaction: TransactionAuthChargeResponseBody,
}
@@ -351,7 +351,7 @@ fn get_error_response<T>(
// }
// }
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreePaymentStatus {
Authorized,
@@ -369,13 +369,13 @@ pub enum BraintreePaymentStatus {
SubmittedForSettlement,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ErrorDetails {
pub message: String,
pub extensions: Option<AdditionalErrorDetails>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalErrorDetails {
pub legacy_code: Option<String>,
@@ -553,12 +553,12 @@ impl<F>
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaymentsResponse {
data: DataResponse,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreePaymentsResponse {
PaymentsResponse(Box<PaymentsResponse>),
@@ -566,14 +566,14 @@ pub enum BraintreePaymentsResponse {
ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCompleteChargeResponse {
PaymentsResponse(Box<PaymentsResponse>),
ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataResponse {
charge_credit_card: AuthChargeCreditCard,
@@ -633,7 +633,7 @@ impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for Braintree
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreeRefundStatus {
SettlementPending,
@@ -654,30 +654,30 @@ impl From<BraintreeRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BraintreeRefundTransactionBody {
pub id: String,
pub status: BraintreeRefundStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BraintreeRefundTransaction {
pub refund: BraintreeRefundTransactionBody,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeRefundResponseData {
pub refund_transaction: BraintreeRefundTransaction,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
pub data: BraintreeRefundResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeRefundResponse {
RefundResponse(Box<RefundResponse>),
@@ -733,38 +733,38 @@ impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncNodeData {
id: String,
status: BraintreeRefundStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncEdgeData {
node: RSyncNodeData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RefundData {
edges: Vec<RSyncEdgeData>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncSearchData {
refunds: RefundData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncResponseData {
search: RSyncSearchData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RSyncResponse {
data: RSyncResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeRSyncResponse {
RSyncResponse(Box<RSyncResponse>),
@@ -897,51 +897,51 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct TokenizePaymentMethodData {
id: String,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizeCreditCardData {
payment_method: TokenizePaymentMethodData,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientToken {
client_token: Secret<String>,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizeCreditCard {
tokenize_credit_card: TokenizeCreditCardData,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientTokenData {
create_client_token: ClientToken,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ClientTokenResponse {
data: ClientTokenData,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct TokenResponse {
data: TokenizeCreditCard,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ErrorResponse {
errors: Vec<ErrorDetails>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeTokenResponse {
TokenResponse(Box<TokenResponse>),
@@ -1020,29 +1020,29 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for Braint
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureResponseTransactionBody {
id: String,
status: BraintreePaymentStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureTransactionData {
transaction: CaptureResponseTransactionBody,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureResponseData {
capture_transaction: CaptureTransactionData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CaptureResponse {
data: CaptureResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCaptureResponse {
CaptureResponse(Box<CaptureResponse>),
@@ -1112,29 +1112,29 @@ impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelResponseTransactionBody {
id: String,
status: BraintreePaymentStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelTransactionData {
reversal: CancelResponseTransactionBody,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelResponseData {
reverse_transaction: CancelTransactionData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CancelResponse {
data: CancelResponseData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCancelResponse {
CancelResponse(Box<CancelResponse>),
@@ -1194,40 +1194,40 @@ impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NodeData {
id: String,
status: BraintreePaymentStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EdgeData {
node: NodeData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TransactionData {
edges: Vec<EdgeData>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SearchData {
transactions: TransactionData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PSyncResponseData {
search: SearchData,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreePSyncResponse {
PSyncResponse(Box<PSyncResponse>),
ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PSyncResponse {
data: PSyncResponseData,
}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index f4bd62add3b..8846753117c 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -178,7 +178,7 @@ impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
}
}
-#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq)]
+#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BraintreePaymentStatus {
Succeeded,
@@ -272,25 +272,25 @@ impl<F, T>
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreePaymentsResponse {
transaction: TransactionResponse,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientToken {
pub value: String,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeSessionTokenResponse {
pub client_token: ClientToken,
}
-#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionResponse {
id: String,
@@ -299,42 +299,42 @@ pub struct TransactionResponse {
status: BraintreePaymentStatus,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeApiErrorResponse {
pub api_error_response: ApiErrorResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorsObject {
pub errors: Vec<ErrorObject>,
pub transaction: Option<TransactionError>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionError {
pub errors: Vec<ErrorObject>,
pub credit_card: Option<CreditCardError>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CreditCardError {
pub errors: Vec<ErrorObject>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorObject {
pub code: String,
pub message: String,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeErrorResponse {
pub errors: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
@@ -343,7 +343,7 @@ pub enum ErrorResponse {
BraintreeErrorResponse(Box<BraintreeErrorResponse>),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ApiErrorResponse {
pub message: String,
pub errors: ErrorsObject,
@@ -378,7 +378,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest {
}
#[allow(dead_code)]
-#[derive(Debug, Default, Deserialize, Clone)]
+#[derive(Debug, Default, Deserialize, Clone, Serialize)]
pub enum RefundStatus {
Succeeded,
Failed,
@@ -396,7 +396,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs
index 5a628f775b6..127451f3836 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/router/src/connector/cashtocode.rs
@@ -12,6 +12,7 @@ use super::utils as connector_utils;
use crate::{
configs::settings::{self},
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -109,11 +110,16 @@ impl ConnectorCommon for Cashtocode {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cashtocode::CashtocodeErrorResponse = res
.response
.parse_struct("CashtocodeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.to_string(),
@@ -249,12 +255,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode 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 {
response,
data: data.clone(),
@@ -265,8 +275,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -277,12 +288,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -293,8 +307,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs
index 8a92956756a..6e930d5cb4b 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/router/src/connector/cashtocode/transformers.rs
@@ -168,7 +168,7 @@ impl From<CashtocodePaymentStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
pub message: String,
pub path: String,
@@ -176,20 +176,20 @@ pub struct CashtocodeErrors {
pub event_type: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
CashtoCodeError(CashtocodeErrorResponse),
CashtoCodeData(CashtocodePaymentsResponseData),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
pub pay_url: url::Url,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
pub transaction_id: String,
@@ -319,7 +319,7 @@ impl<F, T>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
pub error: serde_json::Value,
pub error_description: String,
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 382737a28f6..ea2c4fefd30 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -19,6 +19,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -89,6 +90,7 @@ impl ConnectorCommon for Checkout {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: checkout::ErrorResponse = if res.response.is_empty() {
let (error_codes, error_type) = if res.status_code == 401 {
@@ -110,7 +112,9 @@ impl ConnectorCommon for Checkout {
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
};
- router_env::logger::info!(error_response=?response);
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let errors_list = response.error_codes.clone().unwrap_or_default();
let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority(
self.clone(),
@@ -237,6 +241,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -246,8 +251,8 @@ impl
.response
.parse_struct("CheckoutTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
-
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -259,8 +264,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -362,14 +368,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: checkout::PaymentCaptureResponse = res
.response
.parse_struct("CaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
-
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -381,8 +388,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -436,6 +444,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError>
where
@@ -449,6 +458,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("checkout::PaymentsResponseEnum")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -462,6 +472,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -482,8 +493,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -549,12 +561,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -567,8 +581,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -624,14 +639,18 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let mut response: checkout::PaymentVoidResponse = res
.response
.parse_struct("PaymentVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+
response.status = res.status_code;
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -643,8 +662,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -717,12 +737,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: checkout::RefundResponse = res
.response
.parse_struct("checkout::RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response = checkout::CheckoutRefundResponse {
response,
@@ -740,8 +762,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -785,6 +808,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundsRouterData<api::RSync>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
let refund_action_id = data.request.get_connector_refund_id()?;
@@ -793,6 +817,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("checkout::CheckoutRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response = response
@@ -811,8 +837,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -870,6 +897,7 @@ impl
fn handle_response(
&self,
data: &types::AcceptDisputeRouterData,
+ _event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<types::AcceptDisputeRouterData, errors::ConnectorError> {
Ok(types::AcceptDisputeRouterData {
@@ -884,8 +912,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -983,6 +1012,7 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
fn handle_response(
&self,
data: &types::UploadFileRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>,
@@ -992,6 +1022,7 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
.response
.parse_struct("Checkout FileUploadResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::UploadFileRouterData {
response: Ok(types::UploadFileResponse {
@@ -1004,8 +1035,9 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1077,6 +1109,7 @@ impl
fn handle_response(
&self,
data: &types::SubmitEvidenceRouterData,
+ _event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> {
Ok(types::SubmitEvidenceRouterData {
@@ -1091,8 +1124,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1148,6 +1182,7 @@ impl
fn handle_response(
&self,
data: &types::DefendDisputeRouterData,
+ _event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<types::DefendDisputeRouterData, errors::ConnectorError> {
Ok(types::DefendDisputeRouterData {
@@ -1162,8 +1197,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 6e7656c38a6..f96bd50ffc8 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -152,7 +152,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
}
}
-#[derive(Debug, Eq, PartialEq, Deserialize)]
+#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutTokenResponse {
token: Secret<String>,
}
@@ -555,7 +555,7 @@ pub struct PaymentsResponse {
response_summary: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymentsResponseEnum {
ActionResponse(Vec<ActionResponse>),
@@ -723,7 +723,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponseEnum>>
pub struct PaymentVoidRequest {
reference: String,
}
-#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentVoidResponse {
#[serde(skip)]
pub(super) status: u16,
@@ -816,7 +816,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsCaptureRouterData>> for Payment
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentCaptureResponse {
pub action_id: String,
pub reference: Option<String>,
@@ -885,7 +885,7 @@ impl<F> TryFrom<&CheckoutRouterData<&types::RefundsRouterData<F>>> for RefundReq
}
}
#[allow(dead_code)]
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
action_id: String,
reference: String,
@@ -943,14 +943,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse
}
}
-#[derive(Debug, Default, Eq, PartialEq, Deserialize)]
+#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
}
-#[derive(Deserialize, Debug, PartialEq)]
+#[derive(Deserialize, Debug, PartialEq, Serialize)]
pub enum ActionType {
Authorization,
Void,
@@ -962,7 +962,7 @@ pub enum ActionType {
CardVerification,
}
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
@@ -1278,7 +1278,7 @@ pub fn construct_file_upload_request(
Ok(multipart)
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs
index 76f88b66326..1886b651172 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/router/src/connector/coinbase.rs
@@ -13,6 +13,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -97,12 +98,16 @@ impl ConnectorCommon for Coinbase {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: coinbase::CoinbaseErrorResponse = res
.response
.parse_struct("CoinbaseErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.error_type,
@@ -229,12 +234,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -246,8 +254,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -300,12 +309,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -317,8 +329,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index b1435e50df9..5b3b6f63278 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -234,7 +234,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorData {
#[serde(rename = "type")]
pub error_type: String,
@@ -242,7 +242,7 @@ pub struct CoinbaseErrorData {
pub code: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorResponse {
pub error: CoinbaseErrorData,
}
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index 8727461ba34..af33ae21d76 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -20,6 +20,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -160,12 +161,16 @@ impl ConnectorCommon for Cryptopay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cryptopay::CryptopayErrorResponse = res
.response
.parse_struct("CryptopayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
@@ -273,12 +278,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay 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 {
response,
data: data.clone(),
@@ -289,8 +297,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -353,12 +362,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay 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 {
response,
data: data.clone(),
@@ -369,8 +381,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 7970656d6e3..5597af94e3f 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -18,6 +18,7 @@ use crate::{
connector::{utils as connector_utils, utils::RefundsRequestData},
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -114,12 +115,16 @@ impl ConnectorCommon for Cybersource {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceErrorResponse = res
.response
.parse_struct("Cybersource ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_message = if res.status_code == 401 {
consts::CONNECTOR_UNAUTHORIZED_ERROR
} else {
@@ -357,12 +362,15 @@ impl
fn handle_response(
&self,
data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceSetupMandatesResponse = 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 {
response,
data: data.clone(),
@@ -373,8 +381,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -428,9 +437,11 @@ impl
fn handle_response(
&self,
data: &types::MandateRevokeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
mandate_status: common_enums::MandateStatus::Revoked,
@@ -444,6 +455,13 @@ impl
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response_string = response_value.to_string();
+ event_builder.map(|i| {
+ i.set_response_body(
+ &serde_json::json!({"response_string": response_string.clone()}),
+ )
+ });
+ router_env::logger::info!(connector_response=?response_string);
+
Ok(types::MandateRevokeRouterData {
response: Err(types::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
@@ -460,8 +478,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
@@ -563,12 +582,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -579,8 +601,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -649,6 +672,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
@@ -658,6 +682,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.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 {
response,
data: data.clone(),
@@ -667,19 +693,24 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
@@ -747,12 +778,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -762,8 +796,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -851,6 +886,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
if data.is_three_ds()
@@ -861,6 +897,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Cybersource AuthSetupResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -871,6 +909,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.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 {
response,
data: data.clone(),
@@ -882,18 +922,24 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
@@ -981,12 +1027,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -997,18 +1046,24 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
@@ -1099,12 +1154,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -1115,19 +1173,24 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|event| event.set_response_body(&response));
+ router_env::logger::info!(error_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
@@ -1210,12 +1273,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundExecuteRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -1225,8 +1291,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1276,12 +1343,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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 {
response,
data: data.clone(),
@@ -1291,8 +1361,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1373,6 +1444,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsIncrementalAuthorizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
@@ -1386,6 +1458,8 @@ impl
.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 {
response,
@@ -1399,8 +1473,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 324fe77d0bc..646fe179da6 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1303,7 +1303,7 @@ impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourcePaymentStatus {
Authorized,
@@ -1325,7 +1325,7 @@ pub enum CybersourcePaymentStatus {
//PartialAuthorized, not being consumed yet.
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceIncrementalAuthorizationStatus {
Authorized,
@@ -1380,14 +1380,14 @@ impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::Authoriza
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourcePaymentsResponse {
ClientReferenceInformation(CybersourceClientReferenceResponse),
ErrorInformation(CybersourceErrorInformationResponse),
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceClientReferenceResponse {
id: String,
@@ -1399,14 +1399,14 @@ pub struct CybersourceClientReferenceResponse {
error_information: Option<CybersourceErrorInformation>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceErrorInformationResponse {
id: String,
error_information: CybersourceErrorInformation,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationResponse {
access_token: String,
@@ -1414,7 +1414,7 @@ pub struct CybersourceConsumerAuthInformationResponse {
reference_id: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthSetupInfoResponse {
id: String,
@@ -1422,21 +1422,21 @@ pub struct ClientAuthSetupInfoResponse {
consumer_authentication_information: CybersourceConsumerAuthInformationResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceAuthSetupResponse {
ClientAuthSetupInfo(ClientAuthSetupInfoResponse),
ErrorInformation(CybersourceErrorInformationResponse),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsIncrementalAuthorizationResponse {
status: CybersourceIncrementalAuthorizationStatus,
error_information: Option<CybersourceErrorInformation>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceSetupMandatesResponse {
ClientReferenceInformation(CybersourceClientReferenceResponse),
@@ -1462,24 +1462,24 @@ pub struct Avs {
code_raw: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceTokenInformation {
payment_instrument: CybersoucrePaymentInstrument,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CybersourceErrorInformation {
reason: Option<String>,
message: Option<String>,
@@ -1908,7 +1908,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceAuthEnrollmentStatus {
PendingAuthentication,
@@ -1932,7 +1932,7 @@ pub struct CybersourceThreeDSMetadata {
three_ds_data: CybersourceConsumerAuthValidateResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
access_token: Option<String>,
@@ -1942,7 +1942,7 @@ pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
validate_response: CybersourceConsumerAuthValidateResponse,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
@@ -1952,7 +1952,7 @@ pub struct ClientAuthCheckInfoResponse {
error_information: Option<CybersourceErrorInformation>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourcePreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
@@ -2335,14 +2335,14 @@ impl<F, T>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceTransactionResponse {
ApplicationInformation(CybersourceApplicationInfoResponse),
ErrorInformation(CybersourceErrorInformationResponse),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceApplicationInfoResponse {
id: String,
@@ -2351,7 +2351,7 @@ pub struct CybersourceApplicationInfoResponse {
error_information: Option<CybersourceErrorInformation>,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInformation {
status: CybersourcePaymentStatus,
@@ -2474,7 +2474,7 @@ impl From<CybersourceRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceRefundStatus {
Succeeded,
@@ -2484,7 +2484,7 @@ pub enum CybersourceRefundStatus {
Voided,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRefundResponse {
id: String,
@@ -2508,13 +2508,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, CybersourceRefundRes
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RsyncApplicationInformation {
status: CybersourceRefundStatus,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceRsyncResponse {
id: String,
@@ -2540,7 +2540,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceStandardErrorResponse {
pub error_information: Option<ErrorInformation>,
@@ -2550,13 +2550,13 @@ pub struct CybersourceStandardErrorResponse {
pub details: Option<Vec<Details>>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorResponse {
pub errors: Vec<CybersourceNotAvailableErrorObject>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceNotAvailableErrorObject {
#[serde(rename = "type")]
@@ -2564,7 +2564,7 @@ pub struct CybersourceNotAvailableErrorObject {
pub message: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceServerErrorResponse {
pub status: Option<String>,
@@ -2572,7 +2572,7 @@ pub struct CybersourceServerErrorResponse {
pub reason: Option<Reason>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Reason {
SystemError,
@@ -2580,12 +2580,12 @@ pub enum Reason {
ServiceTimeout,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CybersourceAuthenticationErrorResponse {
pub response: AuthenticationErrorInformation,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CybersourceErrorResponse {
AuthenticationError(CybersourceAuthenticationErrorResponse),
@@ -2594,20 +2594,20 @@ pub enum CybersourceErrorResponse {
StandardError(CybersourceStandardErrorResponse),
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Details {
pub field: String,
pub reason: String,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorInformation {
pub message: String,
pub reason: String,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs
index 1e6fc7561ed..5487fd68a51 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/router/src/connector/dlocal.rs
@@ -17,6 +17,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -120,12 +121,16 @@ impl ConnectorCommon for Dlocal {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dlocal::DlocalErrorResponse = res
.response
.parse_struct("Dlocal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
@@ -259,6 +264,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
logger::debug!(dlocal_payments_authorize_response=?res);
@@ -266,6 +272,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.response
.parse_struct("Dlocal PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -278,8 +288,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -329,13 +340,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
logger::debug!(dlocal_payment_sync_response=?res);
@@ -343,6 +356,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("Dlocal PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -407,6 +422,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
logger::debug!(dlocal_payments_capture_response=?res);
@@ -414,6 +430,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.response
.parse_struct("Dlocal PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -426,8 +444,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -477,6 +496,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
logger::debug!(dlocal_payments_cancel_response=?res);
@@ -484,6 +504,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.response
.parse_struct("Dlocal PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -496,8 +519,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -559,6 +583,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
logger::debug!(dlocal_refund_response=?res);
@@ -566,6 +591,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
res.response
.parse_struct("Dlocal RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -578,8 +605,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -627,6 +655,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
logger::debug!(dlocal_refund_sync_response=?res);
@@ -634,6 +663,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("Dlocal RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -646,8 +677,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs
index 28d9eaedf07..85b87f26c5e 100644
--- a/crates/router/src/connector/dummyconnector.rs
+++ b/crates/router/src/connector/dummyconnector.rs
@@ -11,6 +11,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -101,12 +102,16 @@ impl<const T: u8> ConnectorCommon for DummyConnector<T> {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: transformers::DummyConnectorErrorResponse = res
.response
.parse_struct("DummyConnectorErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
@@ -235,13 +240,15 @@ impl<const T: u8>
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("DummyConnector PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- println!("handle_response: {:#?}", response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -253,8 +260,9 @@ impl<const T: u8>
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -313,12 +321,15 @@ impl<const T: u8>
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("dummyconnector 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 {
response,
data: data.clone(),
@@ -330,8 +341,9 @@ impl<const T: u8>
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -387,12 +399,15 @@ impl<const T: u8>
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: transformers::PaymentsResponse = res
.response
.parse_struct("transformers PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -404,8 +419,9 @@ impl<const T: u8>
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -473,12 +489,15 @@ impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types::
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers 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 {
response,
data: data.clone(),
@@ -490,8 +509,9 @@ impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types::
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -541,12 +561,15 @@ impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::Re
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers 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 {
response,
data: data.clone(),
@@ -558,8 +581,9 @@ impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::Re
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs
index 0bd82115627..5cbfee51947 100644
--- a/crates/router/src/connector/fiserv.rs
+++ b/crates/router/src/connector/fiserv.rs
@@ -17,6 +17,7 @@ use crate::{
connector::utils as connector_utils,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -129,12 +130,16 @@ impl ConnectorCommon for Fiserv {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: fiserv::ErrorResponse = res
.response
.parse_struct("Fiserv ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let fiserv::ErrorResponse { error, details } = response;
Ok(error
@@ -290,12 +295,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -308,8 +316,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -373,13 +382,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: fiserv::FiservSyncResponse = res
.response
.parse_struct("Fiserv PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -392,8 +403,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -452,12 +464,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv Payment Response")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -481,8 +498,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -564,12 +582,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: fiserv::FiservPaymentsResponse = res
.response
.parse_struct("Fiserv PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -582,8 +603,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -649,6 +671,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
logger::debug!(target: "router::connector::fiserv", response=?res);
@@ -656,6 +679,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
res.response
.parse_struct("fiserv RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -667,8 +692,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -728,6 +754,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
logger::debug!(target: "router::connector::fiserv", response=?res);
@@ -736,6 +763,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("Fiserv Refund Response")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -748,8 +777,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index 00109f89207..e2511dc8d56 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -257,14 +257,14 @@ impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest {
}
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub details: Option<Vec<ErrorDetails>>,
pub error: Option<Vec<ErrorDetails>>,
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorDetails {
#[serde(rename = "type")]
diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs
index f23907232c4..f179e8a8cce 100644
--- a/crates/router/src/connector/forte.rs
+++ b/crates/router/src/connector/forte.rs
@@ -17,6 +17,7 @@ use crate::{
},
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -116,11 +117,16 @@ impl ConnectorCommon for Forte {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: forte::ForteErrorResponse = res
.response
.parse_struct("Forte ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let message = response.response.response_desc;
let code = response
.response
@@ -248,12 +254,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsResponse = res
.response
.parse_struct("Forte AuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -264,8 +275,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -318,12 +330,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsSyncResponse = res
.response
.parse_struct("forte 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 {
response,
data: data.clone(),
@@ -334,8 +351,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -400,12 +418,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: forte::ForteCaptureResponse = res
.response
.parse_struct("Forte PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -416,8 +439,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
@@ -479,12 +503,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: forte::ForteCancelResponse = res
.response
.parse_struct("forte CancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -495,8 +524,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -558,12 +588,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: forte::RefundResponse = res
.response
.parse_struct("forte 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 {
response,
data: data.clone(),
@@ -574,8 +609,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -625,12 +661,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: forte::RefundSyncResponse = res
.response
.parse_struct("forte 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 {
response,
data: data.clone(),
@@ -641,8 +682,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 4c770eb788d..83bcb2c551b 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -151,7 +151,7 @@ impl TryFrom<&types::ConnectorAuthType> for ForteAuthType {
}
}
// PaymentsResponse
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FortePaymentStatus {
Complete,
@@ -188,7 +188,7 @@ impl ForeignFrom<(ForteResponseCode, ForteAction)> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CardResponse {
pub name_on_card: Secret<String>,
pub last_4_account_number: String,
@@ -196,7 +196,7 @@ pub struct CardResponse {
pub card_type: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub enum ForteResponseCode {
A01,
A05,
@@ -218,7 +218,7 @@ impl From<ForteResponseCode> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ResponseStatus {
pub environment: String,
pub response_type: String,
@@ -237,7 +237,7 @@ pub enum ForteAction {
Verify,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsResponse {
pub transaction_id: String,
pub location_id: String,
@@ -286,7 +286,7 @@ impl<F, T>
//PsyncResponse
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsSyncResponse {
pub transaction_id: String,
pub location_id: String,
@@ -356,7 +356,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for ForteCaptureRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureResponseStatus {
pub environment: String,
pub response_type: String,
@@ -365,7 +365,7 @@ pub struct CaptureResponseStatus {
pub authorization_code: String,
}
// Capture Response
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCaptureResponse {
pub transaction_id: String,
pub original_transaction_id: String,
@@ -423,7 +423,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for ForteCancelRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CancelResponseStatus {
pub response_type: String,
pub response_code: ForteResponseCode,
@@ -431,7 +431,7 @@ pub struct CancelResponseStatus {
pub authorization_code: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCancelResponse {
pub transaction_id: String,
pub location_id: String,
@@ -495,7 +495,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for ForteRefundRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Complete,
@@ -523,7 +523,7 @@ impl From<ForteResponseCode> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
pub transaction_id: String,
pub original_transaction_id: String,
@@ -550,7 +550,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncResponse {
status: RefundStatus,
transaction_id: String,
@@ -573,7 +573,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponseStatus {
pub environment: String,
pub response_type: Option<String>,
@@ -581,7 +581,7 @@ pub struct ErrorResponseStatus {
pub response_desc: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ForteErrorResponse {
pub response: ErrorResponseStatus,
}
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs
index 76954217eef..620805eb3e5 100644
--- a/crates/router/src/connector/globalpay.rs
+++ b/crates/router/src/connector/globalpay.rs
@@ -25,6 +25,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -93,12 +94,16 @@ impl ConnectorCommon for Globalpay {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: transformers::GlobalpayErrorResponse = res
.response
.parse_struct("Globalpay ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
@@ -196,6 +201,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
@@ -203,6 +209,9 @@ impl
.parse_struct("Globalpay PaymentsResponse")
.switch()?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -214,8 +223,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -282,6 +292,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: GlobalpayRefreshTokenResponse = res
@@ -289,6 +300,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -301,12 +315,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: GlobalpayRefreshTokenErrorResponse = res
.response
.parse_struct("Globalpay ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
@@ -415,12 +433,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -433,8 +454,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -487,19 +509,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let is_multiple_capture_sync = match data.request.sync_type {
types::SyncRequestType::MultipleCaptureSync(_) => true,
types::SyncRequestType::SinglePaymentSync => false,
@@ -581,12 +609,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -599,8 +630,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -670,12 +702,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("Globalpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -688,8 +723,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -755,12 +791,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("globalpay 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 {
response,
data: data.clone(),
@@ -772,8 +813,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -823,12 +865,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: GlobalpayPaymentsResponse = res
.response
.parse_struct("globalpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -841,8 +886,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs
index 7416d6f716a..201297c399e 100644
--- a/crates/router/src/connector/globalpay/response.rs
+++ b/crates/router/src/connector/globalpay/response.rs
@@ -70,13 +70,13 @@ pub struct Action {
pub action_type: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobalpayRefreshTokenResponse {
pub token: Secret<String>,
pub seconds_to_expire: i64,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobalpayRefreshTokenErrorResponse {
pub error_code: String,
pub detailed_error_description: String,
diff --git a/crates/router/src/connector/globepay.rs b/crates/router/src/connector/globepay.rs
index 8f8b01de8ef..d480e35cfc0 100644
--- a/crates/router/src/connector/globepay.rs
+++ b/crates/router/src/connector/globepay.rs
@@ -18,6 +18,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
@@ -114,12 +115,16 @@ impl ConnectorCommon for Globepay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: globepay::GlobepayErrorResponse = res
.response
.parse_struct("GlobepayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.return_code.to_string(),
@@ -237,12 +242,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: globepay::GlobepayPaymentsResponse = res
.response
.parse_struct("Globepay 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 {
response,
data: data.clone(),
@@ -253,8 +263,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -305,12 +316,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: globepay::GlobepaySyncResponse = res
.response
.parse_struct("globepay 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 {
response,
data: data.clone(),
@@ -321,8 +337,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -409,12 +426,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: globepay::GlobepayRefundResponse = res
.response
.parse_struct("Globalpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -425,8 +447,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -476,12 +499,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: globepay::GlobepayRefundResponse = res
.response
.parse_struct("Globalpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -492,8 +520,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs
index a874fc21d29..5cb22890b7c 100644
--- a/crates/router/src/connector/globepay/transformers.rs
+++ b/crates/router/src/connector/globepay/transformers.rs
@@ -102,7 +102,7 @@ impl TryFrom<&types::ConnectorAuthType> for GlobepayAuthType {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentStatus {
Success,
@@ -123,7 +123,7 @@ pub struct GlobepayConnectorMetadata {
image_data_url: url::Url,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayPaymentsResponse {
result_code: Option<GlobepayPaymentStatus>,
order_id: Option<String>,
@@ -132,7 +132,7 @@ pub struct GlobepayPaymentsResponse {
return_msg: Option<String>,
}
-#[derive(Debug, Deserialize, PartialEq, strum::Display)]
+#[derive(Debug, Deserialize, PartialEq, strum::Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayReturnCode {
Success,
@@ -210,7 +210,7 @@ impl<F, T>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepaySyncResponse {
pub result_code: Option<GlobepayPaymentPsyncStatus>,
pub order_id: Option<String>,
@@ -218,7 +218,7 @@ pub struct GlobepaySyncResponse {
pub return_msg: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentPsyncStatus {
Paying,
@@ -313,7 +313,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for GlobepayRefundRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub enum GlobepayRefundStatus {
Waiting,
CreateFailed,
@@ -335,7 +335,7 @@ impl From<GlobepayRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayRefundResponse {
pub result_code: Option<GlobepayRefundStatus>,
pub refund_id: Option<String>,
@@ -379,7 +379,7 @@ impl<T> TryFrom<types::RefundsResponseRouterData<T, GlobepayRefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayErrorResponse {
pub return_msg: String,
pub return_code: GlobepayReturnCode,
diff --git a/crates/router/src/connector/gocardless.rs b/crates/router/src/connector/gocardless.rs
index 542caa73ff3..720a13611c0 100644
--- a/crates/router/src/connector/gocardless.rs
+++ b/crates/router/src/connector/gocardless.rs
@@ -12,6 +12,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -104,11 +105,16 @@ impl ConnectorCommon for Gocardless {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: gocardless::GocardlessErrorResponse = res
.response
.parse_struct("GocardlessErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_iter = response.error.errors.iter();
let mut error_reason: Vec<String> = Vec::new();
for error in error_iter {
@@ -185,6 +191,7 @@ impl
fn handle_response(
&self,
data: &types::ConnectorCustomerRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
types::RouterData<
@@ -203,6 +210,10 @@ impl
.response
.parse_struct("GocardlessCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -213,8 +224,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -274,6 +286,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -285,6 +298,10 @@ impl
.response
.parse_struct("GocardlessBankAccountResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -295,8 +312,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -395,12 +413,17 @@ impl
fn handle_response(
&self,
data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessMandateResponse = res
.response
.parse_struct("GocardlessMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -411,8 +434,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -480,12 +504,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -496,8 +525,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -549,12 +579,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: gocardless::GocardlessPaymentsResponse = res
.response
.parse_struct("GocardlessPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -565,8 +600,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -640,12 +676,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: gocardless::RefundResponse = res
.response
.parse_struct("gocardless 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 {
response,
data: data.clone(),
@@ -656,8 +697,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index 249dae370b1..d3703bc6bf8 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -172,12 +172,12 @@ fn get_region(
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessCustomerResponse {
customers: Customers,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Customers {
id: Secret<String>,
}
@@ -391,12 +391,12 @@ impl From<BankType> for AccountType {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessBankAccountResponse {
customer_bank_accounts: CustomerBankAccountResponse,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomerBankAccountResponse {
pub id: Secret<String>,
}
@@ -540,12 +540,12 @@ impl TryFrom<&BankDebitData> for GocardlessScheme {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GocardlessMandateResponse {
mandates: MandateResponse,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MandateResponse {
id: String,
}
@@ -817,7 +817,7 @@ impl<F> TryFrom<&GocardlessRouterData<&types::RefundsRouterData<F>>> for Gocardl
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
@@ -839,12 +839,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessErrorResponse {
pub error: GocardlessError,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GocardlessError {
pub message: String,
pub code: u16,
@@ -853,7 +853,7 @@ pub struct GocardlessError {
pub error_type: String,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Error {
pub field: Option<String>,
pub message: String,
diff --git a/crates/router/src/connector/helcim.rs b/crates/router/src/connector/helcim.rs
index 0b2cac5d766..5e03e5046ae 100644
--- a/crates/router/src/connector/helcim.rs
+++ b/crates/router/src/connector/helcim.rs
@@ -13,6 +13,7 @@ use crate::{
configs::settings,
consts::NO_ERROR_CODE,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -123,11 +124,16 @@ impl ConnectorCommon for Helcim {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: helcim::HelcimErrorResponse = res
.response
.parse_struct("HelcimErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_string = match response {
transformers::HelcimErrorResponse::Payment(response) => match response.errors {
transformers::HelcimErrorTypes::StringType(error) => error,
@@ -229,12 +235,15 @@ impl
fn handle_response(
&self,
data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim 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 {
response,
data: data.clone(),
@@ -244,8 +253,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -315,12 +325,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim 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 {
response,
data: data.clone(),
@@ -331,8 +346,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -394,12 +410,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("helcim 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 {
response,
data: data.clone(),
@@ -410,8 +431,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
// fn get_multiple_capture_sync_method(
@@ -482,12 +504,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("Helcim PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -498,8 +525,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -556,12 +584,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: helcim::HelcimPaymentsResponse = res
.response
.parse_struct("HelcimPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -573,8 +606,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -636,12 +670,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: helcim::RefundResponse =
res.response
.parse_struct("helcim 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 {
response,
data: data.clone(),
@@ -652,8 +691,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -713,12 +753,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: helcim::RefundResponse = res
.response
.parse_struct("helcim 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 {
response,
data: data.clone(),
@@ -729,8 +774,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs
index 5e076be651f..fba46bd721f 100644
--- a/crates/router/src/connector/helcim/transformers.rs
+++ b/crates/router/src/connector/helcim/transformers.rs
@@ -299,14 +299,14 @@ impl TryFrom<&types::ConnectorAuthType> for HelcimAuthType {
}
}
// PaymentsResponse
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HelcimPaymentStatus {
Approved,
Declined,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimTransactionType {
Purchase,
@@ -339,7 +339,7 @@ impl From<HelcimPaymentsResponse> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimPaymentsResponse {
status: HelcimPaymentStatus,
@@ -689,12 +689,12 @@ impl<F> TryFrom<&HelcimRouterData<&types::RefundsRouterData<F>>> for HelcimRefun
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimRefundTransactionType {
Refund,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
status: HelcimPaymentStatus,
@@ -748,19 +748,19 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Debug, strum::Display, Deserialize)]
+#[derive(Debug, strum::Display, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorTypes {
StringType(String),
JsonType(serde_json::Value),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct HelcimPaymentsErrorResponse {
pub errors: HelcimErrorTypes,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorResponse {
Payment(HelcimPaymentsErrorResponse),
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs
index c5ac0f43833..c049520de28 100644
--- a/crates/router/src/connector/iatapay.rs
+++ b/crates/router/src/connector/iatapay.rs
@@ -14,6 +14,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -113,12 +114,16 @@ impl ConnectorCommon for Iatapay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: iatapay::IatapayErrorResponse = res
.response
.parse_struct("IatapayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
@@ -207,6 +212,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: iatapay::IatapayAuthUpdateResponse = res
@@ -214,6 +220,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("iatapay IatapayAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -224,12 +233,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: iatapay::IatapayAccessTokenErrorResponse = res
.response
.parse_struct("Iatapay AccessTokenErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
@@ -327,12 +340,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: IatapayPaymentsResponse = res
.response
.parse_struct("Iatapay 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 {
response,
data: data.clone(),
@@ -344,8 +360,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -397,12 +414,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: IatapayPaymentsResponse = res
.response
.parse_struct("iatapay 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 {
response,
data: data.clone(),
@@ -414,8 +434,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -506,12 +527,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: iatapay::RefundResponse = res
.response
.parse_struct("iatapay 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 {
response,
data: data.clone(),
@@ -523,8 +547,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -575,12 +600,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: iatapay::RefundResponse = res
.response
.parse_struct("iatapay 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 {
response,
data: data.clone(),
@@ -592,8 +620,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 4557fda0390..55778af882b 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -60,7 +60,7 @@ impl<T>
})
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct IatapayAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
@@ -507,7 +507,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct IatapayErrorResponse {
pub status: u16,
pub error: String,
@@ -515,7 +515,7 @@ pub struct IatapayErrorResponse {
pub reason: Option<String>,
}
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct IatapayAccessTokenErrorResponse {
pub error: String,
pub path: String,
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 5361a636826..8b7ab0da7f2 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -11,6 +11,7 @@ use crate::{
connector::utils as connector_utils,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -61,11 +62,16 @@ impl ConnectorCommon for Klarna {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: klarna::KlarnaErrorResponse = res
.response
.parse_struct("KlarnaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
// KlarnaErrorResponse will either have error_messages or error_message field Ref: https://docs.klarna.com/api/errors/
let reason = response
.error_messages
@@ -186,12 +192,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsSessionRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
let response: klarna::KlarnaSessionResponse = res
.response
.parse_struct("KlarnaSessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -203,8 +214,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -463,12 +475,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: klarna::KlarnaPaymentsResponse = res
.response
.parse_struct("KlarnaPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -480,8 +497,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 0816dd82ec6..c12f8ed1b10 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -48,7 +48,7 @@ pub struct KlarnaPaymentsRequest {
merchant_reference1: String,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct KlarnaPaymentsResponse {
order_id: String,
fraud_status: KlarnaFraudStatus,
@@ -64,7 +64,7 @@ pub struct KlarnaSessionRequest {
order_lines: Vec<OrderLines>,
}
-#[derive(Deserialize)]
+#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaSessionResponse {
pub client_token: String,
pub session_id: String,
@@ -225,7 +225,7 @@ impl From<KlarnaFraudStatus> for enums::AttemptStatus {
}
}
-#[derive(Deserialize)]
+#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaErrorResponse {
pub error_code: String,
pub error_messages: Option<Vec<String>>,
diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs
index cee4225d861..e6bbd688376 100644
--- a/crates/router/src/connector/mollie.rs
+++ b/crates/router/src/connector/mollie.rs
@@ -14,6 +14,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -87,11 +88,16 @@ impl ConnectorCommon for Mollie {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: mollie::ErrorResponse = res
.response
.parse_struct("MollieErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: response.status,
code: response
@@ -178,6 +184,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -187,6 +194,10 @@ impl
.response
.parse_struct("MollieTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -197,8 +208,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -284,12 +296,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: mollie::MolliePaymentsResponse = res
.response
.parse_struct("MolliePaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -300,8 +317,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -358,12 +376,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: mollie::MolliePaymentsResponse = res
.response
.parse_struct("mollie 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 {
response,
data: data.clone(),
@@ -374,8 +397,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -473,12 +497,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: mollie::RefundResponse = res
.response
.parse_struct("MollieRefundResponse")
.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 {
response,
data: data.clone(),
@@ -489,8 +518,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -543,12 +573,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: mollie::RefundResponse = res
.response
.parse_struct("MollieRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -559,8 +594,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 0fcb14d2cf5..af1159cd2c3 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -388,7 +388,7 @@ fn get_address_details(
Ok(address_details)
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsResponse {
pub resource: String,
@@ -625,7 +625,7 @@ impl<T> TryFrom<types::RefundsResponseRouterData<T, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponse {
pub status: u16,
pub title: Option<String>,
diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs
index 8290a00661c..da3a87454ce 100644
--- a/crates/router/src/connector/multisafepay.rs
+++ b/crates/router/src/connector/multisafepay.rs
@@ -10,6 +10,7 @@ use transformers as multisafepay;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -74,11 +75,16 @@ impl ConnectorCommon for Multisafepay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: multisafepay::MultisafepayErrorResponse = res
.response
.parse_struct("MultisafepayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code.to_string(),
@@ -208,13 +214,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: multisafepay::MultisafepayAuthResponse = res
@@ -222,6 +230,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.parse_struct("multisafepay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -316,6 +327,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: multisafepay::MultisafepayAuthResponse = res
@@ -323,6 +335,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.parse_struct("MultisafepayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -335,8 +350,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -413,12 +429,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: multisafepay::MultisafepayRefundResponse = res
.response
.parse_struct("multisafepay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -431,8 +450,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -485,12 +505,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: multisafepay::MultisafepayRefundResponse = res
.response
.parse_struct("multisafepay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -503,8 +526,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs
index 1f4a7f41f66..4457a0986f6 100644
--- a/crates/router/src/connector/nexinets.rs
+++ b/crates/router/src/connector/nexinets.rs
@@ -13,6 +13,7 @@ use crate::{
utils::{to_connector_meta, PaymentsSyncRequestData},
},
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -100,12 +101,16 @@ impl ConnectorCommon for Nexinets {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: nexinets::NexinetsErrorResponse = res
.response
.parse_struct("NexinetsErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let errors = response.errors;
let mut message = String::new();
let mut static_message = String::new();
@@ -247,12 +252,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPreAuthOrDebitResponse = res
.response
.parse_struct("Nexinets 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 {
response,
data: data.clone(),
@@ -263,8 +273,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -322,12 +333,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("nexinets NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -338,8 +354,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -405,12 +422,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -421,8 +443,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -485,12 +508,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -501,8 +529,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -567,12 +596,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets 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 {
response,
data: data.clone(),
@@ -583,8 +617,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -638,12 +673,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets 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 {
response,
data: data.clone(),
@@ -654,8 +694,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 698b2709a62..07488271aea 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -211,7 +211,7 @@ impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType {
}
}
// PaymentsResponse
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsPaymentStatus {
Success,
@@ -275,7 +275,7 @@ impl TryFrom<&api_models::enums::BankNames> for NexinetsBIC {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPreAuthOrDebitResponse {
order_id: String,
@@ -285,7 +285,7 @@ pub struct NexinetsPreAuthOrDebitResponse {
redirect_url: Option<Url>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsTransaction {
pub transaction_id: String,
@@ -386,7 +386,7 @@ pub struct NexinetsCaptureOrVoidRequest {
pub currency: enums::Currency,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsOrder {
pub order_id: String,
@@ -412,7 +412,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentResponse {
pub transaction_id: String,
@@ -483,7 +483,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NexinetsRefundRequest {
}
// Type definition for Refund Response
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundResponse {
pub transaction_id: String,
@@ -494,7 +494,7 @@ pub struct NexinetsRefundResponse {
}
#[allow(dead_code)]
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
@@ -504,7 +504,7 @@ pub enum RefundStatus {
InProgress,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundType {
Refund,
@@ -554,7 +554,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NexinetsErrorResponse {
pub status: u16,
pub code: u16,
@@ -562,7 +562,7 @@ pub struct NexinetsErrorResponse {
pub errors: Vec<OrderErrorDetails>,
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct OrderErrorDetails {
pub code: u16,
pub message: String,
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index 0550908649f..a7c920a5f93 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -12,6 +12,7 @@ use super::utils as connector_utils;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
self,
@@ -69,11 +70,16 @@ impl ConnectorCommon for Nmi {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: nmi::StandardResponse = res
.response
.parse_struct("StandardResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
message: response.responsetext.to_owned(),
status_code: res.status_code,
@@ -181,11 +187,14 @@ impl
fn handle_response(
&self,
data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -196,8 +205,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -265,11 +275,14 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -280,8 +293,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -343,11 +357,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -358,8 +375,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -428,11 +446,14 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: nmi::NmiCompleteResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -443,8 +464,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -496,10 +518,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response = nmi::SyncResponse::try_from(res.response.to_vec())?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+
types::RouterData::try_from(types::ResponseRouterData {
- response: res.clone(),
+ response,
data: data.clone(),
http_code: res.status_code,
})
@@ -508,8 +535,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -569,11 +597,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -584,8 +615,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -637,11 +669,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -652,8 +687,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -711,11 +747,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.into_report()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -726,8 +765,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -777,10 +817,16 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundsRouterData<api::RSync>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
+ let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
- response: res.clone(),
+ response,
data: data.clone(),
http_code: res.status_code,
})
@@ -789,8 +835,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 65acb5832b4..c6d763fe568 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -137,7 +137,7 @@ fn get_card_details(
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NmiVaultResponse {
pub response: Response,
pub responsetext: String,
@@ -305,7 +305,7 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for Nm
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NmiCompleteResponse {
pub response: Response,
pub responsetext: String,
@@ -707,7 +707,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub enum Response {
#[serde(alias = "1")]
Approved,
@@ -717,7 +717,7 @@ pub enum Response {
Error,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct StandardResponse {
pub response: Response,
pub responsetext: String,
@@ -898,15 +898,14 @@ pub enum NmiStatus {
Unknown,
}
-impl TryFrom<types::PaymentsSyncResponseRouterData<types::Response>>
- for types::PaymentsSyncRouterData
+impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = Error;
fn try_from(
- item: types::PaymentsSyncResponseRouterData<types::Response>,
+ item: types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- let response = SyncResponse::try_from(item.response.response.to_vec())?;
- match response.transaction {
+ match item.response.transaction {
Some(trn) => Ok(Self {
status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -1050,19 +1049,18 @@ impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, types::Response>>
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>>
for types::RefundsRouterData<api::RSync>
{
- type Error = Error;
+ type Error = Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, types::Response>,
+ item: types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>,
) -> Result<Self, Self::Error> {
- let response = NmiRefundSyncResponse::try_from(item.response.response.to_vec())?;
let refund_status =
- enums::RefundStatus::from(NmiStatus::from(response.transaction.condition));
+ enums::RefundStatus::from(NmiStatus::from(item.response.transaction.condition));
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: response.transaction.order_id,
+ connector_refund_id: item.response.transaction.order_id,
refund_status,
}),
..item.data
@@ -1110,14 +1108,14 @@ pub struct SyncResponse {
pub transaction: Option<SyncTransactionResponse>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RefundSyncBody {
order_id: String,
condition: String,
}
-#[derive(Debug, Deserialize)]
-struct NmiRefundSyncResponse {
+#[derive(Debug, Deserialize, Serialize)]
+pub struct NmiRefundSyncResponse {
transaction: RefundSyncBody,
}
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs
index 6e1959b46d0..56f3c7101b2 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -18,6 +18,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -127,20 +128,26 @@ impl ConnectorCommon for Noon {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> =
res.response.parse_struct("NoonErrorResponse");
match response {
- Ok(noon_error_response) => Ok(ErrorResponse {
- status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
- message: noon_error_response.class_description,
- reason: Some(noon_error_response.message),
- attempt_status: None,
- connector_transaction_id: None,
- }),
+ Ok(noon_error_response) => {
+ event_builder.map(|i| i.set_error_response_body(&noon_error_response));
+ router_env::logger::info!(connector_response=?noon_error_response);
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: noon_error_response.class_description,
+ reason: Some(noon_error_response.message),
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
Err(error_message) => {
+ event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
logger::error!(deserialization_error =? error_message);
utils::handle_json_response_deserialization_failure(res, "noon".to_owned())
}
@@ -262,12 +269,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon 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 {
response,
data: data.clone(),
@@ -278,8 +290,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -328,12 +341,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("noon 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 {
response,
data: data.clone(),
@@ -344,8 +362,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -404,12 +423,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -420,8 +444,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -477,12 +502,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -493,8 +523,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -553,12 +584,17 @@ impl
fn handle_response(
&self,
data: &types::MandateRevokeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> {
let response: noon::NoonRevokeMandateResponse = res
.response
.parse_struct("Noon NoonRevokeMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -568,8 +604,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -625,12 +662,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: noon::RefundResponse = res
.response
.parse_struct("noon 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 {
response,
data: data.clone(),
@@ -641,8 +683,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -689,6 +732,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: noon::RefundSyncResponse = res
@@ -696,6 +740,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.parse_struct("noon 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 {
response,
data: data.clone(),
@@ -707,8 +754,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 5818c10eea6..2f5f342d7ae 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -707,22 +707,22 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest {
})
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub enum NoonRevokeStatus {
Cancelled,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NoonCancelSubscriptionObject {
status: NoonRevokeStatus,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResult {
subscription: NoonCancelSubscriptionObject,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResponse {
result: NoonRevokeMandateResult,
}
@@ -757,7 +757,7 @@ impl<F>
}
}
-#[derive(Debug, Default, Deserialize, Clone)]
+#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
@@ -776,19 +776,19 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsTransactionResponse {
id: String,
status: RefundStatus,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct NoonRefundResponseResult {
transaction: NoonPaymentsTransactionResponse,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct RefundResponse {
result: NoonRefundResponseResult,
}
@@ -810,7 +810,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseTransactions {
id: String,
@@ -818,12 +818,12 @@ pub struct NoonRefundResponseTransactions {
transaction_reference: Option<String>,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct NoonRefundSyncResponseResult {
transactions: Vec<NoonRefundResponseTransactions>,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct RefundSyncResponse {
result: NoonRefundSyncResponseResult,
}
@@ -927,7 +927,7 @@ impl From<NoonWebhookObject> for NoonPaymentsResponse {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonErrorResponse {
pub result_code: u32,
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
index 35de293443e..59396766317 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -18,6 +18,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
@@ -195,12 +196,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -212,8 +218,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -272,12 +279,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::PaymentsCancelRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -289,8 +299,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -354,19 +365,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -434,12 +451,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -451,8 +473,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -592,12 +615,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -609,8 +637,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -678,10 +707,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeSessionTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
let response: nuvei::NuveiSessionResponse =
res.response.parse_struct("NuveiSessionResponse").switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -692,8 +726,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -754,12 +789,17 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym
fn handle_response(
&self,
data: &types::PaymentsInitRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -771,8 +811,9 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -831,12 +872,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: nuvei::NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -848,8 +894,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs
index 0ab5785a445..7285ce49fcd 100644
--- a/crates/router/src/connector/opayo.rs
+++ b/crates/router/src/connector/opayo.rs
@@ -12,6 +12,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -97,12 +98,16 @@ impl ConnectorCommon for Opayo {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: opayo::OpayoErrorResponse =
res.response
.parse_struct("OpayoErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
@@ -220,12 +225,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo 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 {
response,
data: data.clone(),
@@ -236,8 +246,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -282,12 +293,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("opayo 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 {
response,
data: data.clone(),
@@ -298,8 +314,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -357,12 +374,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -373,8 +395,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -436,12 +459,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo 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 {
response,
data: data.clone(),
@@ -452,8 +480,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -496,12 +525,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo 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 {
response,
data: data.clone(),
@@ -512,8 +546,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs
index 1eafa67fdda..1bd7461b668 100644
--- a/crates/router/src/connector/opennode.rs
+++ b/crates/router/src/connector/opennode.rs
@@ -11,6 +11,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -99,12 +100,16 @@ impl ConnectorCommon for Opennode {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: opennode::OpennodeErrorResponse = res
.response
.parse_struct("OpennodeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
@@ -224,12 +229,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("Opennode 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 {
response,
data: data.clone(),
@@ -241,8 +251,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -295,12 +306,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("opennode 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 {
response,
data: data.clone(),
@@ -312,8 +328,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index 7670166faba..3267caf60d6 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -252,7 +252,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
//TODO: Fill the struct with respective fields
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct OpennodeErrorResponse {
pub message: String,
}
diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs
index 442bbaca312..6f6a366ee46 100644
--- a/crates/router/src/connector/payeezy.rs
+++ b/crates/router/src/connector/payeezy.rs
@@ -16,6 +16,7 @@ use crate::{
connector::utils as connector_utils,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -104,12 +105,16 @@ impl ConnectorCommon for Payeezy {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payeezy::PayeezyErrorResponse = res
.response
.parse_struct("payeezy ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_messages: Vec<String> = response
.error
.messages
@@ -240,12 +245,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("Payeezy PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -257,8 +267,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -343,12 +354,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("Payeezy PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -360,8 +376,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -438,12 +455,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("payeezy Response")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -455,8 +477,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -528,6 +551,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
// Parse the response into a payeezy::RefundResponse
@@ -536,6 +560,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.parse_struct("payeezy RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ 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 {
response,
@@ -551,8 +578,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index c633fd3d99f..e8801e3222b 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -298,7 +298,7 @@ impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType {
}
// PaymentsResponse
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyPaymentStatus {
Approved,
@@ -308,7 +308,7 @@ pub enum PayeezyPaymentStatus {
NotProcessed,
}
-#[derive(Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyPaymentsResponse {
pub correlation_id: String,
pub transaction_status: PayeezyPaymentStatus,
@@ -327,7 +327,7 @@ pub struct PayeezyPaymentsResponse {
pub reference: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsStoredCredentials {
cardbrand_original_transaction_id: String,
}
@@ -502,7 +502,7 @@ impl<F> TryFrom<&PayeezyRouterData<&types::RefundsRouterData<F>>> for PayeezyRef
// Type definition for Refund Response
-#[derive(Debug, Deserialize, Default)]
+#[derive(Debug, Deserialize, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Approved,
@@ -522,7 +522,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Deserialize)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
pub correlation_id: String,
pub transaction_status: RefundStatus,
@@ -556,18 +556,18 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct Message {
pub code: String,
pub description: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyError {
pub messages: Vec<Message>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyErrorResponse {
pub transaction_status: String,
#[serde(rename = "Error")]
diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs
index 40f4c646e50..d84c87f2e46 100644
--- a/crates/router/src/connector/payme.rs
+++ b/crates/router/src/connector/payme.rs
@@ -16,6 +16,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
@@ -80,11 +81,16 @@ impl ConnectorCommon for Payme {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payme::PaymeErrorResponse =
res.response
.parse_struct("PaymeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let status_code = match res.status_code {
500..=511 => 200,
_ => res.status_code,
@@ -182,6 +188,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -192,6 +199,9 @@ impl
.parse_struct("Payme CaptureBuyerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -202,16 +212,18 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -288,12 +300,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: payme::GenerateSaleResponse = res
.response
.parse_struct("Payme GenerateSaleResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -304,16 +321,18 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -416,12 +435,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymePaySaleResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -432,15 +456,17 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -522,12 +548,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme 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 {
response,
data: data.clone(),
@@ -538,16 +569,18 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -604,6 +637,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
@@ -618,6 +652,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.response
.parse_struct("PaymePaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -628,9 +666,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -695,12 +734,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -711,16 +755,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -798,12 +844,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: payme::PaymeRefundResponse = res
.response
.parse_struct("PaymeRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -814,16 +865,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -877,6 +930,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
@@ -891,6 +945,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("GetSalesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -901,16 +959,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index a7b21ce292d..77dcb6429c9 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -119,7 +119,7 @@ pub struct CaptureBuyerRequest {
card: PaymeCard,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureBuyerResponse {
buyer_key: String,
}
@@ -156,7 +156,7 @@ pub struct ThreeDsSettings {
active: bool,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct GenerateSaleResponse {
payme_sale_id: String,
}
@@ -858,19 +858,19 @@ impl From<SaleStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaymePaymentsResponse {
PaymePaySaleResponse(PaymePaySaleResponse),
SaleQueryResponse(SaleQueryResponse),
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SaleQueryResponse {
items: Vec<SaleQuery>,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SaleQuery {
sale_status: SaleStatus,
sale_payme_id: String,
@@ -978,7 +978,7 @@ impl TryFrom<SaleStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct PaymeRefundResponse {
sale_status: SaleStatus,
payme_transaction_id: String,
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index 742c563407c..38d8b783d5d 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -21,6 +21,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -59,6 +60,7 @@ impl Paypal {
pub fn get_order_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
//Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync).
//Error response have different fields for Orders and Payments.
@@ -67,6 +69,9 @@ impl Paypal {
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_reason = response.details.map(|order_errors| {
order_errors
.iter()
@@ -207,12 +212,16 @@ impl ConnectorCommon for Paypal {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paypal::PaypalPaymentErrorResponse = res
.response
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error_reason = response
.details
.map(|error_details| {
@@ -345,6 +354,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: paypal::PaypalAuthUpdateResponse = res
@@ -352,6 +362,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("Paypal PaypalAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -362,12 +375,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paypal::PaypalAccessTokenErrorResponse = res
.response
.parse_struct("Paypal AccessTokenErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
@@ -464,6 +481,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: PaypalAuthResponse =
@@ -473,6 +491,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
match response {
PaypalAuthResponse::PaypalOrdersResponse(response) => {
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -480,6 +501,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
})
}
PaypalAuthResponse::PaypalRedirectResponse(response) => {
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -487,6 +510,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
})
}
PaypalAuthResponse::PaypalThreeDsResponse(response) => {
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -499,8 +524,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.get_order_error_response(res)
+ self.get_order_error_response(res, event_builder)
}
}
@@ -560,6 +586,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: paypal::PaypalPreProcessingResponse = res
@@ -567,6 +594,9 @@ impl
.parse_struct("paypal PaypalPreProcessingResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
match response {
// if card supports 3DS check for liability
paypal::PaypalPreProcessingResponse::PaypalLiabilityResponse(liability_response) => {
@@ -676,8 +706,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -741,12 +772,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: paypal::PaypalOrdersResponse = res
.response
.parse_struct("paypal PaypalOrdersResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -757,8 +791,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -847,12 +882,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: paypal::PaypalSyncResponse = res
.response
.parse_struct("paypal SyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -863,8 +901,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -938,12 +977,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: paypal::PaypalCaptureResponse = res
.response
.parse_struct("Paypal PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -954,8 +996,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1009,12 +1052,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: paypal::PaypalPaymentsCancelResponse = res
.response
.parse_struct("PaymentCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1024,8 +1070,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1097,12 +1144,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: paypal::RefundResponse =
res.response
.parse_struct("paypal 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 {
response,
data: data.clone(),
@@ -1113,8 +1163,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1160,12 +1211,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: paypal::RefundSyncResponse = res
.response
.parse_struct("paypal 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 {
response,
data: data.clone(),
@@ -1176,8 +1230,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -1268,12 +1323,15 @@ impl
fn handle_response(
&self,
data: &types::VerifyWebhookSourceRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ConnectorError> {
let response: paypal::PaypalSourceVerificationResponse = res
.response
.parse_struct("paypal PaypalSourceVerificationResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1283,8 +1341,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 1447cf75be7..a584fe98165 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -762,7 +762,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PaypalAuthUpdateRequest {
}
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PaypalAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
@@ -1063,7 +1063,7 @@ pub enum PaypalAuthResponse {
}
// Note: Don't change order of deserialization of variant, priority is in descending order
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaypalSyncResponse {
PaypalOrdersSyncResponse(PaypalOrdersResponse),
@@ -1742,7 +1742,7 @@ pub struct PaypalPaymentErrorResponse {
pub details: Option<Vec<ErrorDetails>>,
}
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct PaypalAccessTokenErrorResponse {
pub error: String,
pub error_description: String,
diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs
index c44b4d5d6ff..bd850cf1e89 100644
--- a/crates/router/src/connector/payu.rs
+++ b/crates/router/src/connector/payu.rs
@@ -12,6 +12,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -86,12 +87,16 @@ impl ConnectorCommon for Payu {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payu::PayuErrorResponse = res
.response
.parse_struct("Payu ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.status.status_code,
@@ -202,12 +207,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: payu::PayuPaymentsCancelResponse = res
.response
.parse_struct("PaymentCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -218,8 +228,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -289,6 +300,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: payu::PayuAuthUpdateResponse = res
@@ -296,6 +308,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("payu PayuAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -308,12 +323,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payu::PayuAccessTokenErrorResponse = res
.response
.parse_struct("Payu AccessTokenErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error,
@@ -377,12 +396,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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::ResponseRouterData {
response,
data: data.clone(),
@@ -395,8 +417,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -462,12 +485,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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::ResponseRouterData {
response,
data: data.clone(),
@@ -480,8 +506,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -560,12 +587,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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::ResponseRouterData {
response,
data: data.clone(),
@@ -578,8 +608,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -645,12 +676,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::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::ResponseRouterData {
response,
data: data.clone(),
@@ -663,8 +697,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -713,12 +748,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::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::ResponseRouterData {
response,
data: data.clone(),
@@ -731,8 +769,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs
index 6edc570eb45..e3ad6f8b426 100644
--- a/crates/router/src/connector/payu/transformers.rs
+++ b/crates/router/src/connector/payu/transformers.rs
@@ -172,7 +172,7 @@ impl From<PayuPaymentStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsResponse {
pub status: PayuPaymentStatusData,
@@ -230,7 +230,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for PayuPaymentsCaptureRequest {
}
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuPaymentsCaptureResponse {
status: PayuPaymentStatusData,
}
@@ -283,7 +283,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest {
})
}
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
@@ -394,7 +394,7 @@ pub struct PayuProductData {
listing_date: Option<String>,
}
-#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuOrderResponseData {
order_id: String,
@@ -428,7 +428,7 @@ pub struct PayuOrderResponseBuyerData {
customer_id: Option<String>,
}
-#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayuOrderResponsePayMethod {
CardToken,
@@ -442,7 +442,7 @@ pub struct PayuOrderResponseProperty {
value: String,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuPaymentsSyncResponse {
orders: Vec<PayuOrderResponseData>,
status: PayuPaymentStatusData,
@@ -542,7 +542,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize)]
+#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuRefundResponseData {
refund_id: String,
@@ -555,7 +555,7 @@ pub struct PayuRefundResponseData {
status_date_time: Option<String>,
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund: PayuRefundResponseData,
@@ -579,7 +579,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundSyncResponse {
refunds: Vec<PayuRefundResponseData>,
}
@@ -617,7 +617,7 @@ pub struct PayuErrorResponse {
pub status: PayuErrorData,
}
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct PayuAccessTokenErrorResponse {
pub error: String,
pub error_description: String,
diff --git a/crates/router/src/connector/placetopay.rs b/crates/router/src/connector/placetopay.rs
index ef51f1d6e4b..ab33bf1039d 100644
--- a/crates/router/src/connector/placetopay.rs
+++ b/crates/router/src/connector/placetopay.rs
@@ -10,6 +10,7 @@ use crate::{
configs::settings,
connector::utils::{self},
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -89,12 +90,16 @@ impl ConnectorCommon for Placetopay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: placetopay::PlacetopayErrorResponse = res
.response
.parse_struct("PlacetopayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.status.reason.to_owned(),
@@ -220,12 +225,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: placetopay::PlacetopayPaymentsResponse = res
.response
.parse_struct("Placetopay PlacetopayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -236,8 +246,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -294,12 +305,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: placetopay::PlacetopayPaymentsResponse = res
.response
.parse_struct("placetopay 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 {
response,
data: data.clone(),
@@ -310,8 +326,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -370,12 +387,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: placetopay::PlacetopayPaymentsResponse = res
.response
.parse_struct("Placetopay PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -386,8 +408,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -444,12 +467,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: placetopay::PlacetopayPaymentsResponse = res
.response
.parse_struct("Placetopay PaymentCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -460,8 +488,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -519,12 +548,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: placetopay::PlacetopayRefundResponse = res
.response
.parse_struct("placetopay PlacetopayRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -535,8 +569,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -593,12 +628,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: placetopay::PlacetopayRefundResponse = res
.response
.parse_struct("placetopay PlacetopayRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -609,8 +649,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index dfdd3f904df..f1c054b960b 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -204,7 +204,7 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuthType {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayStatus {
Ok,
@@ -216,7 +216,7 @@ pub enum PlacetopayStatus {
PendingProcess,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
status: PlacetopayStatus,
@@ -234,7 +234,7 @@ impl From<PlacetopayStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsResponse {
status: PlacetopayStatusResponse,
@@ -315,14 +315,14 @@ impl From<PlacetopayRefundStatus> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundResponse {
status: PlacetopayRefundStatus,
internal_reference: u64,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
Refunded,
@@ -390,13 +390,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, PlacetopayRefundRespon
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayErrorResponse {
pub status: PlacetopayError,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayError {
pub status: PlacetopayErrorStatus,
@@ -404,7 +404,7 @@ pub struct PlacetopayError {
pub reason: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayErrorStatus {
Failed,
diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs
index 654128bb3fd..5023f6b743a 100644
--- a/crates/router/src/connector/powertranz.rs
+++ b/crates/router/src/connector/powertranz.rs
@@ -16,6 +16,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -112,9 +113,12 @@ impl ConnectorCommon for Powertranz {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// For error scenerios connector respond with 200 http status code and error response object in response
// For http status code other than 200 they send empty response back
+ event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&serde_json::json!({"error_response": std::str::from_utf8(&res.response).unwrap_or("")})));
+
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
@@ -240,12 +244,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz 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 {
response,
data: data.clone(),
@@ -256,8 +265,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -327,12 +337,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz PaymentsCompleteAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -343,8 +358,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -409,12 +425,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("Powertranz PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -425,8 +446,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -461,12 +483,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz CancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -495,8 +522,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -554,12 +582,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: powertranz::PowertranzBaseResponse = res
.response
.parse_struct("powertranz 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 {
response,
data: data.clone(),
@@ -570,8 +603,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 8dc3688da9e..54849f8bf1d 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -247,7 +247,7 @@ impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType {
}
// Common struct used in Payment, Capture, Void, Refund
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzBaseResponse {
transaction_type: u8,
@@ -475,7 +475,7 @@ pub struct PowertranzErrorResponse {
pub errors: Vec<Error>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Error {
pub code: String,
diff --git a/crates/router/src/connector/prophetpay.rs b/crates/router/src/connector/prophetpay.rs
index fc14f37a2b2..04b3e7b6d65 100644
--- a/crates/router/src/connector/prophetpay.rs
+++ b/crates/router/src/connector/prophetpay.rs
@@ -12,6 +12,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -107,11 +108,16 @@ impl ConnectorCommon for Prophetpay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: serde_json::Value = res
.response
.parse_struct("ProphetPayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
@@ -228,6 +234,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError>
where
@@ -238,6 +245,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.parse_struct("prophetpay ProphetpayTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -248,8 +258,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -325,6 +336,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError>
where
@@ -334,6 +346,10 @@ impl
.response
.parse_struct("prophetpay ProphetpayResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -344,8 +360,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -406,12 +423,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: prophetpay::ProphetpaySyncResponse = res
.response
.parse_struct("prophetpay 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 {
response,
data: data.clone(),
@@ -422,8 +444,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -500,8 +523,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res,event_builder)
}
*/
}
@@ -569,6 +593,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: prophetpay::ProphetpayRefundResponse = res
@@ -576,6 +601,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.parse_struct("prophetpay ProphetpayRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -586,8 +614,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -648,12 +677,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: prophetpay::ProphetpayRefundSyncResponse = res
.response
.parse_struct("prophetpay ProphetpayRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -664,8 +698,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs
index 23cffa3da22..b3b641b6d24 100644
--- a/crates/router/src/connector/prophetpay/transformers.rs
+++ b/crates/router/src/connector/prophetpay/transformers.rs
@@ -169,7 +169,7 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayTokenResponse {
hosted_tokenize_id: String,
@@ -366,7 +366,7 @@ impl TryFrom<&types::PaymentsSyncRouterData> for ProphetpaySyncRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayCompleteAuthResponse {
pub success: bool,
@@ -438,7 +438,7 @@ impl<F>
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpaySyncResponse {
success: bool,
@@ -601,7 +601,7 @@ impl<F> TryFrom<&ProphetpayRouterData<&types::RefundsRouterData<F>>> for Prophet
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundResponse {
pub success: bool,
@@ -646,7 +646,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, ProphetpayRefundResp
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundSyncResponse {
pub success: bool,
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index 5272a8ab21e..389893b5529 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -15,6 +15,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -86,6 +87,7 @@ impl ConnectorCommon for Rapyd {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
rapyd::RapydPaymentsResponse,
@@ -93,15 +95,20 @@ impl ConnectorCommon for Rapyd {
> = res.response.parse_struct("Rapyd ErrorResponse");
match response {
- Ok(response_data) => Ok(ErrorResponse {
- status_code: res.status_code,
- code: response_data.status.error_code,
- message: response_data.status.status.unwrap_or_default(),
- reason: response_data.status.message,
- attempt_status: None,
- connector_transaction_id: None,
- }),
+ Ok(response_data) => {
+ event_builder.map(|i| i.set_error_response_body(&response_data));
+ router_env::logger::info!(connector_response=?response_data);
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response_data.status.error_code,
+ message: response_data.status.status.unwrap_or_default(),
+ reason: response_data.status.message,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
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})));
logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "rapyd".to_owned())
}
@@ -239,12 +246,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -257,8 +267,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -358,12 +369,15 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -376,8 +390,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -454,19 +469,23 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: rapyd::RapydPaymentsResponse = res
.response
.parse_struct("Rapyd PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -558,6 +577,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: rapyd::RapydPaymentsResponse = res
@@ -565,6 +585,9 @@ impl
.parse_struct("RapydPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -588,8 +611,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -687,12 +711,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: rapyd::RefundResponse = res
.response
.parse_struct("rapyd RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -705,8 +732,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -717,12 +745,15 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: rapyd::RefundResponse = res
.response
.parse_struct("rapyd RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs
index 29d57ee28cd..72a9f6dbdbf 100644
--- a/crates/router/src/connector/riskified.rs
+++ b/crates/router/src/connector/riskified.rs
@@ -22,6 +22,7 @@ use crate::{
};
#[cfg(feature = "frm")]
use crate::{
+ events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
@@ -108,11 +109,16 @@ impl ConnectorCommon for Riskified {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: riskified::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
attempt_status: None,
@@ -184,12 +190,15 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmCheckoutRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedPaymentsResponse = res
.response
.parse_struct("RiskifiedPaymentsResponse Checkout")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
<frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -199,8 +208,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -312,6 +322,7 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmTransactionRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedTransactionResponse = res
@@ -319,6 +330,9 @@ impl
.parse_struct("RiskifiedPaymentsResponse Transaction")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
match response {
riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => {
<frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData {
@@ -339,8 +353,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -406,6 +421,7 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmFulfillmentRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedFulfilmentResponse = res
@@ -413,6 +429,9 @@ impl
.parse_struct("RiskifiedFulfilmentResponse fulfilment")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -423,8 +442,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index c38fac56efc..352ec4787a1 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -15,6 +15,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers, routes,
services::{
self,
@@ -85,12 +86,16 @@ impl ConnectorCommon for Shift4 {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: shift4::ErrorResponse = res
.response
.parse_struct("Shift4 ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response
@@ -269,12 +274,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: shift4::Shift4NonThreeDsResponse = res
.response
.parse_struct("Shift4NonThreeDsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -286,8 +296,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -346,19 +357,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: shift4::Shift4NonThreeDsResponse = res
.response
.parse_struct("Shift4NonThreeDsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -403,12 +420,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: shift4::Shift4NonThreeDsResponse = res
.response
.parse_struct("Shift4NonThreeDsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -434,8 +456,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -514,12 +537,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsInitRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsInitRouterData, errors::ConnectorError> {
let response: shift4::Shift4ThreeDsResponse = res
.response
.parse_struct("Shift4ThreeDsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -531,8 +559,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -596,12 +625,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: shift4::Shift4NonThreeDsResponse = res
.response
.parse_struct("Shift4NonThreeDsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -613,8 +647,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -670,12 +705,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: shift4::RefundResponse = res
.response
.parse_struct("RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::ResponseRouterData {
response,
data: data.clone(),
@@ -688,8 +728,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -737,12 +778,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: shift4::RefundResponse =
res.response
.parse_struct("shift4 RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -755,8 +799,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 949082f4253..97c19c49af8 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -555,7 +555,7 @@ pub struct Shift4WebhookObjectResource {
pub data: serde_json::Value,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4NonThreeDsResponse {
pub id: String,
pub currency: String,
@@ -566,7 +566,7 @@ pub struct Shift4NonThreeDsResponse {
pub flow: Option<FlowResponse>,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4ThreeDsResponse {
pub enrolled: bool,
pub version: Option<String>,
@@ -575,7 +575,7 @@ pub struct Shift4ThreeDsResponse {
pub token: Token,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Token {
pub id: String,
pub created: i64,
@@ -593,7 +593,7 @@ pub struct Token {
pub three_d_secure_info: ThreeDSecureInfo,
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct ThreeDSecureInfo {
pub amount: i64,
pub currency: String,
@@ -605,7 +605,7 @@ pub struct ThreeDSecureInfo {
pub authentication_flow: Option<SecretSerdeValue>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FlowResponse {
pub next_action: Option<NextAction>,
@@ -613,13 +613,13 @@ pub struct FlowResponse {
pub return_url: Option<Url>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Redirect {
pub redirect_url: Option<Url>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NextAction {
Redirect,
@@ -810,12 +810,12 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorResponse {
pub error: ApiErrorResponse,
}
-#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct ApiErrorResponse {
pub code: Option<String>,
pub message: String,
diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs
index 544dfd137db..7d19df12221 100644
--- a/crates/router/src/connector/signifyd.rs
+++ b/crates/router/src/connector/signifyd.rs
@@ -19,6 +19,7 @@ use crate::{
};
#[cfg(feature = "frm")]
use crate::{
+ events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
@@ -76,11 +77,16 @@ impl ConnectorCommon for Signifyd {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: signifyd::SignifydErrorResponse = res
.response
.parse_struct("SignifydErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
@@ -251,12 +257,17 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmSaleRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmSaleRouterData, errors::ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Sale")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
<frm_types::FrmSaleRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -266,8 +277,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -335,12 +347,15 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmCheckoutRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Checkout")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
<frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -350,8 +365,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -421,12 +437,15 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmTransactionRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Transaction")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
<frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -436,8 +455,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -507,12 +527,15 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmFulfillmentRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
let response: signifyd::FrmFullfillmentSignifydApiResponse = res
.response
.parse_struct("FrmFullfillmentSignifydApiResponse Sale")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -522,8 +545,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -593,12 +617,15 @@ impl
fn handle_response(
&self,
data: &frm_types::FrmRecordReturnRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> {
let response: signifyd::SignifydPaymentsRecordReturnResponse = res
.response
.parse_struct("SignifydPaymentsResponse Transaction")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
<frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -608,8 +635,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs
index 66d6f0e48cd..b738ec00fcf 100644
--- a/crates/router/src/connector/signifyd/transformers/api.rs
+++ b/crates/router/src/connector/signifyd/transformers/api.rs
@@ -211,7 +211,7 @@ impl<F, T>
}
}
-#[derive(Debug, Deserialize, PartialEq)]
+#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct SignifydErrorResponse {
pub messages: Vec<String>,
pub errors: serde_json::Value,
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs
index e210a851dfc..ea6bd42ffe0 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/router/src/connector/square.rs
@@ -17,6 +17,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -96,12 +97,16 @@ impl ConnectorCommon for Square {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: square::SquareErrorResponse = res
.response
.parse_struct("SquareErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let mut reason_list = Vec::new();
for error_iter in response.errors.iter() {
if let Some(error) = error_iter.detail.clone() {
@@ -289,6 +294,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -299,6 +305,9 @@ impl
.parse_struct("SquareTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -308,8 +317,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -378,6 +388,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeSessionTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
let response: square::SquareSessionResponse = res
@@ -385,6 +396,9 @@ impl
.parse_struct("SquareSessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -395,8 +409,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -458,12 +473,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -474,8 +494,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -529,12 +550,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -545,8 +571,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -603,12 +630,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -619,8 +651,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -669,12 +702,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -685,8 +723,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -742,12 +781,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: square::RefundResponse = res
.response
.parse_struct("SquareRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -758,8 +802,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -806,6 +851,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: square::RefundResponse = res
@@ -813,6 +859,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.parse_struct("SquareRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -823,8 +872,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 7343ef58bb0..e159b1d8ade 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -200,7 +200,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SquareSessionResponse {
session_id: String,
@@ -225,7 +225,7 @@ impl<F, T>
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SquareTokenResponse {
card_nonce: Secret<String>,
}
@@ -373,7 +373,7 @@ pub struct SquarePaymentsResponseDetails {
amount_money: SquarePaymentsAmountData,
reference_id: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SquarePaymentsResponse {
payment: SquarePaymentsResponseDetails,
}
@@ -456,7 +456,7 @@ pub struct SquareRefundResponseDetails {
status: RefundStatus,
id: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
refund: SquareRefundResponseDetails,
}
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs
index 75bb8e68184..db090cdf78b 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/router/src/connector/stax.rs
@@ -14,6 +14,7 @@ use crate::{
configs::settings,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -98,6 +99,7 @@ impl ConnectorCommon for Stax {
fn build_error_response(
&self,
res: Response,
+ _event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
@@ -194,6 +196,7 @@ impl
fn handle_response(
&self,
data: &types::ConnectorCustomerRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError>
where
@@ -204,6 +207,9 @@ impl
.parse_struct("StaxCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -214,8 +220,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -277,6 +284,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -287,6 +295,9 @@ impl
.parse_struct("StaxTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -297,8 +308,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -400,12 +412,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -416,8 +433,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -471,12 +489,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -487,8 +510,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -557,12 +581,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -573,8 +602,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -623,12 +653,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -639,8 +674,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -714,12 +750,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: stax::RefundResponse = res
.response
.parse_struct("StaxRefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -730,8 +771,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -778,12 +820,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: stax::RefundResponse = res
.response
.parse_struct("StaxRefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -794,8 +841,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 596ea1145ec..a9bb68d558e 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -167,7 +167,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct StaxCustomerResponse {
id: Secret<String>,
}
@@ -277,7 +277,7 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct StaxTokenResponse {
id: Secret<String>,
}
@@ -298,19 +298,19 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, StaxTokenResponse, T, types::Pay
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StaxPaymentResponseTypes {
Charge,
PreAuth,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct StaxChildCapture {
id: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct StaxPaymentsResponse {
success: bool,
id: String,
@@ -406,14 +406,14 @@ impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundReq
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ChildTransactionsInResponse {
id: String,
success: bool,
created_at: String,
total: f64,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
success: bool,
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index c151c5af455..01848f704e4 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -17,7 +17,8 @@ use crate::{
errors::{self, CustomResult},
payments,
},
- headers, logger,
+ events::connector_api_logs::ConnectorEvent,
+ headers,
services::{
self,
request::{self, Mask},
@@ -177,13 +178,16 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: stripe::StripeSourceResponse = res
.response
.parse_struct("StripeSourceResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -196,12 +200,16 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -299,6 +307,7 @@ impl
fn handle_response(
&self,
data: &types::ConnectorCustomerRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError>
where
@@ -308,7 +317,9 @@ impl
.response
.parse_struct("StripeCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -321,12 +332,15 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
@@ -421,6 +435,7 @@ impl
fn handle_response(
&self,
data: &types::TokenizationRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
@@ -430,7 +445,9 @@ impl
.response
.parse_struct("StripeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -443,12 +460,15 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
@@ -551,6 +571,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError>
where
@@ -561,7 +582,10 @@ impl
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -573,12 +597,15 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
@@ -673,6 +700,7 @@ impl
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError>
where
@@ -686,7 +714,10 @@ impl
.response
.parse_struct("SetupIntentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -698,7 +729,10 @@ impl
.response
.parse_struct("PaymentIntentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -714,12 +748,14 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
@@ -843,18 +879,57 @@ impl
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
match &data.request.payment_method_data {
api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
- stripe::get_bank_transfer_authorize_response(data, res, bank_transfer_data.deref())
+ match bank_transfer_data.deref() {
+ api_models::payments::BankTransferData::AchBankTransfer { .. }
+ | api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
+ let response: stripe::ChargesResponse = res
+ .response
+ .parse_struct("ChargesResponse")
+ .change_context(
+ errors::ConnectorError::ResponseDeserializationFailed,
+ )?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ _ => {
+ let response: stripe::PaymentIntentResponse = res
+ .response
+ .parse_struct("PaymentIntentResponse")
+ .change_context(
+ errors::ConnectorError::ResponseDeserializationFailed,
+ )?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ }
}
_ => {
let response: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
@@ -869,12 +944,14 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -970,13 +1047,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -988,12 +1069,16 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1110,6 +1195,7 @@ impl
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
@@ -1128,7 +1214,10 @@ impl
.response
.parse_struct("SetupIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1140,12 +1229,16 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1239,13 +1332,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: stripe::RefundResponse =
res.response
.parse_struct("Stripe RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1257,12 +1354,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1340,6 +1441,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn handle_response(
&self,
data: &types::RefundsRouterData<api::RSync>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
@@ -1349,7 +1451,10 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
res.response
.parse_struct("Stripe RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -1361,12 +1466,16 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1488,6 +1597,7 @@ impl
fn handle_response(
&self,
data: &types::UploadFileRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>,
@@ -1497,7 +1607,8 @@ impl
.response
.parse_struct("Stripe FileUploadResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::UploadFileRouterData {
response: Ok(types::UploadFileResponse {
provider_file_id: response.file_id,
@@ -1509,12 +1620,16 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1592,6 +1707,7 @@ impl
fn handle_response(
&self,
data: &types::RetrieveFileRouterData,
+ _event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
@@ -1602,6 +1718,7 @@ impl
errors::ConnectorError,
> {
let response = res.response;
+ router_env::logger::info!(connector_response=?response);
Ok(types::RetrieveFileRouterData {
response: Ok(types::RetrieveFileResponse {
file_data: response.to_vec(),
@@ -1613,12 +1730,15 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
@@ -1719,13 +1839,15 @@ impl
fn handle_response(
&self,
data: &types::SubmitEvidenceRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> {
let response: stripe::DisputeObj = res
.response
.parse_struct("Stripe DisputeObj")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::info!(connector_response=?response);
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::SubmitEvidenceRouterData {
response: Ok(types::SubmitEvidenceResponse {
dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
@@ -1738,12 +1860,16 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 3558d6e487b..6a89232d4e8 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Deref};
use api_models::{self, enums as api_enums, payments};
use common_utils::{
errors::CustomResult,
- ext_traits::{ByteSliceExt, BytesExt},
+ ext_traits::ByteSliceExt,
pii::{self, Email},
request::RequestContent,
};
@@ -186,7 +186,7 @@ pub struct TokenRequest {
pub token_data: StripePaymentMethodData,
}
-#[derive(Debug, Eq, PartialEq, Deserialize)]
+#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeTokenResponse {
pub id: String,
pub object: String,
@@ -201,7 +201,7 @@ pub struct CustomerRequest {
pub source: Option<String>,
}
-#[derive(Debug, Eq, PartialEq, Deserialize)]
+#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeCustomerResponse {
pub id: String,
pub description: Option<String>,
@@ -220,7 +220,7 @@ pub struct ChargesRequest {
pub meta_data: Option<HashMap<String, String>>,
}
-#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ChargesResponse {
pub id: String,
pub amount: u64,
@@ -2085,7 +2085,7 @@ impl From<StripePaymentStatus> for enums::AttemptStatus {
}
}
-#[derive(Debug, Default, Eq, PartialEq, Deserialize)]
+#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentIntentResponse {
pub id: String,
pub object: String,
@@ -2182,7 +2182,7 @@ pub struct LastPaymentError {
decline_code: Option<String>,
}
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Serialize)]
pub struct PaymentIntentSyncResponse {
#[serde(flatten)]
payment_intent_fields: PaymentIntentResponse,
@@ -2190,20 +2190,20 @@ pub struct PaymentIntentSyncResponse {
pub latest_charge: Option<StripeChargeEnum>,
}
-#[derive(Deserialize, Debug, Clone)]
+#[derive(Deserialize, Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum StripeChargeEnum {
ChargeId(String),
ChargeObject(StripeCharge),
}
-#[derive(Deserialize, Clone, Debug)]
+#[derive(Deserialize, Clone, Debug, Serialize)]
pub struct StripeCharge {
pub id: String,
pub payment_method_details: Option<StripePaymentMethodDetailsResponse>,
}
-#[derive(Deserialize, Clone, Debug)]
+#[derive(Deserialize, Clone, Debug, Serialize)]
pub struct StripeBankRedirectDetails {
#[serde(rename = "generated_sepa_debit")]
attached_payment_method: Option<String>,
@@ -2217,7 +2217,7 @@ impl Deref for PaymentIntentSyncResponse {
}
}
-#[derive(Deserialize, Clone, Debug)]
+#[derive(Deserialize, Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum StripePaymentMethodDetailsResponse {
//only ideal, sofort and bancontact is supported by stripe for recurring payment in bank redirect
@@ -2302,7 +2302,7 @@ impl From<SetupIntentResponse> for PaymentIntentResponse {
}
}
-#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct SetupIntentResponse {
pub id: String,
pub object: String,
@@ -2627,7 +2627,7 @@ impl ForeignFrom<Option<LatestAttempt>> for Option<String> {
}
}
-#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", remote = "Self")]
pub enum StripeNextActionResponse {
CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse),
@@ -2686,6 +2686,27 @@ impl<'de> Deserialize<'de> for StripeNextActionResponse {
}
}
+impl Serialize for StripeNextActionResponse {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ match *self {
+ Self::CashappHandleRedirectOrDisplayQrCode(ref i) => {
+ serde::Serialize::serialize(i, serializer)
+ }
+ Self::RedirectToUrl(ref i) => serde::Serialize::serialize(i, serializer),
+ Self::AlipayHandleRedirect(ref i) => serde::Serialize::serialize(i, serializer),
+ Self::VerifyWithMicrodeposits(ref i) => serde::Serialize::serialize(i, serializer),
+ Self::WechatPayDisplayQrCode(ref i) => serde::Serialize::serialize(i, serializer),
+ Self::DisplayBankTransferInstructions(ref i) => {
+ serde::Serialize::serialize(i, serializer)
+ }
+ Self::NoNextActionBody => serde::Serialize::serialize("NoNextActionBody", serializer),
+ }
+ }
+}
+
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeRedirectToUrlResponse {
return_url: String,
@@ -2701,7 +2722,7 @@ pub struct WechatPayRedirectToQr {
image_data_url: Url,
}
-#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeVerifyWithMicroDepositsResponse {
hosted_verification_url: Url,
}
@@ -3013,13 +3034,13 @@ pub struct MitExemption {
pub network_transaction_id: Secret<String>,
}
-#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum LatestAttempt {
PaymentIntentAttempt(LatestPaymentAttempt),
SetupAttempt(String),
}
-#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)]
+#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct LatestPaymentAttempt {
pub payment_method_options: Option<StripePaymentMethodOptions>,
}
@@ -3588,40 +3609,6 @@ pub fn get_bank_transfer_request_data(
}
}
-pub fn get_bank_transfer_authorize_response(
- data: &types::PaymentsAuthorizeRouterData,
- res: types::Response,
- bank_transfer_data: &api_models::payments::BankTransferData,
-) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- match bank_transfer_data {
- api_models::payments::BankTransferData::AchBankTransfer { .. }
- | api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
- let response: ChargesResponse = res
- .response
- .parse_struct("ChargesResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- _ => {
- let response: PaymentIntentResponse = res
- .response
- .parse_struct("PaymentIntentResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
-}
-
pub fn construct_file_upload_request(
file_upload_router_data: types::UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
@@ -3636,7 +3623,7 @@ pub fn construct_file_upload_request(
Ok(multipart)
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
@@ -3768,7 +3755,7 @@ impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct DisputeObj {
#[serde(rename = "id")]
pub dispute_id: String,
diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs
index 61ee2e2659d..18775dd3981 100644
--- a/crates/router/src/connector/trustpay.rs
+++ b/crates/router/src/connector/trustpay.rs
@@ -21,6 +21,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -109,6 +110,7 @@ impl ConnectorCommon for Trustpay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
trustpay::TrustpayErrorResponse,
@@ -117,6 +119,8 @@ impl ConnectorCommon for Trustpay {
match response {
Ok(response_data) => {
+ event_builder.map(|i| i.set_error_response_body(&response_data));
+ router_env::logger::info!(connector_response=?response_data);
let error_list = response_data.errors.clone().unwrap_or_default();
let option_error_code_message = get_error_code_error_message_based_on_priority(
self.clone(),
@@ -147,6 +151,7 @@ impl ConnectorCommon for Trustpay {
})
}
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})));
logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "trustpay".to_owned())
}
@@ -279,12 +284,17 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayAuthUpdateResponse = res
.response
.parse_struct("trustpay TrustpayAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -296,11 +306,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: trustpay::TrustpayAccessTokenErrorResponse = res
.response
.parse_struct("Trustpay AccessTokenErrorResponse")
.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.result_info.result_code.to_string(),
@@ -371,19 +386,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -480,12 +501,17 @@ impl
fn handle_response(
&self,
data: &types::PaymentsPreProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayCreateIntentResponse = res
.response
.parse_struct("TrustpayCreateIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -497,8 +523,9 @@ impl
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -590,12 +617,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -607,8 +639,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -690,12 +723,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: trustpay::RefundResponse = res
.response
.parse_struct("trustpay 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 {
response,
data: data.clone(),
@@ -707,8 +745,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -767,12 +806,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: trustpay::RefundResponse = res
.response
.parse_struct("trustpay 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 {
response,
data: data.clone(),
@@ -784,8 +828,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index c266753423e..71286bda3f1 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -946,7 +946,7 @@ pub struct ResultInfo {
pub correlation_id: Option<String>,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct TrustpayAuthUpdateResponse {
pub access_token: Option<Secret<String>>,
pub token_type: Option<String>,
@@ -955,7 +955,7 @@ pub struct TrustpayAuthUpdateResponse {
pub result_info: ResultInfo,
}
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TrustpayAccessTokenErrorResponse {
pub result_info: ResultInfo,
@@ -1038,7 +1038,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsPreProcessingRouterData>>
}
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayCreateIntentResponse {
// TrustPay's authorization secrets used by client
@@ -1050,14 +1050,14 @@ pub struct TrustpayCreateIntentResponse {
pub instance_id: String,
}
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum InitResultData {
AppleInitResultData(TrustpayApplePayResponse),
GoogleInitResultData(TrustpayGooglePayResponse),
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTransactionInfo {
pub country_code: api_models::enums::CountryAlpha2,
@@ -1066,14 +1066,14 @@ pub struct GooglePayTransactionInfo {
pub total_price: String,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayMerchantInfo {
pub merchant_name: String,
pub merchant_id: String,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayAllowedPaymentMethods {
#[serde(rename = "type")]
@@ -1082,14 +1082,14 @@ pub struct GooglePayAllowedPaymentMethods {
pub tokenization_specification: GpayTokenizationSpecification,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayTokenParameters {
pub gateway: String,
pub gateway_merchant_id: String,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayTokenizationSpecification {
#[serde(rename = "type")]
@@ -1097,14 +1097,14 @@ pub struct GpayTokenizationSpecification {
pub parameters: GpayTokenParameters,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpayAllowedMethodsParameters {
pub allowed_auth_methods: Vec<String>,
pub allowed_card_networks: Vec<String>,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayGooglePayResponse {
pub merchant_info: GooglePayMerchantInfo,
@@ -1112,14 +1112,14 @@ pub struct TrustpayGooglePayResponse {
pub transaction_info: GooglePayTransactionInfo,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkSecretInfo {
pub display: Secret<String>,
pub payment: Secret<String>,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustpayApplePayResponse {
pub country_code: api_models::enums::CountryAlpha2,
@@ -1129,7 +1129,7 @@ pub struct TrustpayApplePayResponse {
pub total: ApplePayTotalInfo,
}
-#[derive(Clone, Default, Debug, Deserialize)]
+#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTotalInfo {
pub label: String,
diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs
index 8c19f9f823a..8117bc8901b 100644
--- a/crates/router/src/connector/tsys.rs
+++ b/crates/router/src/connector/tsys.rs
@@ -11,6 +11,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -189,12 +190,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("Tsys 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 {
response,
data: data.clone(),
@@ -205,8 +211,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -266,12 +273,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: tsys::TsysSyncResponse = res
.response
.parse_struct("tsys 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 {
response,
data: data.clone(),
@@ -282,8 +294,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -345,12 +358,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("Tsys PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -361,8 +379,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -420,12 +439,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: tsys::TsysPaymentsResponse = res
.response
.parse_struct("PaymentCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -435,8 +459,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -495,12 +520,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: tsys::RefundResponse = res
.response
.parse_struct("tsys 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 {
response,
data: data.clone(),
@@ -511,8 +541,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -570,12 +601,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: tsys::TsysSyncResponse = res
.response
.parse_struct("tsys 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 {
response,
data: data.clone(),
@@ -586,8 +622,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index dd700d11bcb..a01576bbb20 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -111,14 +111,14 @@ impl TryFrom<&types::ConnectorAuthType> for TsysAuthType {
}
// PaymentsResponse
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsysPaymentStatus {
Pass,
Fail,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsysTransactionStatus {
Approved,
@@ -142,7 +142,7 @@ impl From<TsysTransactionDetails> for enums::AttemptStatus {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysErrorResponse {
pub status: TsysPaymentStatus,
@@ -150,7 +150,7 @@ pub struct TsysErrorResponse {
pub response_message: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysTransactionDetails {
#[serde(rename = "transactionID")]
@@ -159,7 +159,7 @@ pub struct TsysTransactionDetails {
transaction_status: TsysTransactionStatus,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysPaymentsSyncResponse {
pub status: TsysPaymentStatus,
@@ -168,7 +168,7 @@ pub struct TsysPaymentsSyncResponse {
pub transaction_details: TsysTransactionDetails,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysResponse {
pub status: TsysPaymentStatus,
@@ -178,14 +178,14 @@ pub struct TsysResponse {
pub transaction_id: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TsysResponseTypes {
SuccessResponse(TsysResponse),
ErrorResponse(TsysErrorResponse),
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[allow(clippy::enum_variant_names)]
pub enum TsysPaymentsResponse {
AuthResponse(TsysResponseTypes),
@@ -195,13 +195,13 @@ pub enum TsysPaymentsResponse {
}
fn get_error_response(
- connector_error_response: TsysErrorResponse,
+ connector_response: TsysErrorResponse,
status_code: u16,
) -> types::ErrorResponse {
types::ErrorResponse {
- code: connector_error_response.response_code,
- message: connector_error_response.response_message.clone(),
- reason: Some(connector_error_response.response_message),
+ code: connector_response.response_code,
+ message: connector_response.response_message.clone(),
+ reason: Some(connector_response.response_message),
status_code,
attempt_status: None,
connector_transaction_id: None,
@@ -260,8 +260,8 @@ impl<F, T>
Ok(get_payments_response(auth_response)),
enums::AttemptStatus::Authorized,
),
- TsysResponseTypes::ErrorResponse(connector_error_response) => (
- Err(get_error_response(connector_error_response, item.http_code)),
+ TsysResponseTypes::ErrorResponse(connector_response) => (
+ Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::AuthorizationFailed,
),
},
@@ -270,8 +270,8 @@ impl<F, T>
Ok(get_payments_response(sale_response)),
enums::AttemptStatus::Charged,
),
- TsysResponseTypes::ErrorResponse(connector_error_response) => (
- Err(get_error_response(connector_error_response, item.http_code)),
+ TsysResponseTypes::ErrorResponse(connector_response) => (
+ Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::Failure,
),
},
@@ -280,8 +280,8 @@ impl<F, T>
Ok(get_payments_response(capture_response)),
enums::AttemptStatus::Charged,
),
- TsysResponseTypes::ErrorResponse(connector_error_response) => (
- Err(get_error_response(connector_error_response, item.http_code)),
+ TsysResponseTypes::ErrorResponse(connector_response) => (
+ Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::CaptureFailed,
),
},
@@ -290,8 +290,8 @@ impl<F, T>
Ok(get_payments_response(void_response)),
enums::AttemptStatus::Voided,
),
- TsysResponseTypes::ErrorResponse(connector_error_response) => (
- Err(get_error_response(connector_error_response, item.http_code)),
+ TsysResponseTypes::ErrorResponse(connector_response) => (
+ Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::VoidFailed,
),
},
@@ -340,14 +340,14 @@ impl TryFrom<&types::PaymentsSyncRouterData> for TsysSyncRequest {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SearchResponseTypes {
SuccessResponse(TsysPaymentsSyncResponse),
ErrorResponse(TsysErrorResponse),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysSyncResponse {
search_transaction_response: SearchResponseTypes,
@@ -366,8 +366,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, TsysSyncResponse, T, types::Paym
Ok(get_payments_sync_response(&search_response)),
enums::AttemptStatus::from(search_response.transaction_details),
),
- SearchResponseTypes::ErrorResponse(connector_error_response) => (
- Err(get_error_response(connector_error_response, item.http_code)),
+ SearchResponseTypes::ErrorResponse(connector_response) => (
+ Err(get_error_response(connector_response, item.http_code)),
item.data.status,
),
};
@@ -498,7 +498,7 @@ impl From<TsysTransactionDetails> for enums::RefundStatus {
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundResponse {
return_response: TsysResponseTypes,
@@ -517,8 +517,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
connector_refund_id: return_response.transaction_id,
refund_status: enums::RefundStatus::from(return_response.status),
}),
- TsysResponseTypes::ErrorResponse(connector_error_response) => {
- Err(get_error_response(connector_error_response, item.http_code))
+ TsysResponseTypes::ErrorResponse(connector_response) => {
+ Err(get_error_response(connector_response, item.http_code))
}
};
Ok(Self {
@@ -557,8 +557,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, TsysSyncResponse>>
refund_status: enums::RefundStatus::from(search_response.transaction_details),
})
}
- SearchResponseTypes::ErrorResponse(connector_error_response) => {
- Err(get_error_response(connector_error_response, item.http_code))
+ SearchResponseTypes::ErrorResponse(connector_response) => {
+ Err(get_error_response(connector_response, item.http_code))
}
};
Ok(Self {
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs
index f125f90d93a..4a08bc1ad6b 100644
--- a/crates/router/src/connector/volt.rs
+++ b/crates/router/src/connector/volt.rs
@@ -12,6 +12,7 @@ use super::utils;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -112,12 +113,16 @@ impl ConnectorCommon for Volt {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: volt::VoltErrorResponse = res
.response
.parse_struct("VoltErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let reason = match &response.exception.error_list {
Some(error_list) => error_list
.iter()
@@ -207,6 +212,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
data: &types::RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
let response: volt::VoltAuthUpdateResponse = res
@@ -214,6 +220,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("Volt VoltAuthUpdateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -224,6 +233,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// auth error have different structure than common error
let response: volt::VoltAuthErrorResponse = res
@@ -231,6 +241,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.parse_struct("VoltAuthErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
@@ -328,12 +341,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: volt::VoltPaymentsResponse = res
.response
.parse_struct("Volt 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 {
response,
data: data.clone(),
@@ -344,8 +362,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -398,12 +417,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: volt::VoltPaymentsResponseData = res
.response
.parse_struct("volt 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 {
response,
data: data.clone(),
@@ -414,8 +438,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -473,12 +498,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: volt::VoltPaymentsResponse = res
.response
.parse_struct("Volt PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -489,8 +519,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -561,12 +592,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: volt::RefundResponse = res
.response
.parse_struct("volt 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 {
response,
data: data.clone(),
@@ -577,8 +613,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index b1d77f3416f..ccb482d5b7c 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -185,7 +185,7 @@ impl TryFrom<&types::RefreshTokenRouterData> for VoltAuthUpdateRequest {
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VoltAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
@@ -451,7 +451,7 @@ impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundReq
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
@@ -598,7 +598,7 @@ pub struct VoltErrorResponse {
pub exception: VoltErrorException,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct VoltAuthErrorResponse {
pub code: u64,
pub message: String,
diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs
index 66ccf22c100..152786b46a3 100644
--- a/crates/router/src/connector/wise.rs
+++ b/crates/router/src/connector/wise.rs
@@ -13,6 +13,7 @@ use self::transformers as wise;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -82,11 +83,16 @@ impl ConnectorCommon for Wise {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: wise::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let default_status = response.status.unwrap_or_default().to_string();
match response.errors {
Some(errs) => {
@@ -278,12 +284,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCancel>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
let response: wise::WisePayoutResponse = res
.response
.parse_struct("WisePayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -294,11 +305,16 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: wise::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let def_res = response.status.unwrap_or_default().to_string();
let errors = response.errors.unwrap_or_default();
let (code, message) = if let Some(e) = errors.first() {
@@ -374,12 +390,17 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoQuote>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> {
let response: wise::WisePayoutQuoteResponse = res
.response
.parse_struct("WisePayoutQuoteResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -390,8 +411,9 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -449,12 +471,17 @@ impl
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoRecipient>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> {
let response: wise::WiseRecipientCreateResponse = res
.response
.parse_struct("WiseRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -465,8 +492,9 @@ impl
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -560,12 +588,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCreate>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
let response: wise::WisePayoutResponse = res
.response
.parse_struct("WisePayoutResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -576,8 +609,9 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -667,12 +701,17 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoFulfill>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
let response: wise::WiseFulfillResponse = res
.response
.parse_struct("WiseFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -683,8 +722,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs
index b213c62212c..82ae59205b1 100644
--- a/crates/router/src/connector/wise/transformers.rs
+++ b/crates/router/src/connector/wise/transformers.rs
@@ -3,9 +3,7 @@ use api_models::payouts::PayoutMethodData;
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use masking::Secret;
-use serde::Deserialize;
-#[cfg(feature = "payouts")]
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -40,7 +38,7 @@ impl TryFrom<&types::ConnectorAuthType> for WiseAuthType {
}
// Wise error response
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponse {
pub timestamp: Option<String>,
pub errors: Option<Vec<SubError>>,
@@ -51,7 +49,7 @@ pub struct ErrorResponse {
pub path: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct SubError {
pub code: String,
pub message: String,
@@ -140,7 +138,7 @@ pub struct WiseAddressDetails {
#[allow(dead_code)]
#[cfg(feature = "payouts")]
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseRecipientCreateResponse {
id: i64,
@@ -179,7 +177,7 @@ pub enum WisePayOutOption {
#[allow(dead_code)]
#[cfg(feature = "payouts")]
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutQuoteResponse {
source_amount: f64,
@@ -196,7 +194,7 @@ pub struct WisePayoutQuoteResponse {
}
#[cfg(feature = "payouts")]
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WiseRateType {
#[default]
@@ -225,7 +223,7 @@ pub struct WiseTransferDetails {
#[allow(dead_code)]
#[cfg(feature = "payouts")]
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WisePayoutResponse {
id: i64,
@@ -265,7 +263,7 @@ pub enum FundType {
#[allow(dead_code)]
#[cfg(feature = "payouts")]
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WiseFulfillResponse {
status: WiseStatus,
diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs
index a1ca8a110bc..e46062a312b 100644
--- a/crates/router/src/connector/worldline.rs
+++ b/crates/router/src/connector/worldline.rs
@@ -16,6 +16,7 @@ use crate::{
configs::settings::Connectors,
consts,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers, logger,
services::{
self,
@@ -122,11 +123,16 @@ impl ConnectorCommon for Worldline {
fn build_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: worldline::ErrorResponse = res
.response
.parse_struct("Worldline ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let error = response.errors.into_iter().next().unwrap_or_default();
Ok(ErrorResponse {
status_code: res.status_code,
@@ -247,13 +253,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: worldline::PaymentResponse = res
.response
.parse_struct("Worldline PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- logger::debug!(payments_cancel_response=?response);
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -265,8 +275,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -326,13 +337,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
logger::debug!(payment_sync_response=?res);
@@ -341,6 +354,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.parse_struct("Worldline Payment")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
response.capture_method = data.request.capture_method.unwrap_or_default();
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -429,6 +446,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
types::PaymentsCaptureData,
types::PaymentsResponseData,
>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
@@ -445,6 +463,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.parse_struct("Worldline PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
response.payment.capture_method = enums::CaptureMethod::Manual;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -456,8 +478,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -540,6 +563,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
logger::debug!(payment_authorize_response=?res);
@@ -548,6 +572,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.parse_struct("Worldline PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
response.payment.capture_method = data.request.capture_method.unwrap_or_default();
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -560,8 +586,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -625,6 +652,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
logger::debug!(target: "router::connector::worldline", response=?res);
@@ -632,6 +660,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("Worldline RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -644,8 +674,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -701,6 +732,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
logger::debug!(target: "router::connector::worldline", response=?res);
@@ -708,6 +740,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.response
.parse_struct("Worldline RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
types::ResponseRouterData {
response,
data: data.clone(),
@@ -720,8 +754,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index a21c88a2ce9..1eb22fc52d2 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -528,7 +528,7 @@ impl TryFrom<&types::ConnectorAuthType> for WorldlineAuthType {
}
}
-#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Captured,
@@ -573,7 +573,7 @@ impl ForeignFrom<(PaymentStatus, enums::CaptureMethod)> for enums::AttemptStatus
/// capture_method is not part of response from connector.
/// This is used to decide payment status while converting connector response to RouterData.
/// To keep this try_from logic generic in case of AUTHORIZE, SYNC and CAPTURE flows capture_method will be set from RouterData request.
-#[derive(Default, Debug, Clone, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct Payment {
pub id: String,
pub status: PaymentStatus,
@@ -607,20 +607,20 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData
}
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub payment: Payment,
pub merchant_action: Option<MerchantAction>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAction {
pub redirect_data: RedirectData,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct RedirectData {
#[serde(rename = "redirectURL")]
pub redirect_url: Url,
@@ -688,7 +688,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldlineRefundRequest {
}
#[allow(dead_code)]
-#[derive(Debug, Default, Deserialize, Clone)]
+#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Cancelled,
@@ -708,7 +708,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
@@ -750,7 +750,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
}
}
-#[derive(Default, Debug, Deserialize, PartialEq)]
+#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Error {
pub code: Option<String>,
@@ -758,7 +758,7 @@ pub struct Error {
pub message: Option<String>,
}
-#[derive(Default, Debug, Deserialize, PartialEq)]
+#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub error_id: Option<String>,
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index d4ac530172d..fa534a8806f 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -15,6 +15,7 @@ use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -84,11 +85,16 @@ impl ConnectorCommon for Worldpay {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: WorldpayErrorResponse = res
.response
.parse_struct("WorldpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_name,
@@ -201,6 +207,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError>
where
@@ -214,6 +221,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::PaymentsCancelRouterData {
status: enums::AttemptStatus::Voided,
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -235,8 +244,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -298,13 +308,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: WorldpayEventResponse =
@@ -312,6 +324,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
Ok(types::PaymentsSyncRouterData {
status: enums::AttemptStatus::from(response.last_event),
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -364,6 +379,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
match res.status_code {
@@ -372,6 +388,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::PaymentsCaptureRouterData {
status: enums::AttemptStatus::Charged,
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -406,8 +424,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -486,12 +505,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: WorldpayPaymentsResponse = res
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
@@ -503,8 +527,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -571,6 +596,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
match res.status_code {
@@ -579,6 +605,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.response
.parse_struct("Worldpay PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::RefundExecuteRouterData {
response: Ok(types::RefundsResponseData {
connector_refund_id: ResponseIdStr::try_from(response.links)?.id,
@@ -594,8 +622,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -642,12 +671,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: WorldpayEventResponse =
res.response
.parse_struct("Worldpay EventResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(types::RefundSyncRouterData {
response: Ok(types::RefundsResponseData {
connector_refund_id: data.request.refund_id.clone(),
@@ -660,8 +692,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs
index 0d5634c40c3..537e97cb577 100644
--- a/crates/router/src/connector/zen.rs
+++ b/crates/router/src/connector/zen.rs
@@ -16,6 +16,7 @@ use crate::{
errors::{self, CustomResult},
payments,
},
+ events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
@@ -104,12 +105,15 @@ impl ConnectorCommon for Zen {
fn build_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: zen::ZenErrorResponse = res
.response
.parse_struct("Zen ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- router_env::logger::info!(error_response=?response);
+
+ event_builder.map(|i| i.set_error_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
@@ -265,12 +269,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
@@ -282,8 +288,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -334,12 +341,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::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 {
response,
@@ -351,8 +360,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -455,13 +465,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: zen::RefundResponse = res
.response
.parse_struct("zen 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 {
response,
data: data.clone(),
@@ -472,8 +485,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
@@ -522,13 +536,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: zen::RefundResponse = res
.response
.parse_struct("zen 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 {
response,
data: data.clone(),
@@ -539,8 +557,9 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 0adae0d00bd..ebea61304a1 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -819,7 +819,7 @@ impl TryFrom<&api_models::payments::GiftCardData> for ZenPaymentsRequest {
}
// PaymentsResponse
-#[derive(Debug, Default, Deserialize, Clone, strum::Display)]
+#[derive(Debug, Default, Deserialize, Clone, strum::Display, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ZenPaymentStatus {
Authorized,
@@ -849,7 +849,7 @@ impl ForeignTryFrom<(ZenPaymentStatus, Option<ZenActions>)> for enums::AttemptSt
}
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiResponse {
status: ZenPaymentStatus,
@@ -860,14 +860,14 @@ pub struct ApiResponse {
reject_reason: Option<String>,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ZenPaymentsResponse {
ApiResponse(ApiResponse),
CheckoutResponse(CheckoutResponse),
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutResponse {
redirect_url: url::Url,
@@ -1034,7 +1034,7 @@ impl<F> TryFrom<&ZenRouterData<&types::RefundsRouterData<F>>> for ZenRefundReque
}
}
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Authorized,
@@ -1054,7 +1054,7 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Deserialize)]
+#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
id: String,
@@ -1169,13 +1169,13 @@ pub enum ZenWebhookTxnType {
Unknown,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
pub struct ZenErrorResponse {
pub error: Option<ZenErrorBody>,
pub message: Option<String>,
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct ZenErrorBody {
pub message: String,
pub code: String,
diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs
index 4d3aadc3c45..31ee4a2d989 100644
--- a/crates/router/src/events/connector_api_logs.rs
+++ b/crates/router/src/events/connector_api_logs.rs
@@ -1,6 +1,7 @@
use common_utils::request::Method;
use router_env::tracing_actix_web::RequestId;
use serde::Serialize;
+use serde_json::json;
use time::OffsetDateTime;
use super::{EventType, RawEvent};
@@ -10,7 +11,8 @@ pub struct ConnectorEvent {
connector_name: String,
flow: String,
request: String,
- response: Option<String>,
+ masked_response: Option<String>,
+ error: Option<String>,
url: String,
method: String,
payment_id: String,
@@ -29,7 +31,6 @@ impl ConnectorEvent {
connector_name: String,
flow: &str,
request: serde_json::Value,
- response: Option<String>,
url: String,
method: Method,
payment_id: String,
@@ -48,7 +49,8 @@ impl ConnectorEvent {
.unwrap_or(flow)
.to_string(),
request: request.to_string(),
- response,
+ masked_response: None,
+ error: None,
url,
method: method.to_string(),
payment_id,
@@ -63,6 +65,28 @@ impl ConnectorEvent {
status_code,
}
}
+
+ pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
+ match masking::masked_serialize(response) {
+ Ok(masked) => {
+ self.masked_response = Some(masked.to_string());
+ }
+ Err(er) => self.set_error(json!({"error": er.to_string()})),
+ }
+ }
+
+ pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
+ match masking::masked_serialize(response) {
+ Ok(masked) => {
+ self.error = Some(masked.to_string());
+ }
+ Err(er) => self.set_error(json!({"error": er.to_string()})),
+ }
+ }
+
+ pub fn set_error(&mut self, error: serde_json::Value) {
+ self.error = Some(error.to_string());
+ }
}
impl TryFrom<ConnectorEvent> for RawEvent {
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 28405c001eb..fbaaec62243 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -184,6 +184,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
fn handle_response(
&self,
data: &types::RouterData<T, Req, Resp>,
+ event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
@@ -191,20 +192,25 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
Req: Clone,
Resp: Clone,
{
+ event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
Ok(data.clone())
}
fn get_error_response(
&self,
- _res: types::Response,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
fn get_5xx_error_response(
&self,
res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
@@ -288,8 +294,7 @@ where
response: res.into(),
status_code: 200,
};
-
- connector_integration.handle_response(req, response)
+ connector_integration.handle_response(req, None, response)
}
payments::CallConnectorAction::Avoid => Ok(router_data),
payments::CallConnectorAction::StatusUpdate {
@@ -379,21 +384,10 @@ where
.map_or_else(|value| value.status_code, |value| value.status_code)
})
.unwrap_or_default();
- let connector_event = ConnectorEvent::new(
+ let mut connector_event = ConnectorEvent::new(
req.connector.clone(),
std::any::type_name::<T>(),
masked_request_body,
- response
- .as_ref()
- .map(|response| {
- response
- .as_ref()
- .map_or_else(|value| value, |value| value)
- .response
- .escape_ascii()
- .to_string()
- })
- .ok(),
request_url,
request_method,
req.payment_id.clone(),
@@ -405,22 +399,13 @@ where
status_code,
);
- match connector_event.try_into() {
- Ok(event) => {
- state.event_handler().log_event(event);
- }
- Err(err) => {
- logger::error!(error=?err, "Error Logging Connector Event");
- }
- }
-
match response {
Ok(body) => {
let response = match body {
Ok(body) => {
let connector_http_status_code = Some(body.status_code);
- let mut data = connector_integration
- .handle_response(req, body)
+ match connector_integration
+ .handle_response(req, Some(&mut connector_event), body)
.map_err(|error| {
if error.current_context()
== &errors::ConnectorError::ResponseDeserializationFailed
@@ -435,14 +420,40 @@ where
)
}
error
- })?;
- data.connector_http_status_code = connector_http_status_code;
- // Add up multiple external latencies in case of multiple external calls within the same request.
- data.external_latency = Some(
- data.external_latency
- .map_or(external_latency, |val| val + external_latency),
- );
- data
+ }) {
+ Ok(mut data) => {
+
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
+ }
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ };
+ data.connector_http_status_code = connector_http_status_code;
+ // Add up multiple external latencies in case of multiple external calls within the same request.
+ data.external_latency = Some(
+ data.external_latency
+ .map_or(external_latency, |val| val + external_latency),
+ );
+ Ok(data)
+ },
+ Err(err) => {
+
+ connector_event.set_error(json!({"error": err.to_string()}));
+
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
+ }
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ }
+ Err(err)
+ },
+ }?
}
Err(body) => {
router_data.connector_http_status_code = Some(body.status_code);
@@ -459,13 +470,30 @@ where
req.connector.clone(),
)],
);
+
let error = match body.status_code {
500..=511 => {
- connector_integration.get_5xx_error_response(body)?
+ let error_res = connector_integration
+ .get_5xx_error_response(
+ body,
+ Some(&mut connector_event),
+ )?;
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
+ }
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ };
+ error_res
}
_ => {
- let error_res =
- connector_integration.get_error_response(body)?;
+ let error_res = connector_integration
+ .get_error_response(
+ body,
+ Some(&mut connector_event),
+ )?;
if let Some(status) = error_res.attempt_status {
router_data.status = status;
};
@@ -481,6 +509,15 @@ where
Ok(response)
}
Err(error) => {
+ connector_event.set_error(json!({"error": error.to_string()}));
+ match connector_event.try_into() {
+ Ok(event) => {
+ state.event_handler().log_event(event);
+ }
+ Err(err) => {
+ logger::error!(error=?err, "Error Logging Connector Event");
+ }
+ };
if error.current_context().is_upstream_timeout() {
let error_response = ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index b60153eaf19..db6cb8236b3 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -39,6 +39,7 @@ use crate::{
errors::{self, CustomResult},
payments::types as payments_types,
},
+ events::connector_api_logs::ConnectorEvent,
services::{request, ConnectorIntegration, ConnectorRedirectResponse, ConnectorValidation},
types::{self, api::enums as api_enums},
};
@@ -129,6 +130,7 @@ pub trait ConnectorCommon {
fn build_error_response(
&self,
res: types::Response,
+ _event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index c03f492e8b8..e4c347187cb 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -161,7 +161,7 @@ pub trait VerifyConnector {
dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
- .get_error_response(error_response)
+ .get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
@@ -177,7 +177,7 @@ pub trait VerifyConnector {
dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
- .get_error_response(error_response)
+ .get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Err(errors::ApiErrorResponse::InvalidRequestData {
message: error.reason.unwrap_or(error.message),
diff --git a/crates/router/src/types/api/verify_connector/paypal.rs b/crates/router/src/types/api/verify_connector/paypal.rs
index 33e848f909d..721562bd4a3 100644
--- a/crates/router/src/types/api/verify_connector/paypal.rs
+++ b/crates/router/src/types/api/verify_connector/paypal.rs
@@ -35,7 +35,7 @@ impl VerifyConnector for connector::Paypal {
Ok(res) => Some(
connector_data
.connector
- .handle_response(&router_data, res)
+ .handle_response(&router_data, None, res)
.change_context(errors::ApiErrorResponse::InternalServerError)?
.response
.map_err(|_| errors::ApiErrorResponse::InternalServerError.into()),
diff --git a/crates/router/src/types/api/verify_connector/stripe.rs b/crates/router/src/types/api/verify_connector/stripe.rs
index ece9fa15a1d..3fc55291d9c 100644
--- a/crates/router/src/types/api/verify_connector/stripe.rs
+++ b/crates/router/src/types/api/verify_connector/stripe.rs
@@ -19,7 +19,7 @@ impl VerifyConnector for connector::Stripe {
dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>,
{
let error = connector
- .get_error_response(error_response)
+ .get_error_response(error_response, None)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match (env::which(), error.code.as_str()) {
// In situations where an attempt is made to process a payment using a
| 2024-02-06T12:12:11Z |
## Description
<!-- Describe your changes in detail -->
Mask connector response in the click house
### Test Case
In click house check if connector response fields are masked
_Note: Only fields that are of type Secret<> is masked_
Test all the flows for all the connectors especially NMI as changes are made in response.
All connector flows to be tested
## Area of Impact
All connector response including, 4xx and 5xx error responses. | 09c2a5c2a90f2773b00ab11ad67ab149f8225e3a | [
".cargo/config.toml",
"add_connector.md",
"connector-template/mod.rs",
"crates/analytics/docs/clickhouse/cluster_setup/README.md",
"crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_config.xml",
"crates/analytics/docs/clickhouse/cluster_setup/config/clickhouse_metrika.xml",
"crates/analyt... | ||
juspay/hyperswitch | juspay__hyperswitch-3562 | Bug: chore(analytics): create a seperate flow for a force sync
Currently we use PaymentRetrieve for GET /payment/:id call, for force_sync use cases we should have a separate flow since the underlying execution differs significantly... | diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index d67166c0d04..87560032ea4 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -71,7 +71,7 @@ pub async fn payment_intents_create(
))
.await
}
-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn payment_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
@@ -96,7 +96,7 @@ pub async fn payment_intents_retrieve(
Err(err) => return api::log_and_return_error_response(report!(err)),
};
- let flow = Flow::PaymentsRetrieve;
+ let flow = Flow::PaymentsRetrieveForceSync;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
@@ -131,7 +131,7 @@ pub async fn payment_intents_retrieve(
))
.await
}
-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]
+#[instrument(skip_all, fields(flow))]
pub async fn payment_intents_retrieve_with_gateway_creds(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
@@ -160,7 +160,13 @@ pub async fn payment_intents_retrieve_with_gateway_creds(
Err(err) => return api::log_and_return_error_response(report!(err)),
};
- let flow = Flow::PaymentsRetrieve;
+ let flow = match json_payload.force_sync {
+ Some(true) => Flow::PaymentsRetrieveForceSync,
+ _ => Flow::PaymentsRetrieve,
+ };
+
+ tracing::Span::current().record("flow", &flow.to_string());
+
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
diff --git a/crates/router/src/compatibility/stripe/refunds.rs b/crates/router/src/compatibility/stripe/refunds.rs
index 77c3a61fa78..80ebbc4f84d 100644
--- a/crates/router/src/compatibility/stripe/refunds.rs
+++ b/crates/router/src/compatibility/stripe/refunds.rs
@@ -57,14 +57,14 @@ pub async fn refund_create(
))
.await
}
-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]
+#[instrument(skip_all, fields(flow))]
pub async fn refund_retrieve_with_gateway_creds(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
- let refund_request = match qs_config
+ let refund_request: refund_types::RefundsRetrieveRequest = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
@@ -72,7 +72,12 @@ pub async fn refund_retrieve_with_gateway_creds(
Err(err) => return api::log_and_return_error_response(err),
};
- let flow = Flow::RefundsRetrieve;
+ let flow = match refund_request.force_sync {
+ Some(true) => Flow::RefundsRetrieveForceSync,
+ _ => Flow::RefundsRetrieve,
+ };
+
+ tracing::Span::current().record("flow", &flow.to_string());
Box::pin(wrap::compatibility_api_wrap::<
_,
@@ -103,7 +108,7 @@ pub async fn refund_retrieve_with_gateway_creds(
))
.await
}
-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]
+#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieveForceSync))]
pub async fn refund_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
@@ -115,7 +120,7 @@ pub async fn refund_retrieve(
merchant_connector_details: None,
};
- let flow = Flow::RefundsRetrieve;
+ let flow = Flow::RefundsRetrieveForceSync;
Box::pin(wrap::compatibility_api_wrap::<
_,
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index 515e41ec91f..6522dc4697c 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -78,7 +78,7 @@ pub async fn setup_intents_create(
))
.await
}
-#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieve))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn setup_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
@@ -103,7 +103,7 @@ pub async fn setup_intents_retrieve(
Err(err) => return api::log_and_return_error_response(report!(err)),
};
- let flow = Flow::PaymentsRetrieve;
+ let flow = Flow::PaymentsRetrieveForceSync;
Box::pin(wrap::compatibility_api_wrap::<
_,
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9471289a0c8..6b2fa3046a3 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -102,6 +102,7 @@ impl From<Flow> for ApiIdentifier {
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
+ | Flow::PaymentsRetrieveForceSync
| Flow::PaymentsUpdate
| Flow::PaymentsConfirm
| Flow::PaymentsCapture
@@ -123,6 +124,7 @@ impl From<Flow> for ApiIdentifier {
Flow::RefundsCreate
| Flow::RefundsRetrieve
+ | Flow::RefundsRetrieveForceSync
| Flow::RefundsUpdate
| Flow::RefundsList => Self::Refunds,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index b822e6d4e68..24849d828e2 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -229,7 +229,7 @@ pub async fn payments_start(
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
-#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve, payment_id))]
+#[instrument(skip(state, req), fields(flow, payment_id))]
// #[get("/{payment_id}")]
pub async fn payments_retrieve(
state: web::Data<app::AppState>,
@@ -237,7 +237,10 @@ pub async fn payments_retrieve(
path: web::Path<String>,
json_payload: web::Query<payment_types::PaymentRetrieveBody>,
) -> impl Responder {
- let flow = Flow::PaymentsRetrieve;
+ let flow = match json_payload.force_sync {
+ Some(true) => Flow::PaymentsRetrieveForceSync,
+ _ => Flow::PaymentsRetrieve,
+ };
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(path.to_string()),
merchant_id: json_payload.merchant_id.clone(),
@@ -249,6 +252,7 @@ pub async fn payments_retrieve(
};
tracing::Span::current().record("payment_id", &path.to_string());
+ tracing::Span::current().record("flow", &flow.to_string());
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
@@ -300,7 +304,7 @@ pub async fn payments_retrieve(
operation_id = "Retrieve a Payment",
security(("api_key" = []))
)]
-#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve, payment_id))]
+#[instrument(skip(state, req), fields(flow, payment_id))]
// #[post("/sync")]
pub async fn payments_retrieve_with_gateway_creds(
state: web::Data<app::AppState>,
@@ -320,9 +324,13 @@ pub async fn payments_retrieve_with_gateway_creds(
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
- let flow = Flow::PaymentsRetrieve;
+ let flow = match json_payload.force_sync {
+ Some(true) => Flow::PaymentsRetrieveForceSync,
+ _ => Flow::PaymentsRetrieve,
+ };
tracing::Span::current().record("payment_id", &json_payload.payment_id);
+ tracing::Span::current().record("flow", &flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 47e9f2bf42a..ef9ffb41124 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -63,7 +63,7 @@ pub async fn refunds_create(
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]
+#[instrument(skip_all, fields(flow))]
// #[get("/{id}")]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
@@ -76,7 +76,12 @@ pub async fn refunds_retrieve(
force_sync: query_params.force_sync,
merchant_connector_details: None,
};
- let flow = Flow::RefundsRetrieve;
+ let flow = match query_params.force_sync {
+ Some(true) => Flow::RefundsRetrieveForceSync,
+ _ => Flow::RefundsRetrieve,
+ };
+
+ tracing::Span::current().record("flow", &flow.to_string());
Box::pin(api::server_wrap(
flow,
@@ -115,14 +120,20 @@ pub async fn refunds_retrieve(
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
-#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieve))]
+#[instrument(skip_all, fields(flow))]
// #[post("/sync")]
pub async fn refunds_retrieve_with_body(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsRetrieveRequest>,
) -> HttpResponse {
- let flow = Flow::RefundsRetrieve;
+ let flow = match json_payload.force_sync {
+ Some(true) => Flow::RefundsRetrieveForceSync,
+ _ => Flow::RefundsRetrieve,
+ };
+
+ tracing::Span::current().record("flow", &flow.to_string());
+
Box::pin(api::server_wrap(
flow,
state,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 62c09c42455..93b1ef6cdce 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -127,6 +127,8 @@ pub enum Flow {
PaymentsCreate,
/// Payments Retrieve flow.
PaymentsRetrieve,
+ /// Payments Retrieve force sync flow.
+ PaymentsRetrieveForceSync,
/// Payments update flow.
PaymentsUpdate,
/// Payments confirm flow.
@@ -168,6 +170,8 @@ pub enum Flow {
RefundsCreate,
/// Refunds retrieve flow.
RefundsRetrieve,
+ /// Refunds retrieve force sync flow.
+ RefundsRetrieveForceSync,
/// Refunds update flow.
RefundsUpdate,
/// Refunds list flow.
| 2024-02-06T11:17:50Z | Currently we use PaymentRetrieve for GET /payment/:id call, for force_sync use cases we should have a separate flow since the underlying execution differs significantly...
Refs: #3562
## Description
<!-- Describe your changes in detail -->
Currently we don't show payment retrieve call logs in the audit logs but we want to display the force retrieve calls so we have created the separate flow when the flow is force retrieve.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 53559c22527dde9536aa493ad7cd3bf353335c1a |
hit a payment/refunds/dispute retrieve call with a force sync flag as true and in the logs u get to see the enum contains force retrieve in it ex- `RefundsRetriveForceSync`
when we do a refunds or payment retrive call with the force_sync flag as true , the debugger will display the `RefundsRetriveForceSync` in the flow type
```
curl --location '<url>/refunds/<refund_id>?force_sync=true' \
--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 '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/121.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer <token>' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"'
```

| [
"crates/router/src/compatibility/stripe/payment_intents.rs",
"crates/router/src/compatibility/stripe/refunds.rs",
"crates/router/src/compatibility/stripe/setup_intents.rs",
"crates/router/src/routes/lock_utils.rs",
"crates/router/src/routes/payments.rs",
"crates/router/src/routes/refunds.rs",
"crates/ro... | |
juspay/hyperswitch | juspay__hyperswitch-1357 | Bug: [FEATURE] add domain type for client secret
### Feature Description
Create domain type for client secret
### Possible Implementation
Make type `ClietSecret(String)` and use it wherever applicable
### Have you spent some time to check if this feature request has been raised before?
- [X] I checked and didn't find similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
No, but I'm happy to collaborate on a PR with someone else | diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 6bccfd1124c..1be9762c76c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1,4 +1,4 @@
-use std::num::NonZeroI64;
+use std::{fmt, num::NonZeroI64};
use cards::CardNumber;
use common_utils::{
@@ -8,6 +8,10 @@ use common_utils::{
};
use masking::Secret;
use router_derive::Setter;
+use serde::{
+ de::{self, Unexpected, Visitor},
+ Deserialize, Deserializer, Serialize, Serializer,
+};
use time::PrimitiveDateTime;
use url::Url;
use utoipa::ToSchema;
@@ -51,6 +55,120 @@ pub struct BankCodeResponse {
pub eligible_connectors: Vec<String>,
}
+#[derive(Debug, PartialEq)]
+pub struct ClientSecret {
+ pub payment_id: String,
+ pub secret: String,
+}
+
+impl<'de> Deserialize<'de> for ClientSecret {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct ClientSecretVisitor;
+
+ impl<'de> Visitor<'de> for ClientSecretVisitor {
+ type Value = ClientSecret;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("a string in the format '{payment_id}_secret_{secret}'")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E>
+ where
+ E: de::Error,
+ {
+ let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| {
+ E::invalid_value(Unexpected::Str(value), &"a string with '_secret_'")
+ })?;
+
+ Ok(ClientSecret {
+ payment_id: payment_id.to_owned(),
+ secret: secret.to_owned(),
+ })
+ }
+ }
+
+ deserializer.deserialize_str(ClientSecretVisitor)
+ }
+}
+
+impl Serialize for ClientSecret {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let combined = format!("{}_secret_{}", self.payment_id, self.secret);
+ serializer.serialize_str(&combined)
+ }
+}
+
+#[cfg(test)]
+mod client_secret_tests {
+ #![allow(clippy::expect_used)]
+
+ use serde_json;
+
+ use super::*;
+
+ #[test]
+ fn test_serialize_client_secret() {
+ let client_secret1 = ClientSecret {
+ payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(),
+ secret: "fc34taHLw1ekPgNh92qr".to_string(),
+ };
+ let client_secret2 = ClientSecret {
+ payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(),
+ secret: "fc34taHLw1ekPgNh92qr".to_string(),
+ };
+
+ let expected_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
+ let expected_str2 = r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
+
+ let actual_str1 =
+ serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1");
+ let actual_str2 =
+ serde_json::to_string(&client_secret2).expect("Failed to serialize client_secret2");
+
+ assert_eq!(expected_str1, actual_str1);
+ assert_eq!(expected_str2, actual_str2);
+ }
+
+ #[test]
+ fn test_deserialize_client_secret() {
+ let client_secret_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
+ let client_secret_str2 =
+ r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
+ let client_secret_str3 =
+ r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr""#;
+
+ let expected1 = ClientSecret {
+ payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(),
+ secret: "fc34taHLw1ekPgNh92qr".to_string(),
+ };
+ let expected2 = ClientSecret {
+ payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(),
+ secret: "fc34taHLw1ekPgNh92qr".to_string(),
+ };
+ let expected3 = ClientSecret {
+ payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_".to_string(),
+ secret: "fc34taHLw1ekPgNh92qr".to_string(),
+ };
+
+ let actual1: ClientSecret = serde_json::from_str(client_secret_str1)
+ .expect("Failed to deserialize client_secret_str1");
+ let actual2: ClientSecret = serde_json::from_str(client_secret_str2)
+ .expect("Failed to deserialize client_secret_str2");
+ let actual3: ClientSecret = serde_json::from_str(client_secret_str3)
+ .expect("Failed to deserialize client_secret_str3");
+
+ assert_eq!(expected1, actual1);
+ assert_eq!(expected2, actual2);
+ assert_eq!(expected3, actual3);
+ }
+}
+
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct CustomerDetails {
/// The identifier for the customer.
| 2024-02-05T22:29:45Z |
## Description
Implement `ClientSecret` type for payments.
Closes #1357
## Motivation and Context
# | 91cd70a60b89b1c4e868e359a75f4088854562ef | Added and ran unit tests successfully.
_Maintainer edit:_ This PR only adds a newtype and is not being used anywhere in code, this should not affect any existing application behavior.
| [
"crates/api_models/src/payments.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3488 | Bug: [FEATURE] Create a delete endpoint for Config Table
### Feature Description
Add an API for deleting data from config table.
### Possible Implementation
Add the endpoint DELETE `config/{key}` for deleting the config key.
### 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/configs.rs b/crates/diesel_models/src/query/configs.rs
index 62ed60e3b0a..306fb5e3353 100644
--- a/crates/diesel_models/src/query/configs.rs
+++ b/crates/diesel_models/src/query/configs.rs
@@ -50,8 +50,11 @@ impl Config {
}
#[instrument(skip(conn))]
- pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<bool> {
- generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::key.eq(key.to_owned()))
- .await
+ pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> {
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::key.eq(key.to_owned()),
+ )
+ .await
}
}
diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs
index 8aa2310416e..ba2303167d7 100644
--- a/crates/router/src/core/configs.rs
+++ b/crates/router/src/core/configs.rs
@@ -41,3 +41,12 @@ pub async fn update_config(
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
+
+pub async fn config_delete(state: AppState, key: String) -> RouterResponse<api::Config> {
+ let store = state.store.as_ref();
+ let config = store
+ .delete_config_by_key(&key)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
+ Ok(ApplicationResponse::Json(config.foreign_into()))
+}
diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs
index f3e85ba5d23..1d472c1fb66 100644
--- a/crates/router/src/db/configs.rs
+++ b/crates/router/src/db/configs.rs
@@ -51,7 +51,10 @@ pub trait ConfigInterface {
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError>;
- async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError>;
+ async fn delete_config_by_key(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -154,7 +157,10 @@ impl ConfigInterface for Store {
cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
}
- async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> {
+ async fn delete_config_by_key(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let deleted = storage::Config::delete_by_key(&conn, key)
.await
@@ -226,15 +232,15 @@ impl ConfigInterface for MockDb {
result
}
- async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> {
+ async fn delete_config_by_key(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, errors::StorageError> {
let mut configs = self.configs.lock().await;
let result = configs
.iter()
.position(|c| c.key == key)
- .map(|index| {
- configs.remove(index);
- true
- })
+ .map(|index| configs.remove(index))
.ok_or_else(|| {
errors::StorageError::ValueNotFound("cannot find config to delete".to_string())
.into()
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0897deb87e5..3b88868001a 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -284,7 +284,10 @@ impl ConfigInterface for KafkaStore {
.await
}
- async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> {
+ async fn delete_config_by_key(
+ &self,
+ key: &str,
+ ) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.delete_config_by_key(key).await
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 41881c60ff7..3a94aef623b 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -813,7 +813,8 @@ impl Configs {
.service(
web::resource("/{key}")
.route(web::get().to(config_key_retrieve))
- .route(web::post().to(config_key_update)),
+ .route(web::post().to(config_key_update))
+ .route(web::delete().to(config_key_delete)),
)
}
}
diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs
index 45eb45a83b5..d7e96f40235 100644
--- a/crates/router/src/routes/configs.rs
+++ b/crates/router/src/routes/configs.rs
@@ -71,3 +71,24 @@ pub async fn config_key_update(
)
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyDelete))]
+pub async fn config_key_delete(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> impl Responder {
+ let flow = Flow::ConfigKeyDelete;
+ let key = path.into_inner();
+
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ key,
+ |state, _, key| configs::config_delete(state, key),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9393e8ae212..aa4f3dccb8f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -74,6 +74,7 @@ impl From<Flow> for ApiIdentifier {
Flow::ConfigKeyCreate
| Flow::ConfigKeyFetch
| Flow::ConfigKeyUpdate
+ | Flow::ConfigKeyDelete
| Flow::CreateConfigKey => Self::Configs,
Flow::CustomersCreate
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 6649b89911a..b99b81f8d6b 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -82,6 +82,8 @@ pub enum Flow {
ConfigKeyFetch,
/// ConfigKey Update flow.
ConfigKeyUpdate,
+ /// ConfigKey Delete flow.
+ ConfigKeyDelete,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
| 2024-02-05T14:59:01Z |
## Description
<!-- Describe your changes in detail -->
Added the api to delete config key
Fixes #3488
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
# | 073310c1f671ccbb71cc5c8725eca9771e511589 |
- Create a config.
```bash
curl --location 'http://localhost:8080/configs/' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"key":"keke",
"value": "keke"
}'
```
- Delete the config
```bash
curl --location --request DELETE 'http://localhost:8080/configs/keke' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin'
```
- Get the config
```
curl --location --request GET 'http://localhost:8080/configs/keke' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin'
```
It should return 404
| [
"crates/diesel_models/src/query/configs.rs",
"crates/router/src/core/configs.rs",
"crates/router/src/db/configs.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/configs.rs",
"crates/router/src/routes/lock_utils.rs",
"crates/router_env/src/logger/... | |
juspay/hyperswitch | juspay__hyperswitch-3553 | Bug: [FIX] dont return true in case health check is not done on the component
Whenever a component is disabled we don't have to check for it's health so return false in case if we didn't check it | diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
index 6b0297b655f..29a59df397e 100644
--- a/crates/api_models/src/health_check.rs
+++ b/crates/api_models/src/health_check.rs
@@ -2,7 +2,8 @@
pub struct RouterHealthCheckResponse {
pub database: bool,
pub redis: bool,
- pub locker: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub vault: Option<bool>,
#[cfg(feature = "olap")]
pub analytics: bool,
pub outgoing_request: bool,
@@ -17,4 +18,28 @@ pub struct SchedulerHealthCheckResponse {
pub outgoing_request: bool,
}
+pub enum HealthState {
+ Running,
+ Error,
+ NotApplicable,
+}
+
+impl From<HealthState> for bool {
+ fn from(value: HealthState) -> Self {
+ match value {
+ HealthState::Running => true,
+ HealthState::Error | HealthState::NotApplicable => false,
+ }
+ }
+}
+impl From<HealthState> for Option<bool> {
+ fn from(value: HealthState) -> Self {
+ match value {
+ HealthState::Running => Some(true),
+ HealthState::Error => Some(false),
+ HealthState::NotApplicable => None,
+ }
+ }
+}
+
impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs
index bc523b4fba6..3be764ef66b 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -1,5 +1,6 @@
#[cfg(feature = "olap")]
use analytics::health_check::HealthCheck;
+use api_models::health_check::HealthState;
use error_stack::ResultExt;
use router_env::logger;
@@ -12,23 +13,27 @@ use crate::{
#[async_trait::async_trait]
pub trait HealthCheckInterface {
- async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>;
- async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError>;
- async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError>;
- async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing>;
+ async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>;
+ async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError>;
+ async fn health_check_locker(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckLockerError>;
+ async fn health_check_outgoing(&self)
+ -> CustomResult<HealthState, errors::HealthCheckOutGoing>;
#[cfg(feature = "olap")]
- async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError>;
+ async fn health_check_analytics(&self)
+ -> CustomResult<HealthState, errors::HealthCheckDBError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for app::AppState {
- async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
+ async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let db = &*self.store;
db.health_check_db().await?;
- Ok(())
+ Ok(HealthState::Running)
}
- async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError> {
+ async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> {
let db = &*self.store;
let redis_conn = db
.get_redis_conn()
@@ -55,10 +60,12 @@ impl HealthCheckInterface for app::AppState {
logger::debug!("Redis delete_key was successful");
- Ok(())
+ Ok(HealthState::Running)
}
- async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError> {
+ async fn health_check_locker(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckLockerError> {
let locker = &self.conf.locker;
if !locker.mock_locker {
let mut url = locker.host_rs.to_owned();
@@ -67,16 +74,19 @@ impl HealthCheckInterface for app::AppState {
services::call_connector_api(self, request)
.await
.change_context(errors::HealthCheckLockerError::FailedToCallLocker)?
- .ok();
+ .map_err(|_| {
+ error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker)
+ })?;
+ Ok(HealthState::Running)
+ } else {
+ Ok(HealthState::NotApplicable)
}
-
- logger::debug!("Locker call was successful");
-
- Ok(())
}
#[cfg(feature = "olap")]
- async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError> {
+ async fn health_check_analytics(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let analytics = &self.pool;
match analytics {
analytics::AnalyticsProvider::Sqlx(client) => client
@@ -107,10 +117,14 @@ impl HealthCheckInterface for app::AppState {
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError)
}
- }
+ }?;
+
+ Ok(HealthState::Running)
}
- async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing> {
+ async fn health_check_outgoing(
+ &self,
+ ) -> CustomResult<HealthState, errors::HealthCheckOutGoing> {
let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL);
services::call_connector_api(self, request)
.await
@@ -125,6 +139,6 @@ impl HealthCheckInterface for app::AppState {
})?;
logger::debug!("Outgoing request successful");
- Ok(())
+ Ok(HealthState::Running)
}
}
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index 2183ab07fed..a00ba011bff 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -45,7 +45,7 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
logger::debug!("Database health check begin");
- let db_status = state.health_check_db().await.map(|_| true).map_err(|err| {
+ let db_status = state.health_check_db().await.map_err(|err| {
error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message: err.to_string()
@@ -56,64 +56,48 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
logger::debug!("Redis health check begin");
- let redis_status = state
- .health_check_redis()
- .await
- .map(|_| true)
- .map_err(|err| {
- error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
- component: "Redis",
- message: err.to_string()
- })
- })?;
+ let redis_status = state.health_check_redis().await.map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Redis",
+ message: err.to_string()
+ })
+ })?;
logger::debug!("Redis health check end");
logger::debug!("Locker health check begin");
- let locker_status = state
- .health_check_locker()
- .await
- .map(|_| true)
- .map_err(|err| {
- error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
- component: "Locker",
- message: err.to_string()
- })
- })?;
+ let locker_status = state.health_check_locker().await.map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Locker",
+ message: err.to_string()
+ })
+ })?;
#[cfg(feature = "olap")]
- let analytics_status = state
- .health_check_analytics()
- .await
- .map(|_| true)
- .map_err(|err| {
- error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
- component: "Analytics",
- message: err.to_string()
- })
- })?;
-
- let outgoing_check = state
- .health_check_outgoing()
- .await
- .map(|_| true)
- .map_err(|err| {
- error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
- component: "Outgoing Request",
- message: err.to_string()
- })
- })?;
+ let analytics_status = state.health_check_analytics().await.map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Analytics",
+ message: err.to_string()
+ })
+ })?;
+
+ let outgoing_check = state.health_check_outgoing().await.map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Outgoing Request",
+ message: err.to_string()
+ })
+ })?;
logger::debug!("Locker health check end");
let response = RouterHealthCheckResponse {
- database: db_status,
- redis: redis_status,
- locker: locker_status,
+ database: db_status.into(),
+ redis: redis_status.into(),
+ vault: locker_status.into(),
#[cfg(feature = "olap")]
- analytics: analytics_status,
- outgoing_request: outgoing_check,
+ analytics: analytics_status.into(),
+ outgoing_request: outgoing_check.into(),
};
Ok(api::ApplicationResponse::Json(response))
| 2024-02-05T11:48:10Z |
## Description
<!-- Describe your changes in detail -->
Don't return true on the places where checks or not applicable
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 fixes misconception in health check where it would return true even in case if the case is not checked.
# | d3fb705ed241a216cbe53de1886d18506bff68bc |
- Disable locker in config
```bash
curl --location 'http://localhost:8080/health/ready'
```
<img width="1305" alt="Screenshot 2024-02-07 at 2 55 21 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/27a2a956-a57a-4a1b-a6cf-d2b0e602017d">
**THIS CANNOT BE TESTED IN SANDBOX**
| [
"crates/api_models/src/health_check.rs",
"crates/router/src/core/health_check.rs",
"crates/router/src/routes/health.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3552 | Bug: feat(analytics): adding kafka dispute events
| diff --git a/config/config.example.toml b/config/config.example.toml
index 3f1e789dd50..611c581a3df 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -559,6 +559,7 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events
api_logs_topic = "topic" # Kafka topic to be used for incoming api events
connector_logs_topic = "topic" # Kafka topic to be used for connector api events
outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events
+dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events
# File storage configuration
[file_storage]
diff --git a/config/development.toml b/config/development.toml
index 3a3540da5b6..5eef33eafd9 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -542,6 +542,7 @@ refund_analytics_topic = "hyperswitch-refund-events"
api_logs_topic = "hyperswitch-api-log-events"
connector_logs_topic = "hyperswitch-connector-api-events"
outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
+dispute_analytics_topic = "hyperswitch-dispute-events"
[analytics]
source = "sqlx"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 9728497aaf6..178788677e5 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -383,6 +383,7 @@ refund_analytics_topic = "hyperswitch-refund-events"
api_logs_topic = "hyperswitch-api-log-events"
connector_logs_topic = "hyperswitch-connector-api-events"
outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
+dispute_analytics_topic = "hyperswitch-dispute-events"
[analytics]
source = "sqlx"
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
new file mode 100644
index 00000000000..92a748ff489
--- /dev/null
+++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
@@ -0,0 +1,142 @@
+CREATE TABLE hyperswitch.dispute_queue on cluster '{cluster}' (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `created_at` DateTime CODEC(T64, LZ4),
+ `modified_at` DateTime CODEC(T64, LZ4),
+ `connector` LowCardinality(String),
+ `evidence` Nullable(String),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `sign_flag` Int8
+) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
+kafka_topic_list = 'hyperswitch-dispute-events',
+kafka_group_name = 'hyper-c1',
+kafka_format = 'JSONEachRow',
+kafka_handle_error_mode = 'stream';
+
+
+CREATE MATERIALIZED VIEW hyperswitch.dispute_mv on cluster '{cluster}' TO hyperswitch.dispute (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime64(3)),
+ `connector_created_at` Nullable(DateTime64(3)),
+ `connector_updated_at` Nullable(DateTime64(3)),
+ `created_at` DateTime64(3),
+ `modified_at` DateTime64(3),
+ `connector` LowCardinality(String),
+ `evidence` Nullable(String),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `inserted_at` DateTime64(3),
+ `sign_flag` Int8
+) AS
+SELECT
+ dispute_id,
+ amount,
+ currency,
+ dispute_stage,
+ dispute_status,
+ payment_id,
+ attempt_id,
+ merchant_id,
+ connector_status,
+ connector_dispute_id,
+ connector_reason,
+ connector_reason_code,
+ challenge_required_by,
+ connector_created_at,
+ connector_updated_at,
+ created_at,
+ modified_at,
+ connector,
+ evidence,
+ profile_id,
+ merchant_connector_id,
+ now() as inserted_at,
+ sign_flag
+FROM
+ hyperswitch.dispute_queue
+WHERE length(_error) = 0;
+
+
+CREATE TABLE hyperswitch.dispute_clustered on cluster '{cluster}' (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `connector` LowCardinality(String),
+ `evidence` String DEFAULT '{}' CODEC(T64, LZ4),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `sign_flag` Int8
+ INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
+ INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
+ INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1
+) ENGINE = ReplicatedCollapsingMergeTree(
+ '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/dispute_clustered',
+ '{replica}',
+ dispute_status
+)
+PARTITION BY toStartOfDay(created_at)
+ORDER BY
+ (created_at, merchant_id, dispute_id)
+TTL created_at + toIntervalMonth(6);
+
+
+CREATE MATERIALIZED VIEW hyperswitch.dispute_parse_errors on cluster '{cluster}'
+(
+ `topic` String,
+ `partition` Int64,
+ `offset` Int64,
+ `raw` String,
+ `error` String
+)
+ENGINE = MergeTree
+ORDER BY (topic, partition, offset)
+SETTINGS index_granularity = 8192 AS
+SELECT
+ _topic AS topic,
+ _partition AS partition,
+ _offset AS offset,
+ _raw_message AS raw,
+ _error AS error
+FROM hyperswitch.dispute_queue
+WHERE length(_error) > 0
+;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/disputes.sql b/crates/analytics/docs/clickhouse/scripts/disputes.sql
new file mode 100644
index 00000000000..3f700bc06d3
--- /dev/null
+++ b/crates/analytics/docs/clickhouse/scripts/disputes.sql
@@ -0,0 +1,117 @@
+CREATE TABLE dispute_queue (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `created_at` DateTime CODEC(T64, LZ4),
+ `modified_at` DateTime CODEC(T64, LZ4),
+ `connector` LowCardinality(String),
+ `evidence` Nullable(String),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `sign_flag` Int8
+) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
+kafka_topic_list = 'hyperswitch-dispute-events',
+kafka_group_name = 'hyper-c1',
+kafka_format = 'JSONEachRow',
+kafka_handle_error_mode = 'stream';
+
+
+CREATE TABLE dispute (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `connector` LowCardinality(String),
+ `evidence` String DEFAULT '{}' CODEC(T64, LZ4),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `sign_flag` Int8
+ INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
+ INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
+ INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1
+) ENGINE = CollapsingMergeTree(
+ sign_flag
+)
+PARTITION BY toStartOfDay(created_at)
+ORDER BY
+ (created_at, merchant_id, dispute_id)
+TTL created_at + toIntervalMonth(6)
+;
+
+CREATE MATERIALIZED VIEW kafka_parse_dispute TO dispute (
+ `dispute_id` String,
+ `amount` String,
+ `currency` String,
+ `dispute_stage` LowCardinality(String),
+ `dispute_status` LowCardinality(String),
+ `payment_id` String,
+ `attempt_id` String,
+ `merchant_id` String,
+ `connector_status` String,
+ `connector_dispute_id` String,
+ `connector_reason` Nullable(String),
+ `connector_reason_code` Nullable(String),
+ `challenge_required_by` Nullable(DateTime64(3)),
+ `connector_created_at` Nullable(DateTime64(3)),
+ `connector_updated_at` Nullable(DateTime64(3)),
+ `created_at` DateTime64(3),
+ `modified_at` DateTime64(3),
+ `connector` LowCardinality(String),
+ `evidence` Nullable(String),
+ `profile_id` Nullable(String),
+ `merchant_connector_id` Nullable(String),
+ `inserted_at` DateTime64(3),
+ `sign_flag` Int8
+) AS
+SELECT
+ dispute_id,
+ amount,
+ currency,
+ dispute_stage,
+ dispute_status,
+ payment_id,
+ attempt_id,
+ merchant_id,
+ connector_status,
+ connector_dispute_id,
+ connector_reason,
+ connector_reason_code,
+ challenge_required_by,
+ connector_created_at,
+ connector_updated_at,
+ created_at,
+ modified_at,
+ connector,
+ evidence,
+ profile_id,
+ merchant_connector_id,
+ now() as inserted_at,
+ sign_flag
+FROM
+ dispute_queue;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index a5e5f216a8b..0078f030c5a 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -374,9 +374,15 @@ impl CustomerInterface for KafkaStore {
impl DisputeInterface for KafkaStore {
async fn insert_dispute(
&self,
- dispute: storage::DisputeNew,
+ dispute_new: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError> {
- self.diesel_store.insert_dispute(dispute).await
+ let dispute = self.diesel_store.insert_dispute(dispute_new).await?;
+
+ if let Err(er) = self.kafka_producer.log_dispute(&dispute, None).await {
+ logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er);
+ };
+
+ Ok(dispute)
}
async fn find_by_merchant_id_payment_id_connector_dispute_id(
@@ -419,7 +425,19 @@ impl DisputeInterface for KafkaStore {
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
- self.diesel_store.update_dispute(this, dispute).await
+ let dispute_new = self
+ .diesel_store
+ .update_dispute(this.clone(), dispute)
+ .await?;
+ if let Err(er) = self
+ .kafka_producer
+ .log_dispute(&dispute_new, Some(this))
+ .await
+ {
+ logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er);
+ };
+
+ Ok(dispute_new)
}
async fn find_disputes_by_merchant_id_payment_id(
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 2bcfcfe974f..ef9352e55b4 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -8,6 +8,7 @@ use rdkafka::{
};
use crate::events::EventType;
+mod dispute;
mod payment_attempt;
mod payment_intent;
mod refund;
@@ -17,8 +18,10 @@ use serde::Serialize;
use time::OffsetDateTime;
use self::{
- payment_attempt::KafkaPaymentAttempt, payment_intent::KafkaPaymentIntent, refund::KafkaRefund,
+ dispute::KafkaDispute, payment_attempt::KafkaPaymentAttempt,
+ payment_intent::KafkaPaymentIntent, refund::KafkaRefund,
};
+use crate::types::storage::Dispute;
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
@@ -82,6 +85,7 @@ pub struct KafkaSettings {
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
+ dispute_analytics_topic: String,
}
impl KafkaSettings {
@@ -135,6 +139,12 @@ impl KafkaSettings {
},
)?;
+ common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Kafka Dispute Logs topic must not be empty".into(),
+ ))
+ })?;
+
Ok(())
}
}
@@ -148,6 +158,7 @@ pub struct KafkaProducer {
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
+ dispute_analytics_topic: String,
}
struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);
@@ -186,6 +197,7 @@ impl KafkaProducer {
api_logs_topic: conf.api_logs_topic.clone(),
connector_logs_topic: conf.connector_logs_topic.clone(),
outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(),
+ dispute_analytics_topic: conf.dispute_analytics_topic.clone(),
})
}
@@ -306,6 +318,27 @@ impl KafkaProducer {
})
}
+ pub async fn log_dispute(
+ &self,
+ dispute: &Dispute,
+ old_dispute: Option<Dispute>,
+ ) -> MQResult<()> {
+ if let Some(negative_event) = old_dispute {
+ self.log_kafka_event(
+ &self.dispute_analytics_topic,
+ &KafkaEvent::old(&KafkaDispute::from_storage(&negative_event)),
+ )
+ .attach_printable_lazy(|| {
+ format!("Failed to add negative dispute event {negative_event:?}")
+ })?;
+ };
+ self.log_kafka_event(
+ &self.dispute_analytics_topic,
+ &KafkaEvent::new(&KafkaDispute::from_storage(dispute)),
+ )
+ .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))
+ }
+
pub fn get_topic(&self, event: EventType) -> &str {
match event {
EventType::ApiLogs => &self.api_logs_topic,
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
new file mode 100644
index 00000000000..3ccdbe53cb1
--- /dev/null
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -0,0 +1,76 @@
+use diesel_models::enums as storage_enums;
+use masking::Secret;
+use time::OffsetDateTime;
+
+use crate::types::storage::dispute::Dispute;
+
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaDispute<'a> {
+ pub dispute_id: &'a String,
+ pub amount: &'a String,
+ pub currency: &'a String,
+ pub dispute_stage: &'a storage_enums::DisputeStage,
+ pub dispute_status: &'a storage_enums::DisputeStatus,
+ pub payment_id: &'a String,
+ pub attempt_id: &'a String,
+ pub merchant_id: &'a String,
+ pub connector_status: &'a String,
+ pub connector_dispute_id: &'a String,
+ pub connector_reason: Option<&'a String>,
+ pub connector_reason_code: Option<&'a String>,
+ #[serde(default, with = "time::serde::timestamp::option")]
+ pub challenge_required_by: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp::option")]
+ pub connector_created_at: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp::option")]
+ pub connector_updated_at: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp")]
+ pub created_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp")]
+ pub modified_at: OffsetDateTime,
+ pub connector: &'a String,
+ pub evidence: &'a Secret<serde_json::Value>,
+ pub profile_id: Option<&'a String>,
+ pub merchant_connector_id: Option<&'a String>,
+}
+
+impl<'a> KafkaDispute<'a> {
+ pub fn from_storage(dispute: &'a Dispute) -> Self {
+ Self {
+ dispute_id: &dispute.dispute_id,
+ amount: &dispute.amount,
+ currency: &dispute.currency,
+ dispute_stage: &dispute.dispute_stage,
+ dispute_status: &dispute.dispute_status,
+ payment_id: &dispute.payment_id,
+ attempt_id: &dispute.attempt_id,
+ merchant_id: &dispute.merchant_id,
+ connector_status: &dispute.connector_status,
+ connector_dispute_id: &dispute.connector_dispute_id,
+ connector_reason: dispute.connector_reason.as_ref(),
+ connector_reason_code: dispute.connector_reason_code.as_ref(),
+ challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
+ connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
+ connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
+ created_at: dispute.created_at.assume_utc(),
+ modified_at: dispute.modified_at.assume_utc(),
+ connector: &dispute.connector,
+ evidence: &dispute.evidence,
+ profile_id: dispute.profile_id.as_ref(),
+ merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaDispute<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}",
+ self.merchant_id, self.payment_id, self.dispute_id
+ )
+ }
+
+ fn creation_timestamp(&self) -> Option<i64> {
+ Some(self.modified_at.unix_timestamp())
+ }
+}
| 2024-02-05T11:31:41Z |
## Description
adding dispute events to kafka
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | fb254b8924808e6a2b2a9a31dbed78749836e8d3 | Create a payment curl commented below, I used checkout connector to create dispute
and check on grafana in explore section, select loki and query as ```{app="bach"} |= dispute_id```
I added SS of local console log in the comment below
| [
"config/config.example.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql",
"crates/analytics/docs/clickhouse/scripts/disputes.sql",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/services/kafka.rs",
... | |
juspay/hyperswitch | juspay__hyperswitch-3464 | Bug: [FEATURE] Add the configs for revoking as well as updating the mandates
### Feature Description
Add envs of the connectors that support the revokinga s well as updation of mandates
### Possible Implementation
Make an env that has the list of all the connectors that support revoke as well as mandate flow , and if we try to update or revoke the mandate for a connector that is not there in the list we throw a suitable error
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/config.example.toml b/config/config.example.toml
index dd1206b20dc..dda768bec3c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -391,6 +391,9 @@ bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supp
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" }
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"} # Update Mandate supported payment method type and connector for card
+card.debit = {connector_list ="cybersource"} # Update Mandate supported payment method type and connector for card
# Required fields info used while listing the payment_method_data
[required_fields.pay_later] # payment_method = "pay_later"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index dfb1fc9ee28..1ba455ee134 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 82d5c00c806..ae764682321 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index dfc3033ea20..1cac50298ff 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -120,6 +120,10 @@ wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/development.toml b/config/development.toml
index 1fd76d04ff5..1075452fbd6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -487,6 +487,10 @@ bank_debit.sepa = { connector_list = "gocardless"}
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
+
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = []
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 07a891efd34..a9d415230e9 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1011,6 +1011,23 @@ impl PaymentMethodData {
self.to_owned()
}
}
+ pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> {
+ match self {
+ Self::Card(_) => Some(api_enums::PaymentMethod::Card),
+ Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect),
+ Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet),
+ Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater),
+ Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect),
+ Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit),
+ Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer),
+ Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto),
+ Self::Reward => Some(api_enums::PaymentMethod::Reward),
+ Self::Upi(_) => Some(api_enums::PaymentMethod::Upi),
+ Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher),
+ Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard),
+ Self::CardToken(_) | Self::MandatePayment => None,
+ }
+ }
}
pub trait GetPaymentMethodType {
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index fc5ba0f55bc..71cd61ffa80 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -209,6 +209,7 @@ impl Default for Mandates {
])),
),
])),
+ update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()),
}
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 2519455f95a..2572d764d06 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -237,6 +237,7 @@ pub struct DummyConnector {
#[derive(Debug, Deserialize, Clone)]
pub struct Mandates {
pub supported_payment_methods: SupportedPaymentMethodsForMandate,
+ pub update_mandate_supported: SupportedPaymentMethodsForMandate,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index 7299ef624d8..e564e4a733e 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -59,7 +59,6 @@ pub async fn revoke_mandate(
.find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
-
let mandate_revoke_status = match mandate.mandate_status {
common_enums::MandateStatus::Active
| common_enums::MandateStatus::Inactive
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index e9beb84c7bb..7b505e7c01c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1219,6 +1219,7 @@ pub async fn list_payment_methods(
mca.connector_name.clone(),
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
+ &state.conf.mandates.update_mandate_supported,
)
.await?;
}
@@ -1985,6 +1986,7 @@ pub async fn filter_payment_methods(
connector: String,
config: &settings::ConnectorFilters,
supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
for payment_method in payment_methods.into_iter() {
let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method);
@@ -2091,13 +2093,20 @@ pub async fn filter_payment_methods(
),
};
- if mandate_type_present || update_mandate_id_present {
+ if mandate_type_present {
filter_pm_based_on_supported_payments_for_mandate(
supported_payment_methods_for_mandate,
&payment_method,
&payment_method_object.payment_method_type,
connector_variant,
)
+ } else if update_mandate_id_present {
+ filter_pm_based_on_update_mandate_support_for_connector(
+ supported_payment_methods_for_update_mandate,
+ &payment_method,
+ &payment_method_object.payment_method_type,
+ connector_variant,
+ )
} else {
true
}
@@ -2121,6 +2130,19 @@ pub async fn filter_payment_methods(
}
Ok(())
}
+pub fn filter_pm_based_on_update_mandate_support_for_connector(
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ payment_method: &api_enums::PaymentMethod,
+ payment_method_type: &api_enums::PaymentMethodType,
+ connector: api_enums::Connector,
+) -> bool {
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
+ .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
+ .unwrap_or(false)
+}
fn filter_pm_based_on_supported_payments_for_mandate(
supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 712184308dd..a81f97851d9 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -3,9 +3,11 @@ use error_stack::{IntoReport, ResultExt};
use super::{ConstructFlowSpecificData, Feature};
use crate::{
+ configs::settings,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate,
+ payment_methods::cards,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
@@ -60,106 +62,53 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
connector_request: Option<services::Request>,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self> {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
-
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- &self,
- call_connector_action.clone(),
- connector_request,
- )
- .await
- .to_setup_mandate_failed_response()?;
-
- let is_mandate = resp.request.setup_mandate_details.is_some();
-
- let pm_id = Box::pin(tokenization::save_payment_method(
- state,
- connector,
- resp.to_owned(),
- maybe_customer,
- merchant_account,
- self.request.payment_method_type,
- key_store,
- is_mandate,
- ))
- .await?;
-
if let Some(mandate_id) = self
.request
.setup_mandate_details
.as_ref()
.and_then(|mandate_data| mandate_data.update_mandate_id.clone())
{
- let mandate = state
- .store
- .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
-
- let profile_id = mandate::helpers::get_profile_id_for_mandate(
+ self.update_mandate_flow(
state,
merchant_account,
- mandate.clone(),
+ mandate_id,
+ connector,
+ key_store,
+ call_connector_action,
+ &state.conf.mandates.update_mandate_supported,
+ connector_request,
+ maybe_customer,
)
- .await?;
- match resp.response {
- Ok(types::PaymentsResponseData::TransactionResponse { .. }) => {
- let connector_integration: services::BoxedConnectorIntegration<
- '_,
- types::api::MandateRevoke,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
- > = connector.connector.get_connector_integration();
- let merchant_connector_account = helpers::get_merchant_connector_account(
- state,
- &merchant_account.merchant_id,
- None,
- key_store,
- &profile_id,
- &mandate.connector,
- mandate.merchant_connector_id.as_ref(),
- )
- .await?;
-
- let router_data = mandate::utils::construct_mandate_revoke_router_data(
- merchant_connector_account,
- merchant_account,
- mandate.clone(),
- )
- .await?;
-
- let _response = services::execute_connector_processing_step(
- state,
- connector_integration,
- &router_data,
- call_connector_action,
- None,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- // TODO:Add the revoke mandate task to process tracker
- mandate::update_mandate_procedure(
- state,
- resp,
- mandate,
- &merchant_account.merchant_id,
- pm_id,
- )
- .await
- }
- Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable("Unexpected response received")?,
- Err(_) => Ok(resp),
- }
+ .await
} else {
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &self,
+ call_connector_action.clone(),
+ connector_request,
+ )
+ .await
+ .to_setup_mandate_failed_response()?;
+ let is_mandate = resp.request.setup_mandate_details.is_some();
+ let pm_id = Box::pin(tokenization::save_payment_method(
+ state,
+ connector,
+ resp.to_owned(),
+ maybe_customer,
+ merchant_account,
+ self.request.payment_method_type,
+ key_store,
+ is_mandate,
+ ))
+ .await?;
mandate::mandate_procedure(
state,
resp,
@@ -310,6 +259,130 @@ impl types::SetupMandateRouterData {
_ => Ok(self.clone()),
}
}
+
+ async fn update_mandate_flow(
+ self,
+ state: &AppState,
+ merchant_account: &domain::MerchantAccount,
+ mandate_id: String,
+ connector: &api::ConnectorData,
+ key_store: &domain::MerchantKeyStore,
+ call_connector_action: payments::CallConnectorAction,
+ supported_connectors_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
+ connector_request: Option<services::Request>,
+ maybe_customer: &Option<domain::Customer>,
+ ) -> RouterResult<Self> {
+ let payment_method_type = self.request.payment_method_type;
+
+ let payment_method = self.request.payment_method_data.get_payment_method();
+ let supported_connectors_config =
+ payment_method
+ .zip(payment_method_type)
+ .map_or(false, |(pm, pmt)| {
+ cards::filter_pm_based_on_update_mandate_support_for_connector(
+ supported_connectors_for_update_mandate,
+ &pm,
+ &pmt,
+ connector.connector_name,
+ )
+ });
+ if supported_connectors_config {
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &self,
+ call_connector_action.clone(),
+ connector_request,
+ )
+ .await
+ .to_setup_mandate_failed_response()?;
+ let is_mandate = resp.request.setup_mandate_details.is_some();
+ let pm_id = Box::pin(tokenization::save_payment_method(
+ state,
+ connector,
+ resp.to_owned(),
+ maybe_customer,
+ merchant_account,
+ self.request.payment_method_type,
+ key_store,
+ is_mandate,
+ ))
+ .await?;
+ let mandate = state
+ .store
+ .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
+
+ let profile_id = mandate::helpers::get_profile_id_for_mandate(
+ state,
+ merchant_account,
+ mandate.clone(),
+ )
+ .await?;
+ match resp.response {
+ Ok(types::PaymentsResponseData::TransactionResponse { .. }) => {
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ types::api::MandateRevoke,
+ types::MandateRevokeRequestData,
+ types::MandateRevokeResponseData,
+ > = connector.connector.get_connector_integration();
+ let merchant_connector_account = helpers::get_merchant_connector_account(
+ state,
+ &merchant_account.merchant_id,
+ None,
+ key_store,
+ &profile_id,
+ &mandate.connector,
+ mandate.merchant_connector_id.as_ref(),
+ )
+ .await?;
+
+ let router_data = mandate::utils::construct_mandate_revoke_router_data(
+ merchant_connector_account,
+ merchant_account,
+ mandate.clone(),
+ )
+ .await?;
+
+ let _response = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ call_connector_action,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ // TODO:Add the revoke mandate task to process tracker
+ mandate::update_mandate_procedure(
+ state,
+ resp,
+ mandate,
+ &merchant_account.merchant_id,
+ pm_id,
+ )
+ .await
+ }
+ Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Unexpected response received")?,
+ Err(_) => Ok(resp),
+ }
+ } else {
+ Err(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Update Mandate Flow not implemented for the connector ")?
+ }
+ }
}
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index e92a924bf12..6cf547f668f 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1342,7 +1342,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectDa
})
}
}
-
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index b9119b0dbb8..14d119768d0 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -252,6 +252,13 @@ bank_debit.sepa = { connector_list = "gocardless"}
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+[mandates.update_mandate_supported]
+card.credit ={connector_list ="cybersource"}
+card.debit = {connector_list ="cybersource"}
+
+[mandates.update_mandate_supported]
+connector_list = "cybersource"
+
[analytics]
source = "sqlx"
| 2024-02-05T07:47:56Z |
## Description
add config for update_mandate_flow and allow only those payment_methods that support update while Listing PaymentMethods For Merchants
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | ef302dd3983674c9df47812d3c398a7e7b423257 | - Create an MA and a MCA for Cybersource
> Create an update_,mandate payment using cyber source it'll be successful
- Create an MA and a MCA forStripe
> Create an update_,mandate payment using cyber source it should throw a 5xx
- Now ListPaymentMethodsForMerchnat in an Update Flow, we only list cards
| [
"config/config.example.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"crates/api_models/src/payments.rs",
"crates/router/src/configs/defaults.rs",
"crates/router/src/configs/settings.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-3535 | Bug: [REFACTOR] introducing `hyperswitch_interface` crates
Create a new crate `Hyperswitch-interface` containing below modules for now:
`secrets_interface`: Module used for application config `encryption` and `decryption` during startup which will contain its own trait and error types
`encryption_interface`: Module used for user value `encryption` and `decryption` during runtime which will contain its own trait and error types | diff --git a/Cargo.lock b/Cargo.lock
index 49ccfc2c645..4bee1804f4c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2495,6 +2495,7 @@ dependencies = [
"hex",
"hyper",
"hyper-proxy",
+ "hyperswitch_interfaces",
"masking",
"once_cell",
"router_env",
@@ -3214,6 +3215,18 @@ dependencies = [
"tokio-native-tls",
]
+[[package]]
+name = "hyperswitch_interfaces"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "common_utils",
+ "dyn-clone",
+ "masking",
+ "serde",
+ "thiserror",
+]
+
[[package]]
name = "iana-time-zone"
version = "0.1.58"
@@ -5186,6 +5199,7 @@ dependencies = [
"hex",
"http",
"hyper",
+ "hyperswitch_interfaces",
"image",
"infer 0.13.0",
"josekit",
diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs
index 788ff1456e2..e01b72150c5 100644
--- a/crates/drainer/src/connection.rs
+++ b/crates/drainer/src/connection.rs
@@ -3,7 +3,10 @@ use diesel::PgConnection;
#[cfg(feature = "aws_kms")]
use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt};
#[cfg(feature = "hashicorp-vault")]
-use external_services::hashicorp_vault::{self, decrypt::VaultFetch, Kv2};
+use external_services::hashicorp_vault::{
+ core::{HashiCorpVault, Kv2},
+ decrypt::VaultFetch,
+};
#[cfg(not(feature = "aws_kms"))]
use masking::PeekInterface;
@@ -28,8 +31,8 @@ pub async fn redis_connection(
pub async fn diesel_make_pg_pool(
database: &Database,
_test_transaction: bool,
- #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::AwsKmsClient,
- #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static hashicorp_vault::HashiCorpVault,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::core::AwsKmsClient,
+ #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static HashiCorpVault,
) -> PgPool {
let password = database.password.clone();
#[cfg(feature = "hashicorp-vault")]
diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs
index e6ca8d023a0..3918c756c10 100644
--- a/crates/drainer/src/services.rs
+++ b/crates/drainer/src/services.rs
@@ -34,10 +34,10 @@ impl Store {
&config.master_database,
test_transaction,
#[cfg(feature = "aws_kms")]
- external_services::aws_kms::get_aws_kms_client(&config.kms).await,
+ external_services::aws_kms::core::get_aws_kms_client(&config.kms).await,
#[cfg(feature = "hashicorp-vault")]
#[allow(clippy::expect_used)]
- external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault)
+ external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
.await
.expect("Failed while getting hashicorp client"),
)
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index 17b0b68b324..de5af654540 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -14,7 +14,7 @@ use serde::Deserialize;
use crate::errors;
#[cfg(feature = "aws_kms")]
-pub type Password = aws_kms::AwsKmsValue;
+pub type Password = aws_kms::core::AwsKmsValue;
#[cfg(not(feature = "aws_kms"))]
pub type Password = masking::Secret<String>;
@@ -36,9 +36,9 @@ pub struct Settings {
pub log: Log,
pub drainer: DrainerSettings,
#[cfg(feature = "aws_kms")]
- pub kms: aws_kms::AwsKmsConfig,
+ pub kms: aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- pub hc_vault: hashicorp_vault::HashiCorpVaultConfig,
+ pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 2b6bc22b2e9..58c81946017 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -35,5 +35,6 @@ hex = "0.4.3"
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
+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"] }
diff --git a/crates/external_services/src/aws_kms.rs b/crates/external_services/src/aws_kms.rs
index cf21f36f22b..3e5353fd9e3 100644
--- a/crates/external_services/src/aws_kms.rs
+++ b/crates/external_services/src/aws_kms.rs
@@ -1,284 +1,7 @@
//! Interactions with the AWS KMS SDK
-use std::time::Instant;
+pub mod core;
-use aws_config::meta::region::RegionProviderChain;
-use aws_sdk_kms::{config::Region, primitives::Blob, Client};
-use base64::Engine;
-use common_utils::errors::CustomResult;
-use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
-use router_env::logger;
-/// decrypting data using the AWS KMS SDK.
pub mod decrypt;
-use crate::{consts, metrics};
-
-static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = tokio::sync::OnceCell::const_new();
-
-/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized.
-#[inline]
-pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient {
- AWS_KMS_CLIENT
- .get_or_init(|| AwsKmsClient::new(config))
- .await
-}
-
-/// Configuration parameters required for constructing a [`AwsKmsClient`].
-#[derive(Clone, Debug, Default, serde::Deserialize)]
-#[serde(default)]
-pub struct AwsKmsConfig {
- /// The AWS key identifier of the KMS key used to encrypt or decrypt data.
- pub key_id: String,
-
- /// The AWS region to send KMS requests to.
- pub region: String,
-}
-
-/// Client for AWS KMS operations.
-#[derive(Debug)]
-pub struct AwsKmsClient {
- inner_client: Client,
- key_id: String,
-}
-
-impl AwsKmsClient {
- /// Constructs a new AWS KMS client.
- pub async fn new(config: &AwsKmsConfig) -> Self {
- let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
- let sdk_config = aws_config::from_env().region(region_provider).load().await;
-
- Self {
- inner_client: Client::new(&sdk_config),
- key_id: config.key_id.clone(),
- }
- }
-
- /// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that
- /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
- /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
- /// a machine that is able to assume an IAM role.
- pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
- let start = Instant::now();
- let data = consts::BASE64_ENGINE
- .decode(data)
- .into_report()
- .change_context(AwsKmsError::Base64DecodingFailed)?;
- let ciphertext_blob = Blob::new(data);
-
- let decrypt_output = self
- .inner_client
- .decrypt()
- .key_id(&self.key_id)
- .ciphertext_blob(ciphertext_blob)
- .send()
- .await
- .map_err(|error| {
- // Logging using `Debug` representation of the error as the `Display`
- // representation does not hold sufficient information.
- logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data");
- metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]);
- error
- })
- .into_report()
- .change_context(AwsKmsError::DecryptionFailed)?;
-
- let output = decrypt_output
- .plaintext
- .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput)
- .into_report()
- .and_then(|blob| {
- String::from_utf8(blob.into_inner())
- .into_report()
- .change_context(AwsKmsError::Utf8DecodingFailed)
- })?;
-
- let time_taken = start.elapsed();
- metrics::AWS_KMS_DECRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]);
-
- Ok(output)
- }
-
- /// Encrypts the provided String data using the AWS KMS SDK. We assume that
- /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
- /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
- /// a machine that is able to assume an IAM role.
- pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
- let start = Instant::now();
- let plaintext_blob = Blob::new(data.as_ref());
-
- let encrypted_output = self
- .inner_client
- .encrypt()
- .key_id(&self.key_id)
- .plaintext(plaintext_blob)
- .send()
- .await
- .map_err(|error| {
- // Logging using `Debug` representation of the error as the `Display`
- // representation does not hold sufficient information.
- logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data");
- metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]);
- error
- })
- .into_report()
- .change_context(AwsKmsError::EncryptionFailed)?;
-
- let output = encrypted_output
- .ciphertext_blob
- .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
- .into_report()
- .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?;
- let time_taken = start.elapsed();
- metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]);
-
- Ok(output)
- }
-}
-
-/// Errors that could occur during AWS KMS operations.
-#[derive(Debug, thiserror::Error)]
-pub enum AwsKmsError {
- /// An error occurred when base64 encoding input data.
- #[error("Failed to base64 encode input data")]
- Base64EncodingFailed,
-
- /// An error occurred when base64 decoding input data.
- #[error("Failed to base64 decode input data")]
- Base64DecodingFailed,
-
- /// An error occurred when AWS KMS decrypting input data.
- #[error("Failed to AWS KMS decrypt input data")]
- DecryptionFailed,
-
- /// An error occurred when AWS KMS encrypting input data.
- #[error("Failed to AWS KMS encrypt input data")]
- EncryptionFailed,
-
- /// The AWS KMS decrypted output does not include a plaintext output.
- #[error("Missing plaintext AWS KMS decryption output")]
- MissingPlaintextDecryptionOutput,
-
- /// The AWS KMS encrypted output does not include a ciphertext output.
- #[error("Missing ciphertext AWS KMS encryption output")]
- MissingCiphertextEncryptionOutput,
-
- /// An error occurred UTF-8 decoding AWS KMS decrypted output.
- #[error("Failed to UTF-8 decode decryption output")]
- Utf8DecodingFailed,
-
- /// The AWS KMS client has not been initialized.
- #[error("The AWS KMS client has not been initialized")]
- AwsKmsClientNotInitialized,
-}
-
-impl AwsKmsConfig {
- /// Verifies that the [`AwsKmsClient`] configuration is usable.
- pub fn validate(&self) -> Result<(), &'static str> {
- use common_utils::{ext_traits::ConfigExt, fp_utils::when};
-
- when(self.key_id.is_default_or_empty(), || {
- Err("KMS AWS key ID must not be empty")
- })?;
-
- when(self.region.is_default_or_empty(), || {
- Err("KMS AWS region must not be empty")
- })
- }
-}
-
-/// A wrapper around a AWS KMS value that can be decrypted.
-#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)]
-#[serde(transparent)]
-pub struct AwsKmsValue(Secret<String>);
-
-impl common_utils::ext_traits::ConfigExt for AwsKmsValue {
- fn is_empty_after_trim(&self) -> bool {
- self.0.peek().is_empty_after_trim()
- }
-}
-
-impl From<String> for AwsKmsValue {
- fn from(value: String) -> Self {
- Self(Secret::new(value))
- }
-}
-
-impl From<Secret<String>> for AwsKmsValue {
- fn from(value: Secret<String>) -> Self {
- Self(value)
- }
-}
-
-#[cfg(feature = "hashicorp-vault")]
-#[async_trait::async_trait]
-impl super::hashicorp_vault::decrypt::VaultFetch for AwsKmsValue {
- async fn fetch_inner<En>(
- self,
- client: &super::hashicorp_vault::HashiCorpVault,
- ) -> error_stack::Result<Self, super::hashicorp_vault::HashiCorpError>
- where
- for<'a> En: super::hashicorp_vault::Engine<
- ReturnType<'a, String> = std::pin::Pin<
- Box<
- dyn std::future::Future<
- Output = error_stack::Result<
- String,
- super::hashicorp_vault::HashiCorpError,
- >,
- > + Send
- + 'a,
- >,
- >,
- > + 'a,
- {
- self.0.fetch_inner::<En>(client).await.map(AwsKmsValue)
- }
-}
-
-#[cfg(test)]
-mod tests {
- #![allow(clippy::expect_used)]
- #[tokio::test]
- async fn check_aws_kms_encryption() {
- std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
- std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
- use super::*;
- let config = AwsKmsConfig {
- key_id: "YOUR AWS KMS KEY ID".to_string(),
- region: "AWS REGION".to_string(),
- };
-
- let data = "hello".to_string();
- let binding = data.as_bytes();
- let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
- .await
- .encrypt(binding)
- .await
- .expect("aws kms encryption failed");
-
- println!("{}", kms_encrypted_fingerprint);
- }
-
- #[tokio::test]
- async fn check_aws_kms_decrypt() {
- std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
- std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
- use super::*;
- let config = AwsKmsConfig {
- key_id: "YOUR AWS KMS KEY ID".to_string(),
- region: "AWS REGION".to_string(),
- };
-
- // Should decrypt to hello
- let data = "AWS KMS ENCRYPTED CIPHER".to_string();
- let binding = data.as_bytes();
- let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
- .await
- .decrypt(binding)
- .await
- .expect("aws kms decryption failed");
-
- println!("{}", kms_encrypted_fingerprint);
- }
-}
+pub mod implementers;
diff --git a/crates/external_services/src/aws_kms/core.rs b/crates/external_services/src/aws_kms/core.rs
new file mode 100644
index 00000000000..c01bcbfb094
--- /dev/null
+++ b/crates/external_services/src/aws_kms/core.rs
@@ -0,0 +1,299 @@
+//! Interactions with the AWS KMS SDK
+
+use std::time::Instant;
+
+use aws_config::meta::region::RegionProviderChain;
+use aws_sdk_kms::{config::Region, primitives::Blob, Client};
+use base64::Engine;
+use common_utils::errors::CustomResult;
+use error_stack::{IntoReport, ResultExt};
+use masking::{PeekInterface, Secret};
+use router_env::logger;
+
+#[cfg(feature = "hashicorp-vault")]
+use crate::hashicorp_vault;
+use crate::{aws_kms::decrypt::AwsKmsDecrypt, consts, metrics};
+
+pub(crate) static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> =
+ tokio::sync::OnceCell::const_new();
+
+/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized.
+#[inline]
+pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient {
+ AWS_KMS_CLIENT
+ .get_or_init(|| AwsKmsClient::new(config))
+ .await
+}
+
+/// Configuration parameters required for constructing a [`AwsKmsClient`].
+#[derive(Clone, Debug, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct AwsKmsConfig {
+ /// The AWS key identifier of the KMS key used to encrypt or decrypt data.
+ pub key_id: String,
+
+ /// The AWS region to send KMS requests to.
+ pub region: String,
+}
+
+/// Client for AWS KMS operations.
+#[derive(Debug, Clone)]
+pub struct AwsKmsClient {
+ inner_client: Client,
+ key_id: String,
+}
+
+impl AwsKmsClient {
+ /// Constructs a new AWS KMS client.
+ pub async fn new(config: &AwsKmsConfig) -> Self {
+ let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
+ let sdk_config = aws_config::from_env().region(region_provider).load().await;
+
+ Self {
+ inner_client: Client::new(&sdk_config),
+ key_id: config.key_id.clone(),
+ }
+ }
+
+ /// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that
+ /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
+ /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
+ /// a machine that is able to assume an IAM role.
+ pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
+ let start = Instant::now();
+ let data = consts::BASE64_ENGINE
+ .decode(data)
+ .into_report()
+ .change_context(AwsKmsError::Base64DecodingFailed)?;
+ let ciphertext_blob = Blob::new(data);
+
+ let decrypt_output = self
+ .inner_client
+ .decrypt()
+ .key_id(&self.key_id)
+ .ciphertext_blob(ciphertext_blob)
+ .send()
+ .await
+ .map_err(|error| {
+ // Logging using `Debug` representation of the error as the `Display`
+ // representation does not hold sufficient information.
+ logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data");
+ metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
+ .into_report()
+ .change_context(AwsKmsError::DecryptionFailed)?;
+
+ let output = decrypt_output
+ .plaintext
+ .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput)
+ .into_report()
+ .and_then(|blob| {
+ String::from_utf8(blob.into_inner())
+ .into_report()
+ .change_context(AwsKmsError::Utf8DecodingFailed)
+ })?;
+
+ let time_taken = start.elapsed();
+ metrics::AWS_KMS_DECRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]);
+
+ Ok(output)
+ }
+
+ /// Encrypts the provided String data using the AWS KMS SDK. We assume that
+ /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
+ /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
+ /// a machine that is able to assume an IAM role.
+ pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
+ let start = Instant::now();
+ let plaintext_blob = Blob::new(data.as_ref());
+
+ let encrypted_output = self
+ .inner_client
+ .encrypt()
+ .key_id(&self.key_id)
+ .plaintext(plaintext_blob)
+ .send()
+ .await
+ .map_err(|error| {
+ // Logging using `Debug` representation of the error as the `Display`
+ // representation does not hold sufficient information.
+ logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data");
+ metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
+ .into_report()
+ .change_context(AwsKmsError::EncryptionFailed)?;
+
+ let output = encrypted_output
+ .ciphertext_blob
+ .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
+ .into_report()
+ .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?;
+ let time_taken = start.elapsed();
+ metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]);
+
+ Ok(output)
+ }
+}
+
+/// Errors that could occur during KMS operations.
+#[derive(Debug, thiserror::Error)]
+pub enum AwsKmsError {
+ /// An error occurred when base64 encoding input data.
+ #[error("Failed to base64 encode input data")]
+ Base64EncodingFailed,
+
+ /// An error occurred when base64 decoding input data.
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed,
+
+ /// An error occurred when AWS KMS decrypting input data.
+ #[error("Failed to AWS KMS decrypt input data")]
+ DecryptionFailed,
+
+ /// An error occurred when AWS KMS encrypting input data.
+ #[error("Failed to AWS KMS encrypt input data")]
+ EncryptionFailed,
+
+ /// The AWS KMS decrypted output does not include a plaintext output.
+ #[error("Missing plaintext AWS KMS decryption output")]
+ MissingPlaintextDecryptionOutput,
+
+ /// The AWS KMS encrypted output does not include a ciphertext output.
+ #[error("Missing ciphertext AWS KMS encryption output")]
+ MissingCiphertextEncryptionOutput,
+
+ /// An error occurred UTF-8 decoding AWS KMS decrypted output.
+ #[error("Failed to UTF-8 decode decryption output")]
+ Utf8DecodingFailed,
+
+ /// The AWS KMS client has not been initialized.
+ #[error("The AWS KMS client has not been initialized")]
+ AwsKmsClientNotInitialized,
+}
+
+impl AwsKmsConfig {
+ /// Verifies that the [`AwsKmsClient`] configuration is usable.
+ pub fn validate(&self) -> Result<(), &'static str> {
+ use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+
+ when(self.key_id.is_default_or_empty(), || {
+ Err("KMS AWS key ID must not be empty")
+ })?;
+
+ when(self.region.is_default_or_empty(), || {
+ Err("KMS AWS region must not be empty")
+ })
+ }
+}
+
+/// A wrapper around a AWS KMS value that can be decrypted.
+#[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)]
+#[serde(transparent)]
+pub struct AwsKmsValue(Secret<String>);
+
+impl common_utils::ext_traits::ConfigExt for AwsKmsValue {
+ fn is_empty_after_trim(&self) -> bool {
+ self.0.peek().is_empty_after_trim()
+ }
+}
+
+impl From<String> for AwsKmsValue {
+ fn from(value: String) -> Self {
+ Self(Secret::new(value))
+ }
+}
+
+impl From<Secret<String>> for AwsKmsValue {
+ fn from(value: Secret<String>) -> Self {
+ Self(value)
+ }
+}
+
+#[cfg(feature = "hashicorp-vault")]
+#[async_trait::async_trait]
+impl hashicorp_vault::decrypt::VaultFetch for AwsKmsValue {
+ async fn fetch_inner<En>(
+ self,
+ client: &hashicorp_vault::core::HashiCorpVault,
+ ) -> error_stack::Result<Self, hashicorp_vault::core::HashiCorpError>
+ where
+ for<'a> En: hashicorp_vault::core::Engine<
+ ReturnType<'a, String> = std::pin::Pin<
+ Box<
+ dyn std::future::Future<
+ Output = error_stack::Result<
+ String,
+ hashicorp_vault::core::HashiCorpError,
+ >,
+ > + Send
+ + 'a,
+ >,
+ >,
+ > + 'a,
+ {
+ self.0.fetch_inner::<En>(client).await.map(AwsKmsValue)
+ }
+}
+
+#[async_trait::async_trait]
+impl AwsKmsDecrypt for &AwsKmsValue {
+ type Output = String;
+ async fn decrypt_inner(
+ self,
+ aws_kms_client: &AwsKmsClient,
+ ) -> CustomResult<Self::Output, AwsKmsError> {
+ aws_kms_client
+ .decrypt(self.0.peek())
+ .await
+ .attach_printable("Failed to decrypt AWS KMS value")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::expect_used)]
+ #[tokio::test]
+ async fn check_aws_kms_encryption() {
+ std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
+ std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
+ use super::*;
+ let config = AwsKmsConfig {
+ key_id: "YOUR AWS KMS KEY ID".to_string(),
+ region: "AWS REGION".to_string(),
+ };
+
+ let data = "hello".to_string();
+ let binding = data.as_bytes();
+ let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
+ .await
+ .encrypt(binding)
+ .await
+ .expect("aws kms encryption failed");
+
+ println!("{}", kms_encrypted_fingerprint);
+ }
+
+ #[tokio::test]
+ async fn check_aws_kms_decrypt() {
+ std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
+ std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
+ use super::*;
+ let config = AwsKmsConfig {
+ key_id: "YOUR AWS KMS KEY ID".to_string(),
+ region: "AWS REGION".to_string(),
+ };
+
+ // Should decrypt to hello
+ let data = "AWS KMS ENCRYPTED CIPHER".to_string();
+ let binding = data.as_bytes();
+ let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
+ .await
+ .decrypt(binding)
+ .await
+ .expect("aws kms decryption failed");
+
+ println!("{}", kms_encrypted_fingerprint);
+ }
+}
diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs
index 9abd4fefbef..47edb8f958f 100644
--- a/crates/external_services/src/aws_kms/decrypt.rs
+++ b/crates/external_services/src/aws_kms/decrypt.rs
@@ -1,6 +1,7 @@
+//! Decrypting data using the AWS KMS SDK.
use common_utils::errors::CustomResult;
-use super::*;
+use crate::aws_kms::core::{AwsKmsClient, AwsKmsError, AWS_KMS_CLIENT};
#[async_trait::async_trait]
/// This trait performs in place decryption of the structure on which this is implemented
@@ -26,17 +27,3 @@ pub trait AwsKmsDecrypt {
self.decrypt_inner(client).await
}
}
-
-#[async_trait::async_trait]
-impl AwsKmsDecrypt for &AwsKmsValue {
- type Output = String;
- async fn decrypt_inner(
- self,
- aws_kms_client: &AwsKmsClient,
- ) -> CustomResult<Self::Output, AwsKmsError> {
- aws_kms_client
- .decrypt(self.0.peek())
- .await
- .attach_printable("Failed to decrypt AWS KMS value")
- }
-}
diff --git a/crates/external_services/src/aws_kms/implementers.rs b/crates/external_services/src/aws_kms/implementers.rs
new file mode 100644
index 00000000000..cc00dbf3468
--- /dev/null
+++ b/crates/external_services/src/aws_kms/implementers.rs
@@ -0,0 +1,41 @@
+//! Trait implementations for aws kms client
+
+use common_utils::errors::CustomResult;
+use error_stack::ResultExt;
+use hyperswitch_interfaces::{
+ encryption_interface::{EncryptionError, EncryptionManagementInterface},
+ secrets_interface::{SecretManagementInterface, SecretsManagementError},
+};
+use masking::{PeekInterface, Secret};
+
+use crate::aws_kms::core::AwsKmsClient;
+
+#[async_trait::async_trait]
+impl EncryptionManagementInterface for AwsKmsClient {
+ async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
+ self.encrypt(input)
+ .await
+ .change_context(EncryptionError::EncryptionFailed)
+ .map(|val| val.into_bytes())
+ }
+
+ async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
+ self.decrypt(input)
+ .await
+ .change_context(EncryptionError::DecryptionFailed)
+ .map(|val| val.into_bytes())
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretManagementInterface for AwsKmsClient {
+ async fn get_secret(
+ &self,
+ input: Secret<String>,
+ ) -> CustomResult<Secret<String>, SecretsManagementError> {
+ self.decrypt(input.peek())
+ .await
+ .change_context(SecretsManagementError::FetchSecretFailed)
+ .map(Into::into)
+ }
+}
diff --git a/crates/external_services/src/hashicorp_vault.rs b/crates/external_services/src/hashicorp_vault.rs
index e31c8f01392..5a3ba539689 100644
--- a/crates/external_services/src/hashicorp_vault.rs
+++ b/crates/external_services/src/hashicorp_vault.rs
@@ -1,215 +1,7 @@
//! Interactions with the HashiCorp Vault
-use std::{collections::HashMap, future::Future, pin::Pin};
+pub mod core;
-use error_stack::{Report, ResultExt};
-use vaultrs::client::{VaultClient, VaultClientSettingsBuilder};
-
-/// Utilities for supporting decryption of data
pub mod decrypt;
-static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new();
-
-#[allow(missing_debug_implementations)]
-/// A struct representing a connection to HashiCorp Vault.
-pub struct HashiCorpVault {
- /// The underlying client used for interacting with HashiCorp Vault.
- client: VaultClient,
-}
-
-/// Configuration for connecting to HashiCorp Vault.
-#[derive(Clone, Debug, Default, serde::Deserialize)]
-#[serde(default)]
-pub struct HashiCorpVaultConfig {
- /// The URL of the HashiCorp Vault server.
- pub url: String,
- /// The authentication token used to access HashiCorp Vault.
- pub token: String,
-}
-
-/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration.
-///
-/// # Parameters
-///
-/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
-pub async fn get_hashicorp_client(
- config: &HashiCorpVaultConfig,
-) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> {
- HC_CLIENT
- .get_or_try_init(|| async { HashiCorpVault::new(config) })
- .await
-}
-
-/// A trait defining an engine for interacting with HashiCorp Vault.
-pub trait Engine: Sized {
- /// The associated type representing the return type of the engine's operations.
- type ReturnType<'b, T>
- where
- T: 'b,
- Self: 'b;
- /// Reads data from HashiCorp Vault at the specified location.
- ///
- /// # Parameters
- ///
- /// - `client`: A reference to the HashiCorpVault client.
- /// - `location`: The location in HashiCorp Vault to read data from.
- ///
- /// # Returns
- ///
- /// A future representing the result of the read operation.
- fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>;
-}
-
-/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine.
-#[derive(Debug)]
-pub enum Kv2 {}
-
-impl Engine for Kv2 {
- type ReturnType<'b, T: 'b> =
- Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>;
- fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> {
- Box::pin(async move {
- let mut split = location.split(':');
- let mount = split.next().ok_or(HashiCorpError::IncompleteData)?;
- let path = split.next().ok_or(HashiCorpError::IncompleteData)?;
- let key = split.next().unwrap_or("value");
-
- let mut output =
- vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path)
- .await
- .map_err(Into::<Report<_>>::into)
- .change_context(HashiCorpError::FetchFailed)?;
-
- Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?)
- })
- }
-}
-
-impl HashiCorpVault {
- /// Creates a new instance of HashiCorpVault based on the provided configuration.
- ///
- /// # Parameters
- ///
- /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
- ///
- pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> {
- VaultClient::new(
- VaultClientSettingsBuilder::default()
- .address(&config.url)
- .token(&config.token)
- .build()
- .map_err(Into::<Report<_>>::into)
- .change_context(HashiCorpError::ClientCreationFailed)
- .attach_printable("Failed while building vault settings")?,
- )
- .map_err(Into::<Report<_>>::into)
- .change_context(HashiCorpError::ClientCreationFailed)
- .map(|client| Self { client })
- }
-
- /// Asynchronously fetches data from HashiCorp Vault using the specified engine.
- ///
- /// # Parameters
- ///
- /// - `data`: A String representing the location or identifier of the data in HashiCorp Vault.
- ///
- /// # Type Parameters
- ///
- /// - `En`: The engine type that implements the `Engine` trait.
- /// - `I`: The type that can be constructed from the retrieved encoded data.
- ///
- pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError>
- where
- for<'a> En: Engine<
- ReturnType<'a, String> = Pin<
- Box<
- dyn Future<Output = error_stack::Result<String, HashiCorpError>>
- + Send
- + 'a,
- >,
- >,
- > + 'a,
- I: FromEncoded,
- {
- let output = En::read(self, data).await?;
- I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed))
- }
-}
-
-/// A trait for types that can be constructed from encoded data in the form of a String.
-pub trait FromEncoded: Sized {
- /// Constructs an instance of the type from the provided encoded input.
- ///
- /// # Parameters
- ///
- /// - `input`: A String containing the encoded data.
- ///
- /// # Returns
- ///
- /// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise.
- ///
- /// # Example
- ///
- /// ```rust
- /// # use your_module::{FromEncoded, masking::Secret, Vec};
- /// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string());
- /// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string());
- /// ```
- fn from_encoded(input: String) -> Option<Self>;
-}
-
-impl FromEncoded for masking::Secret<String> {
- fn from_encoded(input: String) -> Option<Self> {
- Some(input.into())
- }
-}
-
-impl FromEncoded for Vec<u8> {
- fn from_encoded(input: String) -> Option<Self> {
- hex::decode(input).ok()
- }
-}
-
-/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault.
-#[derive(Debug, thiserror::Error)]
-pub enum HashiCorpError {
- /// Failed while creating hashicorp client
- #[error("Failed while creating a new client")]
- ClientCreationFailed,
-
- /// Failed while building configurations for hashicorp client
- #[error("Failed while building configuration")]
- ConfigurationBuildFailed,
-
- /// Failed while decoding data to hex format
- #[error("Failed while decoding hex data")]
- HexDecodingFailed,
-
- /// An error occurred when base64 decoding input data.
- #[error("Failed to base64 decode input data")]
- Base64DecodingFailed,
-
- /// An error occurred when KMS decrypting input data.
- #[error("Failed to KMS decrypt input data")]
- DecryptionFailed,
-
- /// The KMS decrypted output does not include a plaintext output.
- #[error("Missing plaintext KMS decryption output")]
- MissingPlaintextDecryptionOutput,
-
- /// An error occurred UTF-8 decoding KMS decrypted output.
- #[error("Failed to UTF-8 decode decryption output")]
- Utf8DecodingFailed,
-
- /// Incomplete data provided to fetch data from hasicorp
- #[error("Provided information about the value is incomplete")]
- IncompleteData,
-
- /// Failed while fetching data from vault
- #[error("Failed while fetching data from the server")]
- FetchFailed,
-
- /// Failed while parsing received data
- #[error("Failed while parsing the response")]
- ParseError,
-}
+pub mod implementers;
diff --git a/crates/external_services/src/hashicorp_vault/core.rs b/crates/external_services/src/hashicorp_vault/core.rs
new file mode 100644
index 00000000000..86908b9d3d6
--- /dev/null
+++ b/crates/external_services/src/hashicorp_vault/core.rs
@@ -0,0 +1,227 @@
+//! Interactions with the HashiCorp Vault
+
+use std::{collections::HashMap, future::Future, pin::Pin};
+
+use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+use error_stack::{Report, ResultExt};
+use masking::{PeekInterface, Secret};
+use vaultrs::client::{VaultClient, VaultClientSettingsBuilder};
+
+static HC_CLIENT: tokio::sync::OnceCell<HashiCorpVault> = tokio::sync::OnceCell::const_new();
+
+#[allow(missing_debug_implementations)]
+/// A struct representing a connection to HashiCorp Vault.
+pub struct HashiCorpVault {
+ /// The underlying client used for interacting with HashiCorp Vault.
+ client: VaultClient,
+}
+
+/// Configuration for connecting to HashiCorp Vault.
+#[derive(Clone, Debug, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct HashiCorpVaultConfig {
+ /// The URL of the HashiCorp Vault server.
+ pub url: String,
+ /// The authentication token used to access HashiCorp Vault.
+ pub token: Secret<String>,
+}
+
+impl HashiCorpVaultConfig {
+ /// Verifies that the [`HashiCorpVault`] configuration is usable.
+ pub fn validate(&self) -> Result<(), &'static str> {
+ when(self.url.is_default_or_empty(), || {
+ Err("HashiCorp vault url must not be empty")
+ })?;
+
+ when(self.token.is_default_or_empty(), || {
+ Err("HashiCorp vault token must not be empty")
+ })
+ }
+}
+
+/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration.
+///
+/// # Parameters
+///
+/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
+pub async fn get_hashicorp_client(
+ config: &HashiCorpVaultConfig,
+) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> {
+ HC_CLIENT
+ .get_or_try_init(|| async { HashiCorpVault::new(config) })
+ .await
+}
+
+/// A trait defining an engine for interacting with HashiCorp Vault.
+pub trait Engine: Sized {
+ /// The associated type representing the return type of the engine's operations.
+ type ReturnType<'b, T>
+ where
+ T: 'b,
+ Self: 'b;
+ /// Reads data from HashiCorp Vault at the specified location.
+ ///
+ /// # Parameters
+ ///
+ /// - `client`: A reference to the HashiCorpVault client.
+ /// - `location`: The location in HashiCorp Vault to read data from.
+ ///
+ /// # Returns
+ ///
+ /// A future representing the result of the read operation.
+ fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String>;
+}
+
+/// An implementation of the `Engine` trait for the Key-Value version 2 (Kv2) engine.
+#[derive(Debug)]
+pub enum Kv2 {}
+
+impl Engine for Kv2 {
+ type ReturnType<'b, T: 'b> =
+ Pin<Box<dyn Future<Output = error_stack::Result<T, HashiCorpError>> + Send + 'b>>;
+ fn read(client: &HashiCorpVault, location: String) -> Self::ReturnType<'_, String> {
+ Box::pin(async move {
+ let mut split = location.split(':');
+ let mount = split.next().ok_or(HashiCorpError::IncompleteData)?;
+ let path = split.next().ok_or(HashiCorpError::IncompleteData)?;
+ let key = split.next().unwrap_or("value");
+
+ let mut output =
+ vaultrs::kv2::read::<HashMap<String, String>>(&client.client, mount, path)
+ .await
+ .map_err(Into::<Report<_>>::into)
+ .change_context(HashiCorpError::FetchFailed)?;
+
+ Ok(output.remove(key).ok_or(HashiCorpError::ParseError)?)
+ })
+ }
+}
+
+impl HashiCorpVault {
+ /// Creates a new instance of HashiCorpVault based on the provided configuration.
+ ///
+ /// # Parameters
+ ///
+ /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
+ ///
+ pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> {
+ VaultClient::new(
+ VaultClientSettingsBuilder::default()
+ .address(&config.url)
+ .token(config.token.peek())
+ .build()
+ .map_err(Into::<Report<_>>::into)
+ .change_context(HashiCorpError::ClientCreationFailed)
+ .attach_printable("Failed while building vault settings")?,
+ )
+ .map_err(Into::<Report<_>>::into)
+ .change_context(HashiCorpError::ClientCreationFailed)
+ .map(|client| Self { client })
+ }
+
+ /// Asynchronously fetches data from HashiCorp Vault using the specified engine.
+ ///
+ /// # Parameters
+ ///
+ /// - `data`: A String representing the location or identifier of the data in HashiCorp Vault.
+ ///
+ /// # Type Parameters
+ ///
+ /// - `En`: The engine type that implements the `Engine` trait.
+ /// - `I`: The type that can be constructed from the retrieved encoded data.
+ ///
+ pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError>
+ where
+ for<'a> En: Engine<
+ ReturnType<'a, String> = Pin<
+ Box<
+ dyn Future<Output = error_stack::Result<String, HashiCorpError>>
+ + Send
+ + 'a,
+ >,
+ >,
+ > + 'a,
+ I: FromEncoded,
+ {
+ let output = En::read(self, data).await?;
+ I::from_encoded(output).ok_or(error_stack::report!(HashiCorpError::HexDecodingFailed))
+ }
+}
+
+/// A trait for types that can be constructed from encoded data in the form of a String.
+pub trait FromEncoded: Sized {
+ /// Constructs an instance of the type from the provided encoded input.
+ ///
+ /// # Parameters
+ ///
+ /// - `input`: A String containing the encoded data.
+ ///
+ /// # Returns
+ ///
+ /// An `Option<Self>` representing the constructed instance if successful, or `None` otherwise.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use your_module::{FromEncoded, masking::Secret, Vec};
+ /// let secret_instance = Secret::<String>::from_encoded("encoded_secret_string".to_string());
+ /// let vec_instance = Vec::<u8>::from_encoded("68656c6c6f".to_string());
+ /// ```
+ fn from_encoded(input: String) -> Option<Self>;
+}
+
+impl FromEncoded for Secret<String> {
+ fn from_encoded(input: String) -> Option<Self> {
+ Some(input.into())
+ }
+}
+
+impl FromEncoded for Vec<u8> {
+ fn from_encoded(input: String) -> Option<Self> {
+ hex::decode(input).ok()
+ }
+}
+
+/// An enumeration representing various errors that can occur in interactions with HashiCorp Vault.
+#[derive(Debug, thiserror::Error)]
+pub enum HashiCorpError {
+ /// Failed while creating hashicorp client
+ #[error("Failed while creating a new client")]
+ ClientCreationFailed,
+
+ /// Failed while building configurations for hashicorp client
+ #[error("Failed while building configuration")]
+ ConfigurationBuildFailed,
+
+ /// Failed while decoding data to hex format
+ #[error("Failed while decoding hex data")]
+ HexDecodingFailed,
+
+ /// An error occurred when base64 decoding input data.
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed,
+
+ /// An error occurred when KMS decrypting input data.
+ #[error("Failed to KMS decrypt input data")]
+ DecryptionFailed,
+
+ /// The KMS decrypted output does not include a plaintext output.
+ #[error("Missing plaintext KMS decryption output")]
+ MissingPlaintextDecryptionOutput,
+
+ /// An error occurred UTF-8 decoding KMS decrypted output.
+ #[error("Failed to UTF-8 decode decryption output")]
+ Utf8DecodingFailed,
+
+ /// Incomplete data provided to fetch data from hasicorp
+ #[error("Provided information about the value is incomplete")]
+ IncompleteData,
+
+ /// Failed while fetching data from vault
+ #[error("Failed while fetching data from the server")]
+ FetchFailed,
+
+ /// Failed while parsing received data
+ #[error("Failed while parsing the response")]
+ ParseError,
+}
diff --git a/crates/external_services/src/hashicorp_vault/decrypt.rs b/crates/external_services/src/hashicorp_vault/decrypt.rs
index 1bc1b6ffa16..650b219841f 100644
--- a/crates/external_services/src/hashicorp_vault/decrypt.rs
+++ b/crates/external_services/src/hashicorp_vault/decrypt.rs
@@ -1,7 +1,11 @@
+//! Utilities for supporting decryption of data
+
use std::{future::Future, pin::Pin};
use masking::ExposeInterface;
+use crate::hashicorp_vault::core::{Engine, HashiCorpError, HashiCorpVault};
+
/// A trait for types that can be asynchronously fetched and decrypted from HashiCorp Vault.
#[async_trait::async_trait]
pub trait VaultFetch: Sized {
@@ -14,13 +18,13 @@ pub trait VaultFetch: Sized {
///
async fn fetch_inner<En>(
self,
- client: &super::HashiCorpVault,
- ) -> error_stack::Result<Self, super::HashiCorpError>
+ client: &HashiCorpVault,
+ ) -> error_stack::Result<Self, HashiCorpError>
where
- for<'a> En: super::Engine<
+ for<'a> En: Engine<
ReturnType<'a, String> = Pin<
Box<
- dyn Future<Output = error_stack::Result<String, super::HashiCorpError>>
+ dyn Future<Output = error_stack::Result<String, HashiCorpError>>
+ Send
+ 'a,
>,
@@ -32,13 +36,13 @@ pub trait VaultFetch: Sized {
impl VaultFetch for masking::Secret<String> {
async fn fetch_inner<En>(
self,
- client: &super::HashiCorpVault,
- ) -> error_stack::Result<Self, super::HashiCorpError>
+ client: &HashiCorpVault,
+ ) -> error_stack::Result<Self, HashiCorpError>
where
- for<'a> En: super::Engine<
+ for<'a> En: Engine<
ReturnType<'a, String> = Pin<
Box<
- dyn Future<Output = error_stack::Result<String, super::HashiCorpError>>
+ dyn Future<Output = error_stack::Result<String, HashiCorpError>>
+ Send
+ 'a,
>,
diff --git a/crates/external_services/src/hashicorp_vault/implementers.rs b/crates/external_services/src/hashicorp_vault/implementers.rs
new file mode 100644
index 00000000000..52fec2bd8d3
--- /dev/null
+++ b/crates/external_services/src/hashicorp_vault/implementers.rs
@@ -0,0 +1,24 @@
+//! Trait implementations for Hashicorp vault client
+
+use common_utils::errors::CustomResult;
+use error_stack::ResultExt;
+use hyperswitch_interfaces::secrets_interface::{
+ SecretManagementInterface, SecretsManagementError,
+};
+use masking::{ExposeInterface, Secret};
+
+use crate::hashicorp_vault::core::{HashiCorpVault, Kv2};
+
+#[async_trait::async_trait]
+impl SecretManagementInterface for HashiCorpVault {
+ async fn get_secret(
+ &self,
+ input: Secret<String>,
+ ) -> CustomResult<Secret<String>, SecretsManagementError> {
+ self.fetch::<Kv2, Secret<String>>(input.expose())
+ .await
+ .map(|val| val.expose().to_owned())
+ .change_context(SecretsManagementError::FetchSecretFailed)
+ .map(Into::into)
+ }
+}
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index cdabdeb49ae..33ab7541974 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -13,6 +13,10 @@ pub mod file_storage;
#[cfg(feature = "hashicorp-vault")]
pub mod hashicorp_vault;
+pub mod no_encryption;
+
+pub mod managers;
+
/// Crate specific constants
#[cfg(feature = "aws_kms")]
pub mod consts {
diff --git a/crates/external_services/src/managers.rs b/crates/external_services/src/managers.rs
new file mode 100644
index 00000000000..cb33d7bbf38
--- /dev/null
+++ b/crates/external_services/src/managers.rs
@@ -0,0 +1,5 @@
+//! Config and client managers
+
+pub mod encryption_management;
+
+pub mod secrets_management;
diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs
new file mode 100644
index 00000000000..4612190926c
--- /dev/null
+++ b/crates/external_services/src/managers/encryption_management.rs
@@ -0,0 +1,53 @@
+//!
+//! Encryption management util module
+//!
+
+use common_utils::errors::CustomResult;
+use hyperswitch_interfaces::encryption_interface::{
+ EncryptionError, EncryptionManagementInterface,
+};
+
+#[cfg(feature = "aws_kms")]
+use crate::aws_kms;
+use crate::no_encryption::core::NoEncryption;
+
+/// Enum representing configuration options for encryption management.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+#[serde(tag = "encryption_manager")]
+#[serde(rename_all = "snake_case")]
+pub enum EncryptionManagementConfig {
+ /// AWS KMS configuration
+ #[cfg(feature = "aws_kms")]
+ AwsKms {
+ /// AWS KMS config
+ aws_kms: aws_kms::core::AwsKmsConfig,
+ },
+
+ /// Variant representing no encryption
+ #[default]
+ NoEncryption,
+}
+
+impl EncryptionManagementConfig {
+ /// Verifies that the client configuration is usable
+ pub fn validate(&self) -> Result<(), &'static str> {
+ match self {
+ #[cfg(feature = "aws_kms")]
+ Self::AwsKms { aws_kms } => aws_kms.validate(),
+
+ Self::NoEncryption => Ok(()),
+ }
+ }
+
+ /// Retrieves the appropriate encryption client based on the configuration.
+ pub async fn get_encryption_management_client(
+ &self,
+ ) -> CustomResult<Box<dyn EncryptionManagementInterface>, EncryptionError> {
+ Ok(match self {
+ #[cfg(feature = "aws_kms")]
+ Self::AwsKms { aws_kms } => Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
+
+ Self::NoEncryption => Box::new(NoEncryption),
+ })
+ }
+}
diff --git a/crates/external_services/src/managers/secrets_management.rs b/crates/external_services/src/managers/secrets_management.rs
new file mode 100644
index 00000000000..b79046b4c75
--- /dev/null
+++ b/crates/external_services/src/managers/secrets_management.rs
@@ -0,0 +1,72 @@
+//!
+//! Secrets management util module
+//!
+
+use common_utils::errors::CustomResult;
+#[cfg(feature = "hashicorp-vault")]
+use error_stack::ResultExt;
+use hyperswitch_interfaces::secrets_interface::{
+ SecretManagementInterface, SecretsManagementError,
+};
+
+#[cfg(feature = "aws_kms")]
+use crate::aws_kms;
+#[cfg(feature = "hashicorp-vault")]
+use crate::hashicorp_vault;
+use crate::no_encryption::core::NoEncryption;
+
+/// Enum representing configuration options for secrets management.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+#[serde(tag = "secrets_manager")]
+#[serde(rename_all = "snake_case")]
+pub enum SecretsManagementConfig {
+ /// AWS KMS configuration
+ #[cfg(feature = "aws_kms")]
+ AwsKms {
+ /// AWS KMS config
+ aws_kms: aws_kms::core::AwsKmsConfig,
+ },
+
+ /// HashiCorp-Vault configuration
+ #[cfg(feature = "hashicorp-vault")]
+ HashiCorpVault {
+ /// HC-Vault config
+ hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
+ },
+
+ /// Variant representing no encryption
+ #[default]
+ NoEncryption,
+}
+
+impl SecretsManagementConfig {
+ /// Verifies that the client configuration is usable
+ pub fn validate(&self) -> Result<(), &'static str> {
+ match self {
+ #[cfg(feature = "aws_kms")]
+ Self::AwsKms { aws_kms } => aws_kms.validate(),
+ #[cfg(feature = "hashicorp-vault")]
+ Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
+ Self::NoEncryption => Ok(()),
+ }
+ }
+
+ /// Retrieves the appropriate secret management client based on the configuration.
+ pub async fn get_secret_management_client(
+ &self,
+ ) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
+ match self {
+ #[cfg(feature = "aws_kms")]
+ Self::AwsKms { aws_kms } => {
+ Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
+ }
+ #[cfg(feature = "hashicorp-vault")]
+ Self::HashiCorpVault { hc_vault } => {
+ hashicorp_vault::core::HashiCorpVault::new(hc_vault)
+ .change_context(SecretsManagementError::ClientCreationFailed)
+ .map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
+ }
+ Self::NoEncryption => Ok(Box::new(NoEncryption)),
+ }
+ }
+}
diff --git a/crates/external_services/src/no_encryption.rs b/crates/external_services/src/no_encryption.rs
new file mode 100644
index 00000000000..17c29618f89
--- /dev/null
+++ b/crates/external_services/src/no_encryption.rs
@@ -0,0 +1,7 @@
+//!
+//! No encryption functionalities
+//!
+
+pub mod core;
+
+pub mod implementers;
diff --git a/crates/external_services/src/no_encryption/core.rs b/crates/external_services/src/no_encryption/core.rs
new file mode 100644
index 00000000000..a55815c03f9
--- /dev/null
+++ b/crates/external_services/src/no_encryption/core.rs
@@ -0,0 +1,17 @@
+//! No encryption core functionalities
+
+/// No encryption type
+#[derive(Debug, Clone)]
+pub struct NoEncryption;
+
+impl NoEncryption {
+ /// Encryption functionality
+ pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
+ data.as_ref().into()
+ }
+
+ /// Decryption functionality
+ pub fn decrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
+ data.as_ref().into()
+ }
+}
diff --git a/crates/external_services/src/no_encryption/implementers.rs b/crates/external_services/src/no_encryption/implementers.rs
new file mode 100644
index 00000000000..f67c7c85fd5
--- /dev/null
+++ b/crates/external_services/src/no_encryption/implementers.rs
@@ -0,0 +1,36 @@
+//! Trait implementations for No encryption client
+
+use common_utils::errors::CustomResult;
+use error_stack::{IntoReport, ResultExt};
+use hyperswitch_interfaces::{
+ encryption_interface::{EncryptionError, EncryptionManagementInterface},
+ secrets_interface::{SecretManagementInterface, SecretsManagementError},
+};
+use masking::{ExposeInterface, Secret};
+
+use crate::no_encryption::core::NoEncryption;
+
+#[async_trait::async_trait]
+impl EncryptionManagementInterface for NoEncryption {
+ async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
+ Ok(self.encrypt(input))
+ }
+
+ async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
+ Ok(self.decrypt(input))
+ }
+}
+
+#[async_trait::async_trait]
+impl SecretManagementInterface for NoEncryption {
+ async fn get_secret(
+ &self,
+ input: Secret<String>,
+ ) -> CustomResult<Secret<String>, SecretsManagementError> {
+ String::from_utf8(self.decrypt(input.expose()))
+ .map(Into::into)
+ .into_report()
+ .change_context(SecretsManagementError::FetchSecretFailed)
+ .attach_printable("Failed to convert decrypted value to UTF-8")
+ }
+}
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
new file mode 100644
index 00000000000..855cf63917f
--- /dev/null
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "hyperswitch_interfaces"
+version = "0.1.0"
+edition.workspace = true
+rust-version.workspace = true
+readme = "README.md"
+license.workspace = true
+
+[dependencies]
+async-trait = "0.1.68"
+dyn-clone = "1.0.11"
+serde = { version = "1.0.193", features = ["derive"] }
+thiserror = "1.0.40"
+
+# First party crates
+common_utils = { version = "0.1.0", path = "../common_utils" }
+masking = { version = "0.1.0", path = "../masking" }
diff --git a/crates/hyperswitch_interfaces/README.md b/crates/hyperswitch_interfaces/README.md
new file mode 100644
index 00000000000..e96e3eabe2a
--- /dev/null
+++ b/crates/hyperswitch_interfaces/README.md
@@ -0,0 +1,3 @@
+# Hyperswitch Interfaces
+
+This crate includes interfaces and its error types
diff --git a/crates/hyperswitch_interfaces/src/encryption_interface.rs b/crates/hyperswitch_interfaces/src/encryption_interface.rs
new file mode 100644
index 00000000000..1993019a213
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/encryption_interface.rs
@@ -0,0 +1,29 @@
+//! Encryption related interface and error types
+
+#![warn(missing_docs, missing_debug_implementations)]
+
+use common_utils::errors::CustomResult;
+
+/// Trait defining the interface for encryption management
+#[async_trait::async_trait]
+pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone {
+ /// Encrypt the given input data
+ async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
+
+ /// Decrypt the given input data
+ async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
+}
+
+dyn_clone::clone_trait_object!(EncryptionManagementInterface);
+
+/// Errors that may occur during above encryption functionalities
+#[derive(Debug, thiserror::Error)]
+pub enum EncryptionError {
+ /// An error occurred when encrypting input data.
+ #[error("Failed to encrypt input data")]
+ EncryptionFailed,
+
+ /// An error occurred when decrypting input data.
+ #[error("Failed to decrypt input data")]
+ DecryptionFailed,
+}
diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs
new file mode 100644
index 00000000000..3f7b8d41c3e
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/lib.rs
@@ -0,0 +1,7 @@
+//! Hyperswitch interface
+
+#![warn(missing_docs, missing_debug_implementations)]
+
+pub mod secrets_interface;
+
+pub mod encryption_interface;
diff --git a/crates/hyperswitch_interfaces/src/secrets_interface.rs b/crates/hyperswitch_interfaces/src/secrets_interface.rs
new file mode 100644
index 00000000000..761981bedda
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/secrets_interface.rs
@@ -0,0 +1,36 @@
+//! Secrets management interface
+
+pub mod secret_handler;
+
+pub mod secret_state;
+
+use common_utils::errors::CustomResult;
+use masking::Secret;
+
+/// Trait defining the interface for managing application secrets
+#[async_trait::async_trait]
+pub trait SecretManagementInterface: Send + Sync {
+ /// Given an input, encrypt/store the secret
+ // async fn store_secret(
+ // &self,
+ // input: Secret<String>,
+ // ) -> CustomResult<String, SecretsManagementError>;
+
+ /// Given an input, decrypt/retrieve the secret
+ async fn get_secret(
+ &self,
+ input: Secret<String>,
+ ) -> CustomResult<Secret<String>, SecretsManagementError>;
+}
+
+/// Errors that may occur during secret management
+#[derive(Debug, thiserror::Error)]
+pub enum SecretsManagementError {
+ /// An error occurred when retrieving raw data.
+ #[error("Failed to fetch the raw data")]
+ FetchSecretFailed,
+
+ /// Failed while creating kms client
+ #[error("Failed while creating a secrets management client")]
+ ClientCreationFailed,
+}
diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
new file mode 100644
index 00000000000..a0915b8de69
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_handler.rs
@@ -0,0 +1,21 @@
+//! Module containing trait for raw secret retrieval
+
+use common_utils::errors::CustomResult;
+
+use crate::secrets_interface::{
+ secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
+ SecretManagementInterface, SecretsManagementError,
+};
+
+/// Trait defining the interface for retrieving a raw secret value, given a secured value
+#[async_trait::async_trait]
+pub trait SecretsHandler
+where
+ Self: Sized,
+{
+ /// Construct `Self` with raw secret value and transitions its type from `SecuredSecret` to `RawSecret`
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ kms_client: Box<dyn SecretManagementInterface>,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError>;
+}
diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
new file mode 100644
index 00000000000..6d3f75500af
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs
@@ -0,0 +1,71 @@
+//! Module to manage encrypted and decrypted states for a given type.
+
+use std::marker::PhantomData;
+
+use serde::{Deserialize, Deserializer};
+
+/// Trait defining the states of a secret
+pub trait SecretState {}
+
+/// Decrypted state
+#[derive(Debug, Clone, Deserialize)]
+pub enum RawSecret {}
+
+/// Encrypted state
+#[derive(Debug, Clone, Deserialize)]
+pub enum SecuredSecret {}
+
+impl SecretState for RawSecret {}
+impl SecretState for SecuredSecret {}
+
+/// Struct for managing the encrypted and decrypted states of a given type
+#[derive(Debug, Clone, Default)]
+pub struct SecretStateContainer<T, S: SecretState> {
+ inner: T,
+ marker: PhantomData<S>,
+}
+
+impl<T: Clone, S: SecretState> SecretStateContainer<T, S> {
+ ///
+ /// Get the inner data while consuming self
+ ///
+ #[inline]
+ pub fn into_inner(self) -> T {
+ self.inner
+ }
+
+ ///
+ /// Get the reference to inner value
+ ///
+ #[inline]
+ pub fn get_inner(&self) -> &T {
+ &self.inner
+ }
+}
+
+impl<'de, T: Deserialize<'de>, S: SecretState> Deserialize<'de> for SecretStateContainer<T, S> {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let val = Deserialize::deserialize(deserializer)?;
+ Ok(Self {
+ inner: val,
+ marker: PhantomData,
+ })
+ }
+}
+
+impl<T> SecretStateContainer<T, SecuredSecret> {
+ /// Transition the secret state from `SecuredSecret` to `RawSecret`
+ pub fn transition_state(
+ mut self,
+ decryptor_fn: impl FnOnce(T) -> T,
+ ) -> SecretStateContainer<T, RawSecret> {
+ self.inner = decryptor_fn(self.inner);
+ SecretStateContainer {
+ inner: self.inner,
+ marker: PhantomData,
+ }
+ }
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 9b345217bb5..690a0676fa6 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -111,6 +111,7 @@ diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_
euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }
pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" }
external_services = { version = "0.1.0", path = "../external_services" }
+hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }
kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" }
masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs
index 5e37f2a4dd6..9bb5fcc6f20 100644
--- a/crates/router/src/configs/aws_kms.rs
+++ b/crates/router/src/configs/aws_kms.rs
@@ -1,5 +1,8 @@
use common_utils::errors::CustomResult;
-use external_services::aws_kms::{decrypt::AwsKmsDecrypt, AwsKmsClient, AwsKmsError};
+use external_services::aws_kms::{
+ core::{AwsKmsClient, AwsKmsError},
+ decrypt::AwsKmsDecrypt,
+};
use masking::ExposeInterface;
use crate::configs::settings;
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 71cd61ffa80..82237e7a887 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use api_models::{enums, payment_methods::RequiredFieldInfo};
#[cfg(feature = "aws_kms")]
-use external_services::aws_kms::AwsKmsValue;
+use external_services::aws_kms::core::AwsKmsValue;
use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal};
diff --git a/crates/router/src/configs/hc_vault.rs b/crates/router/src/configs/hc_vault.rs
index f20d8e79ed8..fa6596f7494 100644
--- a/crates/router/src/configs/hc_vault.rs
+++ b/crates/router/src/configs/hc_vault.rs
@@ -1,5 +1,6 @@
use external_services::hashicorp_vault::{
- decrypt::VaultFetch, Engine, HashiCorpError, HashiCorpVault,
+ core::{Engine, HashiCorpError, HashiCorpVault},
+ decrypt::VaultFetch,
};
use masking::ExposeInterface;
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 2572d764d06..13c3ba23e1d 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -12,9 +12,15 @@ use config::{Environment, File};
use external_services::aws_kms;
#[cfg(feature = "email")]
use external_services::email::EmailSettings;
-use external_services::file_storage::FileStorageConfig;
#[cfg(feature = "hashicorp-vault")]
use external_services::hashicorp_vault;
+use external_services::{
+ file_storage::FileStorageConfig,
+ managers::{
+ encryption_management::EncryptionManagementConfig,
+ secrets_management::SecretsManagementConfig,
+ },
+};
use redis_interface::RedisSettings;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use rust_decimal::Decimal;
@@ -30,7 +36,7 @@ use crate::{
events::EventsConfig,
};
#[cfg(feature = "aws_kms")]
-pub type Password = aws_kms::AwsKmsValue;
+pub type Password = aws_kms::core::AwsKmsValue;
#[cfg(not(feature = "aws_kms"))]
pub type Password = masking::Secret<String>;
@@ -89,10 +95,12 @@ pub struct Settings {
pub bank_config: BankRedirectConfig,
pub api_keys: ApiKeys,
#[cfg(feature = "aws_kms")]
- pub kms: aws_kms::AwsKmsConfig,
+ pub kms: aws_kms::core::AwsKmsConfig,
pub file_storage: FileStorageConfig,
+ pub encryption_management: EncryptionManagementConfig,
+ pub secrets_management: SecretsManagementConfig,
#[cfg(feature = "hashicorp-vault")]
- pub hc_vault: hashicorp_vault::HashiCorpVaultConfig,
+ pub hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
pub tokenization: TokenizationConfig,
pub connector_customer: ConnectorCustomer,
#[cfg(feature = "dummy_connector")]
@@ -368,11 +376,11 @@ pub struct Secrets {
pub recon_admin_api_key: String,
pub master_enc_key: Password,
#[cfg(feature = "aws_kms")]
- pub kms_encrypted_jwt_secret: aws_kms::AwsKmsValue,
+ pub kms_encrypted_jwt_secret: aws_kms::core::AwsKmsValue,
#[cfg(feature = "aws_kms")]
- pub kms_encrypted_admin_api_key: aws_kms::AwsKmsValue,
+ pub kms_encrypted_admin_api_key: aws_kms::core::AwsKmsValue,
#[cfg(feature = "aws_kms")]
- pub kms_encrypted_recon_admin_api_key: aws_kms::AwsKmsValue,
+ pub kms_encrypted_recon_admin_api_key: aws_kms::core::AwsKmsValue,
}
#[derive(Debug, Deserialize, Clone)]
@@ -598,7 +606,7 @@ pub struct ApiKeys {
/// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API
/// keys
#[cfg(feature = "aws_kms")]
- pub kms_encrypted_hash_key: aws_kms::AwsKmsValue,
+ pub kms_encrypted_hash_key: aws_kms::core::AwsKmsValue,
/// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating
/// hashes of API keys
@@ -724,6 +732,14 @@ impl Settings {
self.lock_settings.validate()?;
self.events.validate()?;
+
+ self.encryption_management
+ .validate()
+ .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
+
+ self.secrets_management
+ .validate()
+ .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
Ok(())
}
}
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 162f8bed0f8..b694d1291a8 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -38,9 +38,9 @@ static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_K
pub async fn get_hash_key(
api_key_config: &settings::ApiKeys,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
#[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::HashiCorpVault,
+ hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> {
HASH_KEY
.get_or_try_init(|| async {
@@ -57,7 +57,7 @@ pub async fn get_hash_key(
#[cfg(feature = "hashicorp-vault")]
let hash_key = hash_key
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -153,9 +153,9 @@ impl PlaintextApiKey {
#[instrument(skip_all)]
pub async fn create_api_key(
state: AppState,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
#[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::HashiCorpVault,
+ hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
api_key: api::CreateApiKeyRequest,
merchant_id: String,
) -> RouterResponse<api::CreateApiKeyResponse> {
@@ -590,9 +590,9 @@ mod tests {
let hash_key = get_hash_key(
&settings.api_keys,
#[cfg(feature = "aws_kms")]
- external_services::aws_kms::get_aws_kms_client(&settings.kms).await,
+ external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await,
#[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::get_hashicorp_client(&settings.hc_vault)
+ external_services::hashicorp_vault::core::get_hashicorp_client(&settings.hc_vault)
.await
.unwrap(),
)
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 43701c80786..733b565beed 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -48,7 +48,7 @@ pub async fn delete_entry_from_blocklist(
})?;
#[cfg(feature = "aws_kms")]
- let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms)
+ let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(blocklist_fingerprint.encrypted_fingerprint)
.await
@@ -244,7 +244,7 @@ pub async fn insert_entry_into_blocklist(
})?;
#[cfg(feature = "aws_kms")]
- let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms)
+ let decrypted_fingerprint = aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(blocklist_fingerprint.encrypted_fingerprint)
.await
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 062c58e056c..479a0685a97 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -189,12 +189,13 @@ async fn create_applepay_session_token(
common_merchant_identifier,
) = async {
#[cfg(feature = "hashicorp-vault")]
- let client = external_services::hashicorp_vault::get_hashicorp_client(
- &state.conf.hc_vault,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while building hashicorp client")?;
+ let client =
+ external_services::hashicorp_vault::core::get_hashicorp_client(
+ &state.conf.hc_vault,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while building hashicorp client")?;
#[cfg(feature = "hashicorp-vault")]
{
@@ -206,7 +207,7 @@ async fn create_applepay_session_token(
.apple_pay_merchant_cert
.clone(),
)
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
.expose(),
@@ -217,7 +218,7 @@ async fn create_applepay_session_token(
.apple_pay_merchant_cert_key
.clone(),
)
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
.expose(),
@@ -228,7 +229,7 @@ async fn create_applepay_session_token(
.common_merchant_identifier
.clone(),
)
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
.expose(),
@@ -260,7 +261,7 @@ async fn create_applepay_session_token(
#[cfg(feature = "aws_kms")]
let decrypted_apple_pay_merchant_cert =
- aws_kms::get_aws_kms_client(&state.conf.kms)
+ aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(apple_pay_merchant_cert)
.await
@@ -269,7 +270,7 @@ async fn create_applepay_session_token(
#[cfg(feature = "aws_kms")]
let decrypted_apple_pay_merchant_cert_key =
- aws_kms::get_aws_kms_client(&state.conf.kms)
+ aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(apple_pay_merchant_cert_key)
.await
@@ -280,7 +281,7 @@ async fn create_applepay_session_token(
#[cfg(feature = "aws_kms")]
let decrypted_merchant_identifier =
- aws_kms::get_aws_kms_client(&state.conf.kms)
+ aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(common_merchant_identifier)
.await
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 7ec1f5e9213..b93d959eb8d 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3537,16 +3537,17 @@ impl ApplePayData {
) -> CustomResult<String, errors::ApplePayDecryptionError> {
let apple_pay_ppc = async {
#[cfg(feature = "hashicorp-vault")]
- let client =
- external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
- .attach_printable("Failed while creating client")?;
+ let client = external_services::hashicorp_vault::core::get_hashicorp_client(
+ &state.conf.hc_vault,
+ )
+ .await
+ .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
+ .attach_printable("Failed while creating client")?;
#[cfg(feature = "hashicorp-vault")]
let output =
masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc.clone())
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?
.expose();
@@ -3559,7 +3560,7 @@ impl ApplePayData {
.await?;
#[cfg(feature = "aws_kms")]
- let cert_data = aws_kms::get_aws_kms_client(&state.conf.kms)
+ let cert_data = aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(&apple_pay_ppc)
.await
@@ -3620,16 +3621,17 @@ impl ApplePayData {
let apple_pay_ppc_key = async {
#[cfg(feature = "hashicorp-vault")]
- let client =
- external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault)
- .await
- .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
- .attach_printable("Failed while creating client")?;
+ let client = external_services::hashicorp_vault::core::get_hashicorp_client(
+ &state.conf.hc_vault,
+ )
+ .await
+ .change_context(errors::ApplePayDecryptionError::DecryptionFailed)
+ .attach_printable("Failed while creating client")?;
#[cfg(feature = "hashicorp-vault")]
let output =
masking::Secret::new(state.conf.applepay_decrypt_keys.apple_pay_ppc_key.clone())
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)
.attach_printable("Failed while creating client")?
@@ -3643,7 +3645,7 @@ impl ApplePayData {
.await?;
#[cfg(feature = "aws_kms")]
- let decrypted_apple_pay_ppc_key = aws_kms::get_aws_kms_client(&state.conf.kms)
+ let decrypted_apple_pay_ppc_key = aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(&apple_pay_ppc_key)
.await
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index f77d5120812..f00c452f3ea 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -349,14 +349,15 @@ async fn store_bank_details_in_payment_methods(
let pm_auth_key = async {
#[cfg(feature = "hashicorp-vault")]
- let client = external_services::hashicorp_vault::get_hashicorp_client(&state.conf.hc_vault)
- .await
- .change_context(ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while creating client")?;
+ let client =
+ external_services::hashicorp_vault::core::get_hashicorp_client(&state.conf.hc_vault)
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while creating client")?;
#[cfg(feature = "hashicorp-vault")]
let output = masking::Secret::new(state.conf.payment_method_auth.pm_auth_key.clone())
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(ApiErrorResponse::InternalServerError)?
.expose();
@@ -369,7 +370,7 @@ async fn store_bank_details_in_payment_methods(
.await?;
#[cfg(feature = "aws_kms")]
- let pm_auth_key = aws_kms::get_aws_kms_client(&state.conf.kms)
+ let pm_auth_key = aws_kms::core::get_aws_kms_client(&state.conf.kms)
.await
.decrypt(pm_auth_key)
.await
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index 0ed70e6e0c6..79513bfb308 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -13,7 +13,7 @@ pub async fn verify_merchant_creds_for_applepay(
state: AppState,
_req: &actix_web::HttpRequest,
body: verifications::ApplepayMerchantVerificationRequest,
- kms_config: &aws_kms::AwsKmsConfig,
+ kms_config: &aws_kms::core::AwsKmsConfig,
merchant_id: String,
) -> CustomResult<
services::ApplicationResponse<ApplepayMerchantResponse>,
@@ -27,19 +27,19 @@ pub async fn verify_merchant_creds_for_applepay(
let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key;
let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint;
- let applepay_internal_merchant_identifier = aws_kms::get_aws_kms_client(kms_config)
+ let applepay_internal_merchant_identifier = aws_kms::core::get_aws_kms_client(kms_config)
.await
.decrypt(encrypted_merchant_identifier)
.await
.change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
- let cert_data = aws_kms::get_aws_kms_client(kms_config)
+ let cert_data = aws_kms::core::get_aws_kms_client(kms_config)
.await
.decrypt(encrypted_cert)
.await
.change_context(api_error_response::ApiErrorResponse::InternalServerError)?;
- let key_data = aws_kms::get_aws_kms_client(kms_config)
+ let key_data = aws_kms::core::get_aws_kms_client(kms_config)
.await
.decrypt(encrypted_key)
.await
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index cf859d048dd..cf0f009a0b1 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -46,10 +46,10 @@ pub async fn api_key_create(
|state, _, payload| async {
#[cfg(feature = "aws_kms")]
let aws_kms_client =
- external_services::aws_kms::get_aws_kms_client(&state.clone().conf.kms).await;
+ external_services::aws_kms::core::get_aws_kms_client(&state.clone().conf.kms).await;
#[cfg(feature = "hashicorp-vault")]
- let hc_client = external_services::hashicorp_vault::get_hashicorp_client(
+ let hc_client = external_services::hashicorp_vault::core::get_hashicorp_client(
&state.clone().conf.hc_vault,
)
.await
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 651d3c0026f..84f8b62b57d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -13,6 +13,7 @@ use external_services::email::{ses::AwsSes, EmailService};
use external_services::file_storage::FileStorageInterface;
#[cfg(all(feature = "olap", feature = "hashicorp-vault"))]
use external_services::hashicorp_vault::decrypt::VaultFetch;
+use hyperswitch_interfaces::encryption_interface::EncryptionManagementInterface;
#[cfg(all(feature = "olap", feature = "aws_kms"))]
use masking::PeekInterface;
use router_env::tracing_actix_web::RequestId;
@@ -73,6 +74,7 @@ pub struct AppState {
pub pool: crate::analytics::AnalyticsProvider,
pub request_id: Option<RequestId>,
pub file_storage_client: Box<dyn FileStorageInterface>,
+ pub encryption_client: Box<dyn EncryptionManagementInterface>,
}
impl scheduler::SchedulerAppState for AppState {
@@ -150,13 +152,20 @@ impl AppState {
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
+ #[allow(clippy::expect_used)]
+ let encryption_client = conf
+ .encryption_management
+ .get_encryption_management_client()
+ .await
+ .expect("Failed to create encryption client");
+
Box::pin(async move {
#[cfg(feature = "aws_kms")]
- let aws_kms_client = aws_kms::get_aws_kms_client(&conf.kms).await;
+ let aws_kms_client = aws_kms::core::get_aws_kms_client(&conf.kms).await;
#[cfg(all(feature = "hashicorp-vault", feature = "olap"))]
#[allow(clippy::expect_used)]
let hc_client =
- external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault)
+ external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault)
.await
.expect("Failed while creating hashicorp_client");
let testable = storage_impl == StorageImpl::PostgresqlTest;
@@ -204,7 +213,7 @@ impl AppState {
sqlx.password = sqlx
.password
.clone()
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.expect("Failed while fetching from hashicorp vault");
}
@@ -230,7 +239,7 @@ impl AppState {
{
conf.connector_onboarding = conf
.connector_onboarding
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.expect("Failed to decrypt connector onboarding credentials");
}
@@ -254,7 +263,7 @@ impl AppState {
conf.jwekey = conf
.jwekey
.clone()
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.expect("Failed to decrypt connector onboarding credentials");
}
@@ -287,6 +296,7 @@ impl AppState {
pool,
request_id: None,
file_storage_client,
+ encryption_client,
}
})
.await
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 220fde4631f..dc7bf14fecf 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -46,18 +46,19 @@ pub async fn get_store(
test_transaction: bool,
) -> StorageResult<Store> {
#[cfg(feature = "aws_kms")]
- let aws_kms_client = aws_kms::get_aws_kms_client(&config.kms).await;
+ let aws_kms_client = aws_kms::core::get_aws_kms_client(&config.kms).await;
#[cfg(feature = "hashicorp-vault")]
- let hc_client = external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault)
- .await
- .change_context(StorageError::InitializationError)?;
+ let hc_client =
+ external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
+ .await
+ .change_context(StorageError::InitializationError)?;
let master_config = config.master_database.clone();
#[cfg(feature = "hashicorp-vault")]
let master_config = master_config
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to fetch data from hashicorp vault")?;
@@ -74,7 +75,7 @@ pub async fn get_store(
#[cfg(all(feature = "olap", feature = "hashicorp-vault"))]
let replica_config = replica_config
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to fetch data from hashicorp vault")?;
@@ -128,15 +129,15 @@ pub async fn get_store(
#[allow(clippy::expect_used)]
async fn get_master_enc_key(
conf: &crate::configs::settings::Settings,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
#[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::HashiCorpVault,
+ hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
) -> StrongSecret<Vec<u8>> {
let master_enc_key = conf.secrets.master_enc_key.clone();
#[cfg(feature = "hashicorp-vault")]
let master_enc_key = master_enc_key
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.expect("Failed to fetch master enc key");
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 308ceb2672b..990e0785306 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -226,9 +226,9 @@ where
api_keys::get_hash_key(
&config.api_keys,
#[cfg(feature = "aws_kms")]
- aws_kms::get_aws_kms_client(&config.kms).await,
+ aws_kms::core::get_aws_kms_client(&config.kms).await,
#[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault)
+ external_services::hashicorp_vault::core::get_hashicorp_client(&config.hc_vault)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?,
)
@@ -289,9 +289,9 @@ static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> =
pub async fn get_admin_api_key(
secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
#[cfg(feature = "hashicorp-vault")]
- hc_client: &external_services::hashicorp_vault::HashiCorpVault,
+ hc_client: &external_services::hashicorp_vault::core::HashiCorpVault,
) -> RouterResult<&'static StrongSecret<String>> {
ADMIN_API_KEY
.get_or_try_init(|| async {
@@ -308,7 +308,7 @@ pub async fn get_admin_api_key(
#[cfg(feature = "hashicorp-vault")]
let admin_api_key = masking::Secret::new(admin_api_key)
- .fetch_inner::<external_services::hashicorp_vault::Kv2>(hc_client)
+ .fetch_inner::<external_services::hashicorp_vault::core::Kv2>(hc_client)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to KMS decrypt admin API key")?
@@ -369,9 +369,9 @@ where
let admin_api_key = get_admin_api_key(
&conf.secrets,
#[cfg(feature = "aws_kms")]
- aws_kms::get_aws_kms_client(&conf.kms).await,
+ aws_kms::core::get_aws_kms_client(&conf.kms).await,
#[cfg(feature = "hashicorp-vault")]
- external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault)
+ external_services::hashicorp_vault::core::get_hashicorp_client(&conf.hc_vault)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting admin api key")?,
@@ -873,7 +873,7 @@ static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::On
pub async fn get_jwt_secret(
secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::core::AwsKmsClient,
) -> RouterResult<&'static StrongSecret<String>> {
JWT_SECRET
.get_or_try_init(|| async {
@@ -901,7 +901,7 @@ where
let secret = get_jwt_secret(
&conf.secrets,
#[cfg(feature = "aws_kms")]
- aws_kms::get_aws_kms_client(&conf.kms).await,
+ aws_kms::core::get_aws_kms_client(&conf.kms).await,
)
.await?
.peek()
@@ -972,7 +972,7 @@ static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> =
#[cfg(feature = "recon")]
pub async fn get_recon_admin_api_key(
secrets: &settings::Secrets,
- #[cfg(feature = "aws_kms")] kms_client: &aws_kms::AwsKmsClient,
+ #[cfg(feature = "aws_kms")] kms_client: &aws_kms::core::AwsKmsClient,
) -> RouterResult<&'static StrongSecret<String>> {
RECON_API_KEY
.get_or_try_init(|| async {
@@ -1013,7 +1013,7 @@ where
let admin_api_key = get_recon_admin_api_key(
&conf.secrets,
#[cfg(feature = "aws_kms")]
- aws_kms::get_aws_kms_client(&conf.kms).await,
+ aws_kms::core::get_aws_kms_client(&conf.kms).await,
)
.await?;
diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs
index 08db52e4020..05de1b4e11e 100644
--- a/crates/router/src/services/jwt.rs
+++ b/crates/router/src/services/jwt.rs
@@ -27,7 +27,7 @@ where
let jwt_secret = authentication::get_jwt_secret(
&settings.secrets,
#[cfg(feature = "aws_kms")]
- external_services::aws_kms::get_aws_kms_client(&settings.kms).await,
+ external_services::aws_kms::core::get_aws_kms_client(&settings.kms).await,
)
.await
.change_context(UserErrors::InternalServerError)
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs
index 057805a76f0..30ac4815efb 100644
--- a/crates/router/src/utils/currency.rs
+++ b/crates/router/src/utils/currency.rs
@@ -128,9 +128,9 @@ async fn waited_fetch_and_update_caches(
state: &AppState,
local_fetch_retry_delay: u64,
local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
for _n in 1..local_fetch_retry_count {
sleep(Duration::from_millis(local_fetch_retry_delay)).await;
@@ -192,9 +192,9 @@ pub async fn get_forex_rates(
call_delay: i64,
local_fetch_retry_delay: u64,
local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
if let Some(local_rates) = retrieve_forex_from_local().await {
if local_rates.is_expired(call_delay) {
@@ -234,9 +234,9 @@ async fn handler_local_no_data(
call_delay: i64,
_local_fetch_retry_delay: u64,
_local_fetch_retry_count: u64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match retrieve_forex_from_redis(state).await {
Ok(Some(data)) => {
@@ -281,9 +281,9 @@ async fn handler_local_no_data(
async fn successive_fetch_and_save_forex(
state: &AppState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match acquire_redis_lock(state).await {
Ok(lock_acquired) => {
@@ -351,9 +351,9 @@ async fn fallback_forex_redis_check(
state: &AppState,
redis_data: FxExchangeRatesCacheEntry,
call_delay: i64,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await {
Some(redis_forex) => {
@@ -381,9 +381,9 @@ async fn handler_local_expired(
state: &AppState,
call_delay: i64,
local_rates: FxExchangeRatesCacheEntry,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
match retrieve_forex_from_redis(state).await {
Ok(redis_data) => {
@@ -427,14 +427,14 @@ async fn handler_local_expired(
async fn fetch_forex_rates(
state: &AppState,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> {
let forex_api_key = async {
#[cfg(feature = "hashicorp-vault")]
- let client = hashicorp_vault::get_hashicorp_client(hc_config)
+ let client = hashicorp_vault::core::get_hashicorp_client(hc_config)
.await
.change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
@@ -446,7 +446,7 @@ async fn fetch_forex_rates(
.forex_api
.api_key
.clone()
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
@@ -454,7 +454,7 @@ async fn fetch_forex_rates(
}
.await?;
#[cfg(feature = "aws_kms")]
- let forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config)
+ let forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config)
.await
.decrypt(forex_api_key.peek())
.await
@@ -516,13 +516,13 @@ async fn fetch_forex_rates(
pub async fn fallback_fetch_forex_rates(
state: &AppState,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> {
let fallback_api_key = async {
#[cfg(feature = "hashicorp-vault")]
- let client = hashicorp_vault::get_hashicorp_client(hc_config)
+ let client = hashicorp_vault::core::get_hashicorp_client(hc_config)
.await
.change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
@@ -534,7 +534,7 @@ pub async fn fallback_fetch_forex_rates(
.forex_api
.fallback_api_key
.clone()
- .fetch_inner::<hashicorp_vault::Kv2>(client)
+ .fetch_inner::<hashicorp_vault::core::Kv2>(client)
.await
.change_context(ForexCacheError::AwsKmsDecryptionFailed)?;
@@ -542,7 +542,7 @@ pub async fn fallback_fetch_forex_rates(
}
.await?;
#[cfg(feature = "aws_kms")]
- let fallback_forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config)
+ let fallback_forex_api_key = aws_kms::core::get_aws_kms_client(aws_kms_config)
.await
.decrypt(fallback_api_key.peek())
.await
@@ -691,9 +691,9 @@ pub async fn convert_currency(
amount: i64,
to_currency: String,
from_currency: String,
- #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig,
+ #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::core::AwsKmsConfig,
#[cfg(feature = "hashicorp-vault")]
- hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig,
+ hc_config: &external_services::hashicorp_vault::core::HashiCorpVaultConfig,
) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> {
let rates = get_forex_rates(
&state,
| 2024-02-02T13:02:25Z |
## Description
<!-- Describe your changes in detail -->
Create a new crate `Hyperswitch-interface` containing below modules for now:
`secrets_interface`: Module used for application config `encryption` and `decryption` during startup which will contain its own trait and error types
`encryption_interface`: Module used for user value `encryption` and `decryption` during runtime which will contain its own trait and error types
This PR only adds the above crate with the addition of `secret_management_config` and `encryption_management_config` in the `router`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cfa10aa60ef16d2302787f7ecf7c129228fc0549 |
New crates addition which doesn't integrate with other existing crates yet. So basic sanity testing should suffice
| [
"Cargo.lock",
"crates/drainer/src/connection.rs",
"crates/drainer/src/services.rs",
"crates/drainer/src/settings.rs",
"crates/external_services/Cargo.toml",
"crates/external_services/src/aws_kms.rs",
"crates/external_services/src/aws_kms/core.rs",
"crates/external_services/src/aws_kms/decrypt.rs",
"... | |
juspay/hyperswitch | juspay__hyperswitch-3510 | Bug: [FIX] add a configuration validation for workers
We don't have a validation check
[number of workers in our config](https://github.com/juspay/hyperswitch/blob/94cd7b689758a71e13a3eaa655335e658d13afc8/crates/router/src/configs/settings.rs#L422) . But if the number of workers is zero actix straight out panics. Ref: https://docs.rs/actix-web/latest/actix_web/struct.HttpServer.html#method.workers | diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 910ae754347..69d0274d704 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -68,10 +68,18 @@ impl super::settings::Locker {
impl super::settings::Server {
pub fn validate(&self) -> Result<(), ApplicationError> {
- common_utils::fp_utils::when(self.host.is_default_or_empty(), || {
+ use common_utils::fp_utils::when;
+
+ when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"server host must not be empty".into(),
))
+ })?;
+
+ when(self.workers == 0, || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "number of workers must be greater than 0".into(),
+ ))
})
}
}
| 2024-02-02T09:54:18Z |
## Description
<!-- Describe your changes in detail -->
Added validation check on number workers
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
It fixes #3510
# | cf0e0b330e4c62860f645bcb61d96b07c9f4fb7b |
Nothing to test in this PR
| [
"crates/router/src/configs/validations.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3534 | Bug: feat(user_role): Update role API - test and finalise
| diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b29ce811be3..c3e6908c733 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -142,7 +142,6 @@ pub struct GetUsersResponse(pub Vec<UserDetails>);
#[derive(Debug, serde::Serialize)]
pub struct UserDetails {
- pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
pub role_id: String,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index e8c9b777c7f..2672293390e 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -86,7 +86,7 @@ pub struct PermissionInfo {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserRoleRequest {
- pub user_id: String,
+ pub email: pii::Email,
pub role_id: String,
}
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index d3b1679378e..c837fd7c20f 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -60,6 +60,8 @@ pub enum UserErrors {
MaxInvitationsError,
#[error("RoleNotFound")]
RoleNotFound,
+ #[error("InvalidRoleOperationWithMessage")]
+ InvalidRoleOperationWithMessage(String),
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -103,9 +105,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::CompanyNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None))
}
- Self::MerchantAccountCreationError(error_message) => {
- AER::InternalServerError(ApiError::new(sub_code, 15, error_message, None))
- }
+ Self::MerchantAccountCreationError(_) => AER::InternalServerError(ApiError::new(
+ sub_code,
+ 15,
+ self.get_error_message(),
+ None,
+ )),
Self::InvalidEmailError => {
AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None))
}
@@ -151,6 +156,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::RoleNotFound => {
AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None))
}
+ Self::InvalidRoleOperationWithMessage(_) => {
+ AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None))
+ }
}
}
}
@@ -184,6 +192,7 @@ impl UserErrors {
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,
}
}
}
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index a54dae1c035..1f82132a45f 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -509,3 +509,34 @@ impl RedisErrorExt for error_stack::Report<errors::RedisError> {
}
}
}
+
+#[cfg(feature = "olap")]
+impl<T> StorageErrorExt<T, errors::UserErrors> for error_stack::Result<T, errors::StorageError> {
+ #[track_caller]
+ fn to_not_found_response(
+ self,
+ not_found_response: errors::UserErrors,
+ ) -> error_stack::Result<T, errors::UserErrors> {
+ self.map_err(|e| {
+ if e.current_context().is_db_not_found() {
+ e.change_context(not_found_response)
+ } else {
+ e.change_context(errors::UserErrors::InternalServerError)
+ }
+ })
+ }
+
+ #[track_caller]
+ fn to_duplicate_response(
+ self,
+ duplicate_response: errors::UserErrors,
+ ) -> error_stack::Result<T, errors::UserErrors> {
+ self.map_err(|e| {
+ if e.current_context().is_db_unique_violation() {
+ e.change_context(duplicate_response)
+ } else {
+ e.change_context(errors::UserErrors::InternalServerError)
+ }
+ })
+ }
+}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 70c3eb6673b..7b37f529f83 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -11,13 +11,15 @@ use router_env::env;
#[cfg(feature = "email")]
use router_env::logger;
-use super::errors::{UserErrors, UserResponse, UserResult};
+use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult};
#[cfg(feature = "email")]
use crate::services::email::types as email_types;
use crate::{
consts,
routes::AppState,
- services::{authentication as auth, ApplicationResponse},
+ services::{
+ authentication as auth, authorization::predefined_permissions, ApplicationResponse,
+ },
types::domain,
utils,
};
@@ -150,7 +152,7 @@ pub async fn signin(
let preferred_role = user_from_db
.get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str())
.await
- .change_context(UserErrors::InternalServerError)
+ .to_not_found_response(UserErrors::InternalServerError)
.attach_printable("User role with preferred_merchant_id not found")?;
domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy {
user: user_from_db,
@@ -408,11 +410,17 @@ pub async fn invite_user(
.change_context(UserErrors::InternalServerError)?;
if inviter_user.email == request.email {
- return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("User Inviting themself");
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User Inviting themselves".to_string(),
+ )
+ .into());
+ }
+
+ if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ return Err(UserErrors::InvalidRoleId.into())
+ .attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
- utils::user_role::validate_role_id(request.role_id.as_str())?;
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let invitee_user = state
@@ -561,14 +569,20 @@ async fn handle_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
) -> UserResult<InviteMultipleUserResponse> {
- let inviter_user = user_from_token.get_user(state.clone()).await?;
+ let inviter_user = user_from_token.get_user(state).await?;
if inviter_user.email == request.email {
- return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("User Inviting themself");
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User Inviting themselves".to_string(),
+ )
+ .into());
+ }
+
+ if !predefined_permissions::is_role_invitable(request.role_id.as_str())? {
+ return Err(UserErrors::InvalidRoleId.into())
+ .attach_printable(format!("role_id = {} is not invitable", request.role_id));
}
- utils::user_role::validate_role_id(request.role_id.as_str())?;
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let invitee_user = state
.store
@@ -733,7 +747,11 @@ pub async fn resend_invite(
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::InvalidRoleOperation)
- .attach_printable("User role with given UserId MerchantId not found")
+ .attach_printable(format!(
+ "User role with user_id = {} and org_id = {} is not found",
+ user.get_user_id(),
+ user_from_token.merchant_id
+ ))
} else {
e.change_context(UserErrors::InternalServerError)
}
@@ -741,7 +759,7 @@ pub async fn resend_invite(
if !matches!(user_role.status, UserStatus::InvitationSent) {
return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("Invalid Status for Reinvitation");
+ .attach_printable("User status is not InvitationSent".to_string());
}
let email_contents = email_types::InviteUser {
@@ -832,8 +850,10 @@ pub async fn switch_merchant_id(
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::SwitchMerchantResponse> {
if user_from_token.merchant_id == request.merchant_id {
- return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("User switch to same merchant id.");
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "User switching to same merchant id".to_string(),
+ )
+ .into());
}
let user_roles = state
@@ -847,7 +867,7 @@ pub async fn switch_merchant_id(
.filter(|role| role.status == UserStatus::Active)
.collect::<Vec<_>>();
- let user = user_from_token.get_user(state.clone()).await?.into();
+ let user = user_from_token.get_user(&state).await?.into();
let (token, role_id) = if utils::user_role::is_internal_role(&user_from_token.role_id) {
let key_store = state
@@ -916,8 +936,7 @@ pub async fn create_merchant_account(
user_from_token: auth::UserFromToken,
req: user_api::UserMerchantCreate,
) -> UserResponse<()> {
- let user_from_db: domain::UserFromStorage =
- user_from_token.get_user(state.clone()).await?.into();
+ let user_from_db: domain::UserFromStorage = user_from_token.get_user(&state).await?.into();
let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?;
let new_merchant = new_user.get_new_merchant();
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 742c281b89a..b48b39eea14 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -5,7 +5,7 @@ use masking::ExposeInterface;
use router_env::logger;
use crate::{
- core::errors::{UserErrors, UserResponse},
+ core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::AppState,
services::{
authentication::{self as auth},
@@ -33,6 +33,7 @@ pub async fn list_roles(_state: AppState) -> UserResponse<user_role_api::ListRol
Ok(ApplicationResponse::Json(user_role_api::ListRolesResponse(
predefined_permissions::PREDEFINED_PERMISSIONS
.iter()
+ .filter(|(_, role_info)| role_info.is_invitable())
.filter_map(|(role_id, role_info)| {
utils::user_role::get_role_name_and_permission_response(role_info).map(
|(permissions, role_name)| user_role_api::RoleInfoResponse {
@@ -87,34 +88,49 @@ pub async fn update_user_role(
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
) -> UserResponse<()> {
- let merchant_id = user_from_token.merchant_id;
- let role_id = req.role_id.clone();
- utils::user_role::validate_role_id(role_id.as_str())?;
+ if !predefined_permissions::is_role_updatable(&req.role_id)? {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable(format!("User role cannot be updated to {}", req.role_id));
+ }
+
+ let user_to_be_updated =
+ utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?)
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)
+ .attach_printable("User not found in our records".to_string())?;
- if user_from_token.user_id == req.user_id {
+ if user_from_token.user_id == user_to_be_updated.get_user_id() {
return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("Admin User Changing their role");
+ .attach_printable("User Changing their own role");
+ }
+
+ let user_role_to_be_updated = user_to_be_updated
+ .get_role_from_db_by_merchant_id(&state, &user_from_token.merchant_id)
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)?;
+
+ if !predefined_permissions::is_role_updatable(&user_role_to_be_updated.role_id)? {
+ return Err(UserErrors::InvalidRoleOperation.into()).attach_printable(format!(
+ "User role cannot be updated from {}",
+ user_role_to_be_updated.role_id
+ ));
}
state
.store
.update_user_role_by_user_id_merchant_id(
- req.user_id.as_str(),
- merchant_id.as_str(),
+ user_to_be_updated.get_user_id(),
+ user_role_to_be_updated.merchant_id.as_str(),
UserRoleUpdate::UpdateRole {
- role_id,
+ role_id: req.role_id.clone(),
modified_by: user_from_token.user_id,
},
)
.await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- return e
- .change_context(UserErrors::InvalidRoleOperation)
- .attach_printable("UserId MerchantId not found");
- }
- e.change_context(UserErrors::InternalServerError)
- })?;
+ .to_not_found_response(UserErrors::InvalidRoleOperation)
+ .attach_printable("User with given email is not found in the organization")?;
+
+ auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
Ok(ApplicationResponse::StatusOk)
}
@@ -181,7 +197,7 @@ pub async fn delete_user_role(
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::InvalidRoleOperation)
- .attach_printable("User not found in records")
+ .attach_printable("User not found in our records")
} else {
e.change_context(UserErrors::InternalServerError)
}
@@ -204,9 +220,9 @@ pub async fn delete_user_role(
.find(|&role| role.merchant_id == user_from_token.merchant_id.as_str())
{
Some(user_role) => {
- if !predefined_permissions::is_role_deletable(&user_role.role_id) {
- return Err(UserErrors::InvalidRoleId.into())
- .attach_printable("Deletion not allowed for users with specific role id");
+ if !predefined_permissions::is_role_deletable(&user_role.role_id)? {
+ return Err(UserErrors::InvalidDeleteOperation.into())
+ .attach_printable(format!("role_id = {} is not deletable", user_role.role_id));
}
}
None => {
diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs
index 6fe0ddcc360..fd98d90c191 100644
--- a/crates/router/src/services/authorization/predefined_permissions.rs
+++ b/crates/router/src/services/authorization/predefined_permissions.rs
@@ -1,15 +1,21 @@
use std::collections::HashMap;
+#[cfg(feature = "olap")]
+use error_stack::ResultExt;
use once_cell::sync::Lazy;
use super::permissions::Permission;
use crate::consts;
+#[cfg(feature = "olap")]
+use crate::core::errors::{UserErrors, UserResult};
+#[allow(dead_code)]
pub struct RoleInfo {
permissions: Vec<Permission>,
name: Option<&'static str>,
is_invitable: bool,
is_deletable: bool,
+ is_updatable: bool,
}
impl RoleInfo {
@@ -65,6 +71,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: None,
is_invitable: false,
is_deletable: false,
+ is_updatable: false,
},
);
roles.insert(
@@ -90,6 +97,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: None,
is_invitable: false,
is_deletable: false,
+ is_updatable: false,
},
);
@@ -130,6 +138,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("Organization Admin"),
is_invitable: false,
is_deletable: false,
+ is_updatable: false,
},
);
@@ -170,6 +179,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("Admin"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles.insert(
@@ -195,6 +205,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("View Only"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles.insert(
@@ -221,6 +232,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("IAM"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles.insert(
@@ -247,6 +259,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("Developer"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles.insert(
@@ -278,6 +291,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("Operator"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles.insert(
@@ -301,6 +315,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
name: Some("Customer Support"),
is_invitable: true,
is_deletable: true,
+ is_updatable: true,
},
);
roles
@@ -312,14 +327,29 @@ pub fn get_role_name_from_id(role_id: &str) -> Option<&'static str> {
.and_then(|role_info| role_info.name)
}
-pub fn is_role_invitable(role_id: &str) -> bool {
+#[cfg(feature = "olap")]
+pub fn is_role_invitable(role_id: &str) -> UserResult<bool> {
PREDEFINED_PERMISSIONS
.get(role_id)
- .map_or(false, |role_info| role_info.is_invitable)
+ .map(|role_info| role_info.is_invitable)
+ .ok_or(UserErrors::InvalidRoleId.into())
+ .attach_printable(format!("role_id = {} doesn't exist", role_id))
}
-pub fn is_role_deletable(role_id: &str) -> bool {
+#[cfg(feature = "olap")]
+pub fn is_role_deletable(role_id: &str) -> UserResult<bool> {
PREDEFINED_PERMISSIONS
.get(role_id)
- .map_or(false, |role_info| role_info.is_deletable)
+ .map(|role_info| role_info.is_deletable)
+ .ok_or(UserErrors::InvalidRoleId.into())
+ .attach_printable(format!("role_id = {} doesn't exist", role_id))
+}
+
+#[cfg(feature = "olap")]
+pub fn is_role_updatable(role_id: &str) -> UserResult<bool> {
+ PREDEFINED_PERMISSIONS
+ .get(role_id)
+ .map(|role_info| role_info.is_updatable)
+ .ok_or(UserErrors::InvalidRoleId.into())
+ .attach_printable(format!("role_id = {} doesn't exist", role_id))
}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index d3ea69ecd86..468fa8e4cd2 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -3,7 +3,7 @@ use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
-use common_utils::pii;
+use common_utils::{errors::CustomResult, pii};
use diesel_models::{
enums::UserStatus,
organization as diesel_org,
@@ -21,7 +21,7 @@ use crate::{
consts,
core::{
admin,
- errors::{UserErrors, UserResult},
+ errors::{self, UserErrors, UserResult},
},
db::StorageInterface,
routes::AppState,
@@ -778,19 +778,11 @@ impl UserFromStorage {
&self,
state: &AppState,
merchant_id: &str,
- ) -> UserResult<UserRole> {
+ ) -> CustomResult<UserRole, errors::StorageError> {
state
.store
.find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id)
.await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- UserErrors::RoleNotFound
- } else {
- UserErrors::InternalServerError
- }
- })
- .into_report()
}
}
@@ -850,7 +842,6 @@ impl TryFrom<UserAndRoleJoined> for user_api::UserDetails {
.to_string();
Ok(Self {
- user_id: user_and_role.0.user_id,
email: user_and_role.0.email,
name: user_and_role.0.name,
role_id,
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 697d10f772e..9c2d2c1fd3f 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,15 +1,16 @@
use std::collections::HashMap;
use api_models::user as user_api;
+use common_utils::errors::CustomResult;
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use crate::{
- core::errors::{UserErrors, UserResult},
+ core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
services::authentication::{AuthToken, UserFromToken},
- types::domain::{MerchantAccount, UserFromStorage},
+ types::domain::{self, MerchantAccount, UserFromStorage},
};
pub mod dashboard_metadata;
@@ -47,7 +48,7 @@ impl UserFromToken {
Ok(merchant_account)
}
- pub async fn get_user(&self, state: AppState) -> UserResult<diesel_models::user::User> {
+ pub async fn get_user(&self, state: &AppState) -> UserResult<diesel_models::user::User> {
let user = state
.store
.find_user_by_id(&self.user_id)
@@ -146,3 +147,14 @@ pub fn get_multiple_merchant_details_with_status(
})
.collect()
}
+
+pub async fn get_user_from_db_by_email(
+ state: &AppState,
+ email: domain::UserEmail,
+) -> CustomResult<UserFromStorage, StorageError> {
+ state
+ .store
+ .find_user_by_email(email.get_secret().expose().as_str())
+ .await
+ .map(UserFromStorage::from)
+}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 462d3d01d79..9c7150c08da 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -2,11 +2,7 @@ use api_models::user_role as user_role_api;
use crate::{
consts,
- core::errors::{UserErrors, UserResult},
- services::authorization::{
- permissions::Permission,
- predefined_permissions::{self, RoleInfo},
- },
+ services::authorization::{permissions::Permission, predefined_permissions::RoleInfo},
};
pub fn is_internal_role(role_id: &str) -> bool {
@@ -14,13 +10,6 @@ pub fn is_internal_role(role_id: &str) -> bool {
|| role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER
}
-pub fn validate_role_id(role_id: &str) -> UserResult<()> {
- if predefined_permissions::is_role_invitable(role_id) {
- return Ok(());
- }
- Err(UserErrors::InvalidRoleId.into())
-}
-
pub fn get_role_name_and_permission_response(
role_info: &RoleInfo,
) -> Option<(Vec<user_role_api::Permission>, &'static str)> {
| 2024-02-01T14:05:34Z |
## Description
<!-- Describe your changes in detail -->
This PR changes update user role api and the list users api. And fixes a bug in list roles api.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 allow roles to be updated.
# | 014c2d5f555633bc04baca9b4a8c30b9c3534350 |
1. Update user role api
```
curl --location 'http://localhost:8080/user/user/update_role' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"email": "user_email",
"role_id": "merchant_admin"
}'
```
If api is success, it will respond with 200 OK.
2. List users api
```
curl --location 'http://localhost:8080/user/user/list' \
--header 'Authorization: Bearer JWT'
```
If api is success, response will be like this. Previously this response used to have `user_id` field, now it is removed.
```
[
{
"email": "email",
"name": "name",
"role_id": "merchant_iam_admin",
"role_name": "IAM",
"status": "InvitationSent",
"last_modified_at": "2024-01-22T11:16:42.283Z"
},
{
"email": "email",
"name": "name",
"role_id": "org_admin",
"role_name": "Organization Admin",
"status": "Active",
"last_modified_at": "2024-01-22T11:15:26.260Z"
},
]
```
3. List roles api
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT'
```
This api will no longer return org_admin role in the response and the response will be identical to this.
```
[
{
"role_id": "merchant_admin",
"permissions": [
"PaymentRead",
"PaymentWrite",
"RefundRead",
"RefundWrite",
"ApiKeyRead",
"ApiKeyWrite",
"MerchantAccountRead",
"MerchantAccountWrite",
"MerchantConnectorAccountRead",
"ForexRead",
"MerchantConnectorAccountWrite",
"RoutingRead",
"RoutingWrite",
"ThreeDsDecisionManagerWrite",
"ThreeDsDecisionManagerRead",
"SurchargeDecisionManagerWrite",
"SurchargeDecisionManagerRead",
"DisputeRead",
"DisputeWrite",
"MandateRead",
"MandateWrite",
"CustomerRead",
"CustomerWrite",
"FileRead",
"FileWrite",
"Analytics",
"UsersRead",
"UsersWrite"
],
"role_name": "Admin"
},
{
"role_id": "merchant_operator",
"permissions": [
"PaymentRead",
"PaymentWrite",
"RefundRead",
"RefundWrite",
"ApiKeyRead",
"MerchantAccountRead",
"ForexRead",
"MerchantConnectorAccountRead",
"MerchantConnectorAccountWrite",
"RoutingRead",
"RoutingWrite",
"ThreeDsDecisionManagerRead",
"ThreeDsDecisionManagerWrite",
"SurchargeDecisionManagerRead",
"SurchargeDecisionManagerWrite",
"DisputeRead",
"MandateRead",
"CustomerRead",
"FileRead",
"Analytics",
"UsersRead"
],
"role_name": "Operator"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"PaymentRead",
"RefundRead",
"RefundWrite",
"ForexRead",
"DisputeRead",
"DisputeWrite",
"MerchantAccountRead",
"MerchantConnectorAccountRead",
"MandateRead",
"CustomerRead",
"FileRead",
"FileWrite",
"Analytics"
],
"role_name": "Customer Support"
},
{
"role_id": "merchant_developer",
"permissions": [
"PaymentRead",
"RefundRead",
"ApiKeyRead",
"ApiKeyWrite",
"MerchantAccountRead",
"ForexRead",
"MerchantConnectorAccountRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"SurchargeDecisionManagerRead",
"DisputeRead",
"MandateRead",
"CustomerRead",
"FileRead",
"Analytics",
"UsersRead"
],
"role_name": "Developer"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"PaymentRead",
"RefundRead",
"ApiKeyRead",
"MerchantAccountRead",
"ForexRead",
"MerchantConnectorAccountRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"SurchargeDecisionManagerRead",
"DisputeRead",
"MandateRead",
"CustomerRead",
"FileRead",
"Analytics",
"UsersRead",
"UsersWrite"
],
"role_name": "IAM"
},
{
"role_id": "merchant_view_only",
"permissions": [
"PaymentRead",
"RefundRead",
"ApiKeyRead",
"MerchantAccountRead",
"ForexRead",
"MerchantConnectorAccountRead",
"RoutingRead",
"ThreeDsDecisionManagerRead",
"SurchargeDecisionManagerRead",
"DisputeRead",
"MandateRead",
"CustomerRead",
"FileRead",
"Analytics",
"UsersRead"
],
"role_name": "View Only"
}
]
```
| [
"crates/api_models/src/user.rs",
"crates/api_models/src/user_role.rs",
"crates/router/src/core/errors/user.rs",
"crates/router/src/core/errors/utils.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/services/authorization/predefined_permissions.rs",
"crat... | |
juspay/hyperswitch | juspay__hyperswitch-3520 | Bug: feat(logging-framework): Add a end log line to print the accumulated log values
Instead of relying on the exit & entry points of root spans,
we should add an explicit log entry at the end of root span | diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index 702c3c70e6c..9205f53a04b 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -141,9 +141,14 @@ where
let response_fut = self.service.call(req);
Box::pin(
- response_fut.instrument(
+ async move {
+ let response = response_fut.await;
+ logger::info!(golden_log_line = true);
+ response
+ }
+ .instrument(
router_env::tracing::info_span!(
- "golden_log_line",
+ "ROOT_SPAN",
payment_id = Empty,
merchant_id = Empty,
connector_name = Empty,
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 012030df6be..a20d2dd026b 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -147,7 +147,7 @@ pub async fn get_customer_mandates(
customer_id: path.into_inner(),
};
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -166,6 +166,6 @@ pub async fn get_customer_mandates(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index eafd61dcded..1203b766cbb 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -118,7 +118,7 @@ pub async fn retrieve_mandates_list(
) -> HttpResponse {
let flow = Flow::MandatesList;
let payload = payload.into_inner();
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -132,6 +132,6 @@ pub async fn retrieve_mandates_list(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
| 2024-02-01T13:06:05Z |
## Description
<!-- Describe your changes in detail -->
- Add an end request log line for logging keys
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Since we no longer log enter & exit spans we need an explicit log line to mark end of request
# | 54fb61eeebec503f599774fe9e97f6b6ce3f1458 |
make a health API call & check for the following log line
```json
{
"message": "[ROOT_SPAN - EVENT] router::middleware",
"hostname": "sampraslopes-SERIAL.local",
"pid": 78236,
"env": "development",
"level": "INFO",
"target": "router::middleware",
"service": "router",
"line": 146,
"file": "crates/router/src/middleware.rs",
"fn": "ROOT_SPAN",
"full_name": "router::middleware::ROOT_SPAN",
"time": "2024-02-01T11:54:29.607859000Z",
"flow": "UNKNOWN",
"request_id": "018d6485-3b65-7902-8983-fc57988d7e7a",
"extra": {
"golden_log_line": true,
"otel.kind": "server",
"http.scheme": "http",
"trace_id": "00000000000000000000000000000000",
"http.method": "GET",
"http.host": "localhost:8080",
"http.user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0",
"otel.name": "HTTP GET default",
"http.flavor": "1.1",
"http.route": "default",
"http.target": "/favicon.ico",
"http.client_ip": "127.0.0.1"
}
}
```
| [
"crates/router/src/middleware.rs",
"crates/router/src/routes/customers.rs",
"crates/router/src/routes/mandates.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3524 | Bug: Deep health check for outgoing request in scheduler
| diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
index e4611f43bcf..2c65c7b6d50 100644
--- a/crates/api_models/src/health_check.rs
+++ b/crates/api_models/src/health_check.rs
@@ -13,6 +13,7 @@ impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {}
pub struct SchedulerHealthCheckResponse {
pub database: bool,
pub redis: bool,
+ pub outgoing_request: bool,
}
impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 5f98cd88014..59a108ef5e6 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -187,11 +187,23 @@ pub async fn deep_health_check_func(
})
})?;
+ let outgoing_req_check = state
+ .health_check_outgoing()
+ .await
+ .map(|_| true)
+ .map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Outgoing Request",
+ message: err.to_string()
+ })
+ })?;
+
logger::debug!("Redis health check end");
let response = SchedulerHealthCheckResponse {
database: db_status,
redis: redis_status,
+ outgoing_request: outgoing_req_check,
};
Ok(response)
| 2024-02-01T12:37:02Z |
## Description
<!-- Describe your changes in detail -->
Closes #3524 . Add an outgoing request check for scheduler.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Added a check in scheduler for checking the outgoing requests
# | 54fb61eeebec503f599774fe9e97f6b6ce3f1458 |
- `curl --location 'http://localhost:3000/health/ready'`
- <img width="1305" alt="Screenshot 2024-02-01 at 6 06 36 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/5d1e1525-a408-484f-9749-6affbad3758c">
**This cannot be tested in sandbox as it's not exposed externally in sandbox**
| [
"crates/api_models/src/health_check.rs",
"crates/router/src/bin/scheduler.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3527 | Bug: [BUG] ListPaymentMethods For Merchant has an empty array of payment_methods_enabled
### Bug Description
While doing a, ListPaymentMethods For Merchant it has an empty array of payment_methods_enabled.
### Expected Behavior
ListPaymentMethods For Merchant should have the payment_methods that has been enabled for that merchant
### Actual Behavior
ListPaymentMethods For Merchant it has an empty array
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1.Create MA and MCA
2. while making payments do a confirm as false
3. List PaymentMethods For Merchants , the list would be empty for non-card transactions , also the payment_type would be new_mandate/setup_mandate
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index e08dbc61f5e..5797fd60da0 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1823,7 +1823,6 @@ pub async fn list_payment_methods(
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
- print!("PAMT{:?}", payment_attempt);
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: merchant_account.return_url,
@@ -2070,13 +2069,30 @@ pub async fn filter_payment_methods(
})?;
let filter7 = payment_attempt
.and_then(|attempt| attempt.mandate_details.as_ref())
- .map(|_mandate_details| {
- filter_pm_based_on_supported_payments_for_mandate(
- supported_payment_methods_for_mandate,
- &payment_method,
- &payment_method_object.payment_method_type,
- connector_variant,
- )
+ .map(|mandate_details| {
+ let (mandate_type_present, update_mandate_id_present) =
+ match mandate_details {
+ data_models::mandates::MandateTypeDetails::MandateType(_) => {
+ (true, false)
+ }
+ data_models::mandates::MandateTypeDetails::MandateDetails(
+ mand_details,
+ ) => (
+ mand_details.mandate_type.is_some(),
+ mand_details.update_mandate_id.is_some(),
+ ),
+ };
+
+ if mandate_type_present || update_mandate_id_present {
+ filter_pm_based_on_supported_payments_for_mandate(
+ supported_payment_methods_for_mandate,
+ &payment_method,
+ &payment_method_object.payment_method_type,
+ connector_variant,
+ )
+ } else {
+ true
+ }
})
.unwrap_or(true);
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 381f0265976..378cbb25467 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -712,7 +712,9 @@ impl PaymentCreate {
Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
}
- let mandate_dets = if let Some(update_id) = request
+ let mandate_details = if request.mandate_data.is_none() {
+ None
+ } else if let Some(update_id) = request
.mandate_data
.as_ref()
.and_then(|inner| inner.update_mandate_id.clone())
@@ -723,8 +725,6 @@ impl PaymentCreate {
};
Some(MandateTypeDetails::MandateDetails(mandate_data))
} else {
- // let mandate_type: data_models::mandates::MandateDataType =
-
let mandate_data = MandateDetails {
update_mandate_id: None,
mandate_type: request
@@ -761,7 +761,7 @@ impl PaymentCreate {
business_sub_label: request.business_sub_label.clone(),
surcharge_amount,
tax_amount,
- mandate_details: mandate_dets,
+ mandate_details,
..storage::PaymentAttemptNew::default()
},
additional_pm_data,
| 2024-02-01T12:34:32Z |
## Description
ListPaymentMethodsForMerchant was unable to list the payment methods enabled as it was always taking mandate to have Some value even though its respective fields were None. So added a check that, if there's mandate_data present then only any data should be stored in the database
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 54fb61eeebec503f599774fe9e97f6b6ce3f1458 | - Create MA and MCA
- Do a payment with confirm as false and then ListPaymentMethodsForMerchnats
> Earlier

> After fix

| [
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payments/operations/payment_create.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3522 | Bug: feat: resend user invite
Add support to resend invites to users. Currently we can invite the user or multiple users, but there is no support to invite the same user again.
The invitation mail will be send to user and user will be able to accept the invitation.
| diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 04aabc071ae..d7150af9bc7 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -12,8 +12,8 @@ use crate::user::{
},
AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,
DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest,
- InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse,
- SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
+ InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest,
+ SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest,
};
@@ -54,6 +54,7 @@ common_utils::impl_misc_api_event_type!(
ResetPasswordRequest,
InviteUserRequest,
InviteUserResponse,
+ ReInviteUserRequest,
VerifyEmailRequest,
SendVerifyEmailRequest,
SignInResponse,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 89f42f58c39..b29ce811be3 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -113,6 +113,11 @@ pub struct InviteMultipleUserResponse {
pub error: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct ReInviteUserRequest {
+ pub email: pii::Email,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchMerchantIdRequest {
pub merchant_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 7050c9f0024..41a407bd670 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -706,6 +706,63 @@ async fn handle_new_user_invitation(
})
}
+#[cfg(feature = "email")]
+pub async fn resend_invite(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+ request: user_api::ReInviteUserRequest,
+) -> UserResponse<()> {
+ let invitee_email = domain::UserEmail::from_pii_email(request.email)?;
+ let user: domain::UserFromStorage = state
+ .store
+ .find_user_by_email(invitee_email.clone().get_secret().expose().as_str())
+ .await
+ .map_err(|e| {
+ if e.current_context().is_db_not_found() {
+ e.change_context(UserErrors::InvalidRoleOperation)
+ .attach_printable("User not found in the records")
+ } else {
+ e.change_context(UserErrors::InternalServerError)
+ }
+ })?
+ .into();
+ let user_role = state
+ .store
+ .find_user_role_by_user_id_merchant_id(user.get_user_id(), &user_from_token.merchant_id)
+ .await
+ .map_err(|e| {
+ if e.current_context().is_db_not_found() {
+ e.change_context(UserErrors::InvalidRoleOperation)
+ .attach_printable("User role with given UserId MerchantId not found")
+ } else {
+ e.change_context(UserErrors::InternalServerError)
+ }
+ })?;
+
+ if !matches!(user_role.status, UserStatus::InvitationSent) {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Invalid Status for Reinvitation");
+ }
+
+ let email_contents = email_types::InviteUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(user.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id,
+ };
+ state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
pub async fn create_internal_user(
state: AppState,
request: user_api::CreateInternalUserRequest,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 9e8bee73c28..c130da8dbb4 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -976,41 +976,12 @@ impl User {
.service(web::resource("/switch/list").route(web::get().to(list_merchant_ids_for_user)))
.service(web::resource("/permission_info").route(web::get().to(get_authorization_info)))
.service(web::resource("/update").route(web::post().to(update_user_account_details)))
- .service(
- web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)),
- )
.service(
web::resource("/data")
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
- )
- .service(web::resource("/user/delete").route(web::delete().to(delete_user_role)));
-
- // User management
- route = route.service(
- web::scope("/user")
- .service(web::resource("/list").route(web::get().to(get_user_details)))
- .service(web::resource("/invite").route(web::post().to(invite_user)))
- .service(web::resource("/invite/accept").route(web::post().to(accept_invitation)))
- .service(web::resource("/update_role").route(web::post().to(update_user_role))),
- );
-
- // Role information
- route = route.service(
- web::scope("/role")
- .service(web::resource("").route(web::get().to(get_role_from_token)))
- .service(web::resource("/list").route(web::get().to(list_all_roles)))
- .service(web::resource("/{role_id}").route(web::get().to(get_role))),
- );
+ );
- #[cfg(feature = "dummy_connector")]
- {
- route = route.service(
- web::resource("/sample_data")
- .route(web::post().to(generate_sample_data))
- .route(web::delete().to(delete_sample_data)),
- )
- }
#[cfg(feature = "email")]
{
route = route
@@ -1031,12 +1002,43 @@ impl User {
.service(
web::resource("/verify_email_request")
.route(web::post().to(verify_email_request)),
- );
+ )
+ .service(web::resource("/user/resend_invite").route(web::post().to(resend_invite)));
}
#[cfg(not(feature = "email"))]
{
route = route.service(web::resource("/signup").route(web::post().to(user_signup)))
}
+
+ // User management
+ route = route.service(
+ web::scope("/user")
+ .service(web::resource("/list").route(web::get().to(get_user_details)))
+ .service(web::resource("/invite").route(web::post().to(invite_user)))
+ .service(
+ web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
+ )
+ .service(web::resource("/invite/accept").route(web::post().to(accept_invitation)))
+ .service(web::resource("/update_role").route(web::post().to(update_user_role)))
+ .service(web::resource("/delete").route(web::delete().to(delete_user_role))),
+ );
+
+ // Role information
+ route = route.service(
+ web::scope("/role")
+ .service(web::resource("").route(web::get().to(get_role_from_token)))
+ .service(web::resource("/list").route(web::get().to(list_all_roles)))
+ .service(web::resource("/{role_id}").route(web::get().to(get_role))),
+ );
+
+ #[cfg(feature = "dummy_connector")]
+ {
+ route = route.service(
+ web::resource("/sample_data")
+ .route(web::post().to(generate_sample_data))
+ .route(web::delete().to(delete_sample_data)),
+ )
+ }
route
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 0dfc3b1b339..042e89fdd52 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -182,6 +182,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ResetPassword
| Flow::InviteUser
| Flow::InviteMultipleUser
+ | Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmailWithoutInviteChecks
| Flow::VerifyEmail
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 0c2694dc70f..a863bc2b662 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -401,6 +401,25 @@ pub async fn invite_multiple_user(
.await
}
+#[cfg(feature = "email")]
+pub async fn resend_invite(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Json<user_api::ReInviteUserRequest>,
+) -> HttpResponse {
+ let flow = Flow::ReInviteUser;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ user_core::resend_invite,
+ &auth::JWTAuth(Permission::UsersWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "email")]
pub async fn verify_email_without_invite_checks(
state: web::Data<AppState>,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 55e7bafd8e0..11e6f9c0ed8 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -331,6 +331,8 @@ pub enum Flow {
InviteUser,
/// Invite multiple users
InviteMultipleUser,
+ /// Reinvite user
+ ReInviteUser,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
| 2024-02-01T12:20:14Z |
## Description
The new endpoint `/resend_invite`, add supports to send invitation to user again.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 54fb61eeebec503f599774fe9e97f6b6ce3f1458 | To invite user:
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "test_2@juspay.in",
"name": "test2",
"role_id": "merchant_admin"
}
'
```
For resend invite:
```
curl --location 'http://localhost:8080/user/user/resend_invite' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "test_2@juspay.in"
}'
```
<img width="1259" alt="Screenshot 2024-02-01 at 5 39 38 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/0fd7df5d-4db6-4e5f-ba6e-0635cbfe9e18">
| [
"crates/api_models/src/events/user.rs",
"crates/api_models/src/user.rs",
"crates/router/src/core/user.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/lock_utils.rs",
"crates/router/src/routes/user.rs",
"crates/router_env/src/logger/types.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3518 | Bug: Deep health check for outgoing request
| diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
index 8323f135134..c1ab2a2d757 100644
--- a/crates/api_models/src/health_check.rs
+++ b/crates/api_models/src/health_check.rs
@@ -5,6 +5,7 @@ pub struct RouterHealthCheckResponse {
pub locker: bool,
#[cfg(feature = "olap")]
pub analytics: bool,
+ pub outgoing_request: bool,
}
impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 12b688e3d3a..3c3f01dc5f9 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -91,3 +91,6 @@ pub const MAX_SESSION_EXPIRY: u32 = 7890000;
pub const MIN_SESSION_EXPIRY: u32 = 60;
pub const LOCKER_HEALTH_CALL_PATH: &str = "/health";
+
+// URL for checking the outgoing call
+pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck";
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index cbc4290f63b..9052893d4a9 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -186,6 +186,12 @@ pub enum ConnectorError {
InvalidConnectorConfig { config: &'static str },
}
+#[derive(Debug, thiserror::Error)]
+pub enum HealthCheckOutGoing {
+ #[error("Outgoing call failed with error: {message}")]
+ OutGoingFailed { message: String },
+}
+
#[derive(Debug, thiserror::Error)]
pub enum VaultError {
#[error("Failed to save card in card vault")]
diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs
index 6fc038b82e9..bc523b4fba6 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -4,7 +4,7 @@ use error_stack::ResultExt;
use router_env::logger;
use crate::{
- consts::LOCKER_HEALTH_CALL_PATH,
+ consts,
core::errors::{self, CustomResult},
routes::app,
services::api as services,
@@ -15,6 +15,7 @@ pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>;
async fn health_check_redis(&self) -> CustomResult<(), errors::HealthCheckRedisError>;
async fn health_check_locker(&self) -> CustomResult<(), errors::HealthCheckLockerError>;
+ async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing>;
#[cfg(feature = "olap")]
async fn health_check_analytics(&self) -> CustomResult<(), errors::HealthCheckDBError>;
}
@@ -61,7 +62,7 @@ impl HealthCheckInterface for app::AppState {
let locker = &self.conf.locker;
if !locker.mock_locker {
let mut url = locker.host_rs.to_owned();
- url.push_str(LOCKER_HEALTH_CALL_PATH);
+ url.push_str(consts::LOCKER_HEALTH_CALL_PATH);
let request = services::Request::new(services::Method::Get, &url);
services::call_connector_api(self, request)
.await
@@ -108,4 +109,22 @@ impl HealthCheckInterface for app::AppState {
}
}
}
+
+ async fn health_check_outgoing(&self) -> CustomResult<(), errors::HealthCheckOutGoing> {
+ let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL);
+ services::call_connector_api(self, request)
+ .await
+ .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
+ message: err.to_string(),
+ })?
+ .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
+ message: format!(
+ "Got a non 200 status while making outgoing request. Error {:?}",
+ err.response
+ ),
+ })?;
+
+ logger::debug!("Outgoing request successful");
+ Ok(())
+ }
}
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index 89132c3319b..2183ab07fed 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -94,6 +94,17 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
})
})?;
+ let outgoing_check = state
+ .health_check_outgoing()
+ .await
+ .map(|_| true)
+ .map_err(|err| {
+ error_stack::report!(errors::ApiErrorResponse::HealthCheckError {
+ component: "Outgoing Request",
+ message: err.to_string()
+ })
+ })?;
+
logger::debug!("Locker health check end");
let response = RouterHealthCheckResponse {
@@ -102,6 +113,7 @@ async fn deep_health_check_func(state: app::AppState) -> RouterResponse<RouterHe
locker: locker_status,
#[cfg(feature = "olap")]
analytics: analytics_status,
+ outgoing_request: outgoing_check,
};
Ok(api::ApplicationResponse::Json(response))
| 2024-02-01T06:29:21Z |
## Description
<!-- Describe your changes in detail -->
Closes #3518. Add healthcheck for outgoing calls
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Added a check for outgoing requests
# | 20efc3020ac389199eed13154f070685417ef82a |
- `curl --location 'http://localhost:8080/health/ready'`
<img width="907" alt="Screenshot 2024-02-01 at 11 58 57 AM" src="https://github.com/juspay/hyperswitch/assets/43412619/79ebea8f-4ab2-4d35-893d-60974f64b39f">
| [
"crates/api_models/src/health_check.rs",
"crates/router/src/consts.rs",
"crates/router/src/core/errors.rs",
"crates/router/src/core/health_check.rs",
"crates/router/src/routes/health.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3513 | Bug: [CHORE] Add file storage config in env_specific toml
### Feature Description
Add file storage config in env_specific.toml
### Possible Implementation
Add file storage config in env_specific.toml
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 354c320e8f5..04831376050 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -70,9 +70,13 @@ api_logs_topic = "topic" # Kafka topic to be used for incoming api
connector_logs_topic = "topic" # Kafka topic to be used for connector api events
outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events
-[file_upload_config]
-bucket_name = "bucket"
-region = "bucket_region"
+# File storage configuration
+[file_storage]
+file_storage_backend = "aws_s3" # File storage backend to be used
+
+[file_storage.aws_s3]
+region = "bucket_region" # The AWS region used by AWS S3 for file storage
+bucket_name = "bucket" # The AWS S3 bucket name for file storage
# This section provides configs for currency conversion api
[forex_api]
| 2024-01-31T16:03:36Z |
## Description
<!-- Describe your changes in detail -->
This PR adds file storage config in `env_specific.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).
-->
# | 7251f6474fdac3575202971e55638c435ca5c4c8 |
Cannot be tested as this is just a config addition
| [
"config/deployments/env_specific.toml"
] | |
juspay/hyperswitch | juspay__hyperswitch-3509 | Bug: [BUG] : Add noon applepay mandate configs
### Bug Description
Add noon Applepay mandate configs
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/config.example.toml b/config/config.example.toml
index f7e9fa70f6e..007c671e9e4 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -383,6 +383,7 @@ bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment
bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
+wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" }
# Required fields info used while listing the payment_method_data
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index b84546eff34..2c5d16e3e3c 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless"
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index d5479b4f02c..964281c52bb 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless"
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 14f49e01caf..aa2377cf8a0 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -114,7 +114,7 @@ bank_debit.sepa.connector_list = "gocardless"
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 67fca85929d..fba91dc1254 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -334,7 +334,7 @@ adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,hal
[mandates.supported_payment_methods]
pay_later.klarna = {connector_list = "adyen"}
wallet.google_pay = {connector_list = "stripe,adyen"}
-wallet.apple_pay = {connector_list = "stripe,adyen"}
+wallet.apple_pay = {connector_list = "stripe,adyen,cybersource,noon"}
wallet.paypal = {connector_list = "adyen"}
card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}
card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}
| 2024-01-31T13:46:33Z |
##Description
Add Applepay Mandate configs for noon in all environments.
## Test Case
Applepay should appear in the payment method list | 20efc3020ac389199eed13154f070685417ef82a | [
"config/config.example.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/docker_compose.toml"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3558 | Bug: feat(analytics): refunds and disputes audit rail
| diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs
index eb9b2d561c5..4be3a3420da 100644
--- a/crates/analytics/src/api_event/events.rs
+++ b/crates/analytics/src/api_event/events.rs
@@ -33,9 +33,30 @@ where
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
match query_param.query_param {
- QueryType::Payment { payment_id } => query_builder
- .add_filter_clause("payment_id", payment_id)
- .switch()?,
+ QueryType::Payment { payment_id } => {
+ query_builder
+ .add_filter_clause("payment_id", payment_id)
+ .switch()?;
+ query_builder
+ .add_filter_in_range_clause(
+ "api_flow",
+ &[
+ Flow::PaymentsCancel,
+ Flow::PaymentsCapture,
+ Flow::PaymentsConfirm,
+ Flow::PaymentsCreate,
+ Flow::PaymentsStart,
+ Flow::PaymentsUpdate,
+ Flow::RefundsCreate,
+ Flow::RefundsUpdate,
+ Flow::DisputesEvidenceSubmit,
+ Flow::AttachDisputeEvidence,
+ Flow::RetrieveDisputeEvidence,
+ Flow::IncomingWebhookReceive,
+ ],
+ )
+ .switch()?;
+ }
QueryType::Refund {
payment_id,
refund_id,
@@ -46,28 +67,31 @@ where
query_builder
.add_filter_clause("refund_id", refund_id)
.switch()?;
+ query_builder
+ .add_filter_in_range_clause("api_flow", &[Flow::RefundsCreate, Flow::RefundsUpdate])
+ .switch()?;
+ }
+ QueryType::Dispute {
+ payment_id,
+ dispute_id,
+ } => {
+ query_builder
+ .add_filter_clause("payment_id", payment_id)
+ .switch()?;
+ query_builder
+ .add_filter_clause("dispute_id", dispute_id)
+ .switch()?;
+ query_builder
+ .add_filter_in_range_clause(
+ "api_flow",
+ &[
+ Flow::DisputesEvidenceSubmit,
+ Flow::AttachDisputeEvidence,
+ Flow::RetrieveDisputeEvidence,
+ ],
+ )
+ .switch()?;
}
- }
- if let Some(list_api_name) = query_param.api_name_filter {
- query_builder
- .add_filter_in_range_clause("api_flow", &list_api_name)
- .switch()?;
- } else {
- query_builder
- .add_filter_in_range_clause(
- "api_flow",
- &[
- Flow::PaymentsCancel,
- Flow::PaymentsCapture,
- Flow::PaymentsConfirm,
- Flow::PaymentsCreate,
- Flow::PaymentsStart,
- Flow::PaymentsUpdate,
- Flow::RefundsCreate,
- Flow::IncomingWebhookReceive,
- ],
- )
- .switch()?;
}
//TODO!: update the execute_query function to return reports instead of plain errors...
query_builder
diff --git a/crates/api_models/src/analytics/api_event.rs b/crates/api_models/src/analytics/api_event.rs
index 62fe829f01b..5fe8e4ff3a7 100644
--- a/crates/api_models/src/analytics/api_event.rs
+++ b/crates/api_models/src/analytics/api_event.rs
@@ -8,7 +8,6 @@ use super::{NameDescription, TimeRange};
pub struct ApiLogsRequest {
#[serde(flatten)]
pub query_param: QueryType,
- pub api_name_filter: Option<Vec<String>>,
}
pub enum FilterType {
@@ -27,6 +26,10 @@ pub enum QueryType {
payment_id: String,
refund_id: String,
},
+ Dispute {
+ payment_id: String,
+ dispute_id: String,
+ },
}
#[derive(
| 2024-01-31T06:47:14Z |
## Description
<!-- Describe your changes in detail -->
added api_logs for refunds and disputes and same for connector_outgoing_events and webhook_events logs.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | fbe84b2a334cfb744ae4f27b1eadc892c7f9b164 |
to test api_events for refunds
```curl
curl --location '<base_url>/analytics/v1/api_event_logs?type=Refund&payment_id=<payment_id>&refund_id=<refund_id>' \
--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 '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/120.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer <token>"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"'`
<img width="1132" alt="Screenshot 2024-01-31 at 1 50 21 PM" src="https://github.com/juspay/hyperswitch/assets/126486299/318b9a07-d350-4741-8c78-8c1922e014db">
```
for disputes
```curl
curl --location '<base_url>/analytics/v1/api_event_logs?type=Dispute&dispute_id=<dispute_id>' \
--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 '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/120.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer <token>"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"'
```
| [
"crates/analytics/src/api_event/events.rs",
"crates/api_models/src/analytics/api_event.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3493 | Bug: [BUG] : Add iDEAL and Sofort mandate configs to env files
### Expected Behavior
payment method list includes iDeal and Sofort for a mandate payment
### Actual Behavior
payment method list don't include iDeal and Sofort for a mandate payment.
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index d377b3359c9..b84546eff34 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen"
wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
+bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
+bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index d4671d3a99d..d5479b4f02c 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen"
wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
+bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
+bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index abacd3ba5a1..c58eff29edb 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -117,6 +117,8 @@ pay_later.klarna.connector_list = "adyen"
wallet.apple_pay.connector_list = "stripe,adyen,cybersource"
wallet.google_pay.connector_list = "stripe,adyen,cybersource"
wallet.paypal.connector_list = "adyen"
+bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
+bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
| 2024-01-30T09:20:44Z | 87191d687cd66bf096bfb98ffe51a805b4b76a03 | [
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml"
] | |||
juspay/hyperswitch | juspay__hyperswitch-3494 | Bug: [FEATURE]: [Noon] Implement Revoke Mandate
### Feature Description
When revoke mandate api is triggered, revoke the existing connector mandate with noon also
### Possible Implementation
Implement Revoke Mandate for Noon
### 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/connector/noon.rs b/crates/router/src/connector/noon.rs
index 180b4b1485f..6c98a307637 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -46,6 +46,7 @@ impl api::Refund for Noon {}
impl api::RefundExecute for Noon {}
impl api::RefundSync for Noon {}
impl api::PaymentToken for Noon {}
+impl api::ConnectorMandateRevoke for Noon {}
impl
ConnectorIntegration<
@@ -492,6 +493,81 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
+impl
+ ConnectorIntegration<
+ api::MandateRevoke,
+ types::MandateRevokeRequestData,
+ types::MandateRevokeResponseData,
+ > for Noon
+{
+ fn get_headers(
+ &self,
+ req: &types::MandateRevokeRouterData,
+ 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::MandateRevokeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}payment/v1/order", self.base_url(connectors)))
+ }
+ fn build_request(
+ &self,
+ req: &types::MandateRevokeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::MandateRevokeType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::MandateRevokeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::MandateRevokeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+ fn get_request_body(
+ &self,
+ req: &types::MandateRevokeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = noon::NoonRevokeMandateRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::MandateRevokeRouterData,
+ res: Response,
+ ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> {
+ let response: noon::NoonRevokeMandateResponse = res
+ .response
+ .parse_struct("Noon NoonRevokeMandateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Noon {
fn get_headers(
&self,
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index bbf284848b5..ee06cd064be 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -5,7 +5,8 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{
- self as conn_utils, CardData, PaymentsAuthorizeRequestData, RouterData, WalletData,
+ self as conn_utils, CardData, PaymentsAuthorizeRequestData, RevokeMandateRequestData,
+ RouterData, WalletData,
},
core::errors,
services,
@@ -30,11 +31,13 @@ pub enum NoonSubscriptionType {
}
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct NoonSubscriptionData {
#[serde(rename = "type")]
subscription_type: NoonSubscriptionType,
//Short description about the subscription.
name: String,
+ max_amount: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -168,12 +171,13 @@ pub enum NoonPaymentData {
}
#[derive(Debug, Serialize)]
-#[serde(rename_all = "UPPERCASE")]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NoonApiOperations {
Initiate,
Capture,
Reverse,
Refund,
+ CancelSubscription,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -335,6 +339,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
NoonSubscriptionData {
subscription_type: NoonSubscriptionType::Unscheduled,
name: name.clone(),
+ max_amount: item
+ .request
+ .setup_mandate_details
+ .clone()
+ .and_then(|mandate_details| match mandate_details.mandate_type {
+ Some(data_models::mandates::MandateDataType::SingleUse(mandate))
+ | Some(data_models::mandates::MandateDataType::MultiUse(Some(
+ mandate,
+ ))) => Some(
+ conn_utils::to_currency_base_unit(mandate.amount, mandate.currency)
+ .ok(),
+ ),
+ _ => None,
+ })
+ .flatten(),
},
true,
)) {
@@ -450,7 +469,7 @@ impl ForeignFrom<(NoonPaymentStatus, Self)> for enums::AttemptStatus {
}
#[derive(Debug, Serialize, Deserialize)]
-pub struct NoonSubscriptionResponse {
+pub struct NoonSubscriptionObject {
identifier: String,
}
@@ -475,7 +494,7 @@ pub struct NoonCheckoutData {
pub struct NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse,
checkout_data: Option<NoonCheckoutData>,
- subscription: Option<NoonSubscriptionResponse>,
+ subscription: Option<NoonSubscriptionObject>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -603,6 +622,25 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest {
}
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NoonRevokeMandateRequest {
+ api_operation: NoonApiOperations,
+ subscription: NoonSubscriptionObject,
+}
+
+impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::MandateRevokeRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ api_operation: NoonApiOperations::CancelSubscription,
+ subscription: NoonSubscriptionObject {
+ identifier: item.request.get_connector_mandate_id()?,
+ },
+ })
+ }
+}
+
impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
@@ -624,6 +662,55 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest {
})
}
}
+#[derive(Debug, Deserialize)]
+pub enum NoonRevokeStatus {
+ Cancelled,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NoonCancelSubscriptionObject {
+ status: NoonRevokeStatus,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NoonRevokeMandateResult {
+ subscription: NoonCancelSubscriptionObject,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NoonRevokeMandateResponse {
+ result: NoonRevokeMandateResult,
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ NoonRevokeMandateResponse,
+ types::MandateRevokeRequestData,
+ types::MandateRevokeResponseData,
+ >,
+ > for types::RouterData<F, types::MandateRevokeRequestData, types::MandateRevokeResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ NoonRevokeMandateResponse,
+ types::MandateRevokeRequestData,
+ types::MandateRevokeResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response.result.subscription.status {
+ NoonRevokeStatus::Cancelled => Ok(Self {
+ response: Ok(types::MandateRevokeResponseData {
+ mandate_status: common_enums::MandateStatus::Revoked,
+ }),
+ ..item.data
+ }),
+ }
+ }
+}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index c9f9d6d87f5..ebc0cf3664a 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -2247,7 +2247,6 @@ default_imp_for_revoking_mandates!(
connector::Multisafepay,
connector::Nexinets,
connector::Nmi,
- connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
| 2024-01-30T07:57:22Z |
## Description
<!-- Describe your changes in detail -->
Implement revoke mandate flow for Noon
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
#3494
# | 937aea906e759e6e8a76a424db99ed052d46b7d2 |
- Create Mandate with the Noon
- Test Recurring Payment using mandate_id
- Revoke the mandate and check at connector if it is revoked or not.
<img width="928" alt="Screenshot 2024-01-30 at 12 40 51 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/365fd0a3-5992-44ec-a43f-ce2616ad40ba">
<img width="877" alt="Screenshot 2024-01-30 at 12 39 25 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/1170ecc7-0a7b-43ba-95d7-758cb92da3d4">
<img width="1029" alt="Screenshot 2024-01-30 at 12 39 15 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/75b40aea-c29a-41a7-be42-d72409a86f06">
<img width="884" alt="Screenshot 2024-01-30 at 5 12 52 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/386d12c1-3c69-4107-93d5-5b101a7ba4ff">
| [
"crates/router/src/connector/noon.rs",
"crates/router/src/connector/noon/transformers.rs",
"crates/router/src/core/payments/flows.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3490 | Bug: Send Email to biz@hyperswitch.io at every prod intent
| diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index c570aca7603..1cda969f780 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,2 +1,3 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
+pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index b537aa3ec73..24ff292870e 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -3,7 +3,11 @@ use diesel_models::{
enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata,
};
use error_stack::ResultExt;
+#[cfg(feature = "email")]
+use router_env::logger;
+#[cfg(feature = "email")]
+use crate::services::email::types as email_types;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::AppState,
@@ -434,15 +438,31 @@ async fn insert_metadata(
if utils::is_update_required(&metadata) {
metadata = utils::update_user_scoped_metadata(
state,
- user.user_id,
+ user.user_id.clone(),
user.merchant_id,
user.org_id,
metadata_key,
- data,
+ data.clone(),
)
.await
.change_context(UserErrors::InternalServerError);
}
+
+ #[cfg(feature = "email")]
+ {
+ if utils::is_prod_email_required(&data) {
+ let email_contents = email_types::BizEmailProd::new(state, data)?;
+ let send_email_result = state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await;
+ logger::info!(?send_email_result);
+ }
+ }
+
metadata
}
types::MetaData::SPTestPayment(data) => {
diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html
new file mode 100644
index 00000000000..c705608ec72
--- /dev/null
+++ b/crates/router/src/services/email/assets/bizemailprod.html
@@ -0,0 +1,138 @@
+<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
+<title>Welcome to HyperSwitch!</title>
+<body style="background-color: #ececec">
+ <div
+ id="wrapper"
+ style="
+ background-color: none;
+ margin: 0 auto;
+ text-align: center;
+ width: 90%;
+ -premailer-height: 200;
+ "
+ >
+ <table
+ align="center"
+ class="main-table"
+ style="
+ -premailer-cellpadding: 0;
+ -premailer-cellspacing: 0;
+ background-color: #fff;
+ border: 0;
+ border-top: 5px solid #0165ef;
+ margin: 0 auto;
+ mso-table-lspace: 0;
+ mso-table-rspace: 0;
+ padding: 0 40;
+ text-align: center;
+ width: 100%;
+ "
+ bgcolor="#ffffff"
+ cellpadding="0"
+ cellspacing="0"
+ >
+ <tr>
+ <td
+ class="spacer-sm"
+ style="
+ -premailer-height: 20;
+ -premailer-width: 80%;
+ line-height: 10px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-sm"
+ style="
+ -premailer-height: 20;
+ -premailer-width: 80%;
+ line-height: 10px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ width="100%"
+ ></td>
+ </tr>
+ <tr>
+ <td
+ class="copy"
+ style="
+ color: #666;
+ font-family: Roboto, Helvetica, Arial, san-serif;
+ font-size: 14px;
+ text-align: left;
+ line-height: 20px;
+ margin-top: 20px;
+ padding: 15px;
+ "
+ >
+ <br />
+ <p>Hi Team,</p>
+ <p>
+ A Production Account Intent has been initiated by {username} -
+ please find more details below:
+ </p>
+ <ol>
+ <li><strong>Name:</strong> {username}</li>
+ <li><strong>Point of Contact Email (POC):</strong> {poc_email}</li>
+ <li><strong>Legal Business Name:</strong> {legal_business_name}</li>
+ <li><strong>Business Location:</strong> {business_location}</li>
+ <li><strong>Business Website:</strong> {business_website}</li>
+ </ol>
+ <br />
+ </td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-sm"
+ style="
+ -premailer-height: 20;
+ -premailer-width: 80%;
+ line-height: 10px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ width="100%"
+ ></td>
+ </tr>
+
+ <tr>
+ <td
+ class="headline"
+ style="
+ color: #444;
+ font-family: Roboto, Helvetica, Arial, san-serif;
+ font-size: 18px;
+ font-weight: 100;
+ line-height: 36px;
+ margin: 0 auto;
+ padding: 0;
+ text-align: center;
+ "
+ align="center"
+ >
+ Regards,<br />
+ Hyperswitch Dashboard Team
+ </td>
+ </tr>
+ <tr>
+ <td
+ class="spacer-lg"
+ style="
+ -premailer-height: 75;
+ -premailer-width: 100%;
+ line-height: 30px;
+ margin: 0 auto;
+ padding: 0;
+ "
+ height="75"
+ width="100%"
+ ></td>
+ </tr>
+ </table>
+ </div>
+</body>
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index c68907c2846..6ad1a0eb99a 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -1,11 +1,16 @@
+use api_models::user::dashboard_metadata::ProdIntent;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use external_services::email::{EmailContents, EmailData, EmailError};
-use masking::{ExposeInterface, PeekInterface};
+use masking::{ExposeInterface, PeekInterface, Secret};
-use crate::{configs, consts};
+use crate::{configs, consts, routes::AppState};
#[cfg(feature = "olap")]
-use crate::{core::errors::UserErrors, services::jwt, types::domain};
+use crate::{
+ core::errors::{UserErrors, UserResult},
+ services::jwt,
+ types::domain,
+};
pub enum EmailBody {
Verify {
@@ -23,6 +28,13 @@ pub enum EmailBody {
link: String,
user_name: String,
},
+ BizEmailProd {
+ user_name: String,
+ poc_email: String,
+ legal_business_name: String,
+ business_location: String,
+ business_website: String,
+ },
ReconActivation {
user_name: String,
},
@@ -69,6 +81,22 @@ pub mod html {
username = user_name,
)
}
+ EmailBody::BizEmailProd {
+ user_name,
+ poc_email,
+ legal_business_name,
+ business_location,
+ business_website,
+ } => {
+ format!(
+ include_str!("assets/bizemailprod.html"),
+ poc_email = poc_email,
+ legal_business_name = legal_business_name,
+ business_location = business_location,
+ business_website = business_website,
+ username = user_name,
+ )
+ }
EmailBody::ProFeatureRequest {
feature_name,
merchant_id,
@@ -275,6 +303,56 @@ impl EmailData for ReconActivation {
}
}
+pub struct BizEmailProd {
+ pub recipient_email: domain::UserEmail,
+ pub user_name: Secret<String>,
+ pub poc_email: Secret<String>,
+ pub legal_business_name: String,
+ pub business_location: String,
+ pub business_website: String,
+ pub settings: std::sync::Arc<configs::settings::Settings>,
+ pub subject: &'static str,
+}
+
+impl BizEmailProd {
+ pub fn new(state: &AppState, data: ProdIntent) -> UserResult<Self> {
+ Ok(Self {
+ recipient_email: (domain::UserEmail::new(
+ consts::user::BUSINESS_EMAIL.to_string().into(),
+ ))?,
+ settings: state.conf.clone(),
+ subject: "New Prod Intent",
+ user_name: data.poc_name.unwrap_or_default().into(),
+ poc_email: data.poc_email.unwrap_or_default().into(),
+ legal_business_name: data.legal_business_name.unwrap_or_default(),
+ business_location: data
+ .business_location
+ .unwrap_or(common_enums::CountryAlpha2::AD)
+ .to_string(),
+ business_website: data.business_website.unwrap_or_default(),
+ })
+ }
+}
+
+#[async_trait::async_trait]
+impl EmailData for BizEmailProd {
+ async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
+ let body = html::get_html_body(EmailBody::BizEmailProd {
+ user_name: self.user_name.clone().expose(),
+ poc_email: self.poc_email.clone().expose(),
+ legal_business_name: self.legal_business_name.clone(),
+ business_location: self.business_location.clone(),
+ business_website: self.business_website.clone(),
+ });
+
+ Ok(EmailContents {
+ subject: self.subject.to_string(),
+ body: external_services::email::IntermediateString::new(body),
+ recipient: self.recipient_email.clone().into_inner(),
+ })
+ }
+}
+
pub struct ProFeatureRequest {
pub recipient_email: domain::UserEmail,
pub feature_name: String,
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index 09fb5ccd24b..bcf270010ea 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -2,7 +2,7 @@ use std::{net::IpAddr, str::FromStr};
use actix_web::http::header::HeaderMap;
use api_models::user::dashboard_metadata::{
- GetMetaDataRequest, GetMultipleMetaDataPayload, SetMetaDataRequest,
+ GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest,
};
use diesel_models::{
enums::DashboardMetadata as DBEnum,
@@ -276,3 +276,10 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay
.attach_printable("Error Parsing to DashboardMetadata enums")?,
})
}
+
+pub fn is_prod_email_required(data: &ProdIntent) -> bool {
+ !(data
+ .poc_email
+ .as_ref()
+ .map_or(true, |mail| mail.contains("juspay")))
+}
| 2024-01-29T15:48:48Z |
## Description
Sending an email to biz@hyperswitch.io whenever a new Prod Intent will be filled.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 regularly update the biz@hyperswitch.io regarding the Prod Intent.
# | 58771b8985a53c83185805f770fee26c5836c645 |
```
curl --location 'http://localhost:8080/user/data' \
--header 'api-key: hyperswitch' \
--header 'Content-Type: text/plain' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"ProdIntent": {
"poc_email": "---",
"is_completed": true,
"legal_business_name": "---",
"business_location": "AX",
"business_website": "---",
"poc_name": "---",
"comments": "---"
}
}'
```
When we hit this curl the email will be sent to biz@hyperswitch.io
| [
"crates/router/src/consts/user.rs",
"crates/router/src/core/user/dashboard_metadata.rs",
"crates/router/src/services/email/assets/bizemailprod.html",
"crates/router/src/services/email/types.rs",
"crates/router/src/utils/user/dashboard_metadata.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3480 | Bug: fix(invite): change status to active after resetting the password for invitee
| diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs
index b4d5976ba29..6fb5b79ddc1 100644
--- a/crates/diesel_models/src/query/user.rs
+++ b/crates/diesel_models/src/query/user.rs
@@ -3,7 +3,7 @@ use diesel::{
associations::HasTable, debug_query, result::Error as DieselError, ExpressionMethods,
JoinOnDsl, QueryDsl,
};
-use error_stack::{report, IntoReport};
+use error_stack::IntoReport;
use router_env::{
logger,
tracing::{self, instrument},
@@ -49,19 +49,37 @@ impl User {
pub async fn update_by_user_id(
conn: &PgPooledConn,
user_id: &str,
- user: UserUpdate,
+ user_update: UserUpdate,
) -> StorageResult<Self> {
- generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
conn,
users_dsl::user_id.eq(user_id.to_owned()),
- UserUpdateInternal::from(user),
+ UserUpdateInternal::from(user_update),
)
- .await?
- .first()
- .cloned()
- .ok_or_else(|| {
- report!(errors::DatabaseError::NotFound).attach_printable("Error while updating user")
- })
+ .await
+ }
+
+ pub async fn update_by_user_email(
+ conn: &PgPooledConn,
+ user_email: &str,
+ user_update: UserUpdate,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ users_dsl::email.eq(user_email.to_owned()),
+ UserUpdateInternal::from(user_update),
+ )
+ .await
}
pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index ae66728e140..4f50845c8d4 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,4 +1,6 @@
use api_models::user::{self as user_api, InviteMultipleUserResponse};
+#[cfg(feature = "email")]
+use diesel_models::user_role::UserRoleUpdate;
use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew};
#[cfg(feature = "email")]
use error_stack::IntoReport;
@@ -357,18 +359,10 @@ pub async fn reset_password(
let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
- //TODO: Create Update by email query
- let user_id = state
- .store
- .find_user_by_email(token.get_email())
- .await
- .change_context(UserErrors::InternalServerError)?
- .user_id;
-
- state
+ let user = state
.store
- .update_user_by_user_id(
- user_id.as_str(),
+ .update_user_by_email(
+ token.get_email(),
storage_user::UserUpdate::AccountUpdate {
name: None,
password: Some(hash_password),
@@ -379,7 +373,20 @@ pub async fn reset_password(
.await
.change_context(UserErrors::InternalServerError)?;
- //TODO: Update User role status for invited user
+ if let Some(inviter_merchant_id) = token.get_merchant_id() {
+ let update_status_result = state
+ .store
+ .update_user_role_by_user_id_merchant_id(
+ user.user_id.clone().as_str(),
+ inviter_merchant_id,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user.user_id,
+ },
+ )
+ .await;
+ logger::info!(?update_status_result);
+ }
Ok(ApplicationResponse::StatusOk)
}
@@ -462,7 +469,7 @@ pub async fn invite_user(
.store
.insert_user_role(UserRoleNew {
user_id: new_user.get_user_id().to_owned(),
- merchant_id: user_from_token.merchant_id,
+ merchant_id: user_from_token.merchant_id.clone(),
role_id: request.role_id,
org_id: user_from_token.org_id,
status: invitation_status,
@@ -488,6 +495,7 @@ pub async fn invite_user(
user_name: domain::UserName::new(new_user.get_name())?,
settings: state.conf.clone(),
subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id,
};
let send_email_result = state
.email_client
@@ -664,6 +672,7 @@ async fn handle_new_user_invitation(
user_name: domain::UserName::new(new_user.get_name())?,
settings: state.conf.clone(),
subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id.clone(),
};
let send_email_result = state
.email_client
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index e88d59ea9f3..67f4230d878 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1896,6 +1896,16 @@ impl UserInterface for KafkaStore {
.await
}
+ async fn update_user_by_email(
+ &self,
+ user_email: &str,
+ user: storage::UserUpdate,
+ ) -> CustomResult<storage::User, errors::StorageError> {
+ self.diesel_store
+ .update_user_by_email(user_email, user)
+ .await
+ }
+
async fn delete_user_by_user_id(
&self,
user_id: &str,
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index ecd71f7e2c9..c7c005a0b52 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -33,6 +33,12 @@ pub trait UserInterface {
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError>;
+ async fn update_user_by_email(
+ &self,
+ user_email: &str,
+ user: storage::UserUpdate,
+ ) -> CustomResult<storage::User, errors::StorageError>;
+
async fn delete_user_by_user_id(
&self,
user_id: &str,
@@ -92,6 +98,18 @@ impl UserInterface for Store {
.into_report()
}
+ async fn update_user_by_email(
+ &self,
+ user_email: &str,
+ user: storage::UserUpdate,
+ ) -> CustomResult<storage::User, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::User::update_by_user_email(&conn, user_email, user)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn delete_user_by_user_id(
&self,
user_id: &str,
@@ -229,6 +247,50 @@ impl UserInterface for MockDb {
)
}
+ async fn update_user_by_email(
+ &self,
+ user_email: &str,
+ update_user: storage::UserUpdate,
+ ) -> CustomResult<storage::User, errors::StorageError> {
+ let mut users = self.users.lock().await;
+ let user_email_pii: common_utils::pii::Email = user_email
+ .to_string()
+ .try_into()
+ .map_err(|_| errors::StorageError::MockDbError)?;
+ users
+ .iter_mut()
+ .find(|user| user.email == user_email_pii)
+ .map(|user| {
+ *user = match &update_user {
+ storage::UserUpdate::VerifyUser => storage::User {
+ is_verified: true,
+ ..user.to_owned()
+ },
+ storage::UserUpdate::AccountUpdate {
+ name,
+ password,
+ is_verified,
+ preferred_merchant_id,
+ } => storage::User {
+ name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
+ password: password.clone().unwrap_or(user.password.clone()),
+ is_verified: is_verified.unwrap_or(user.is_verified),
+ preferred_merchant_id: preferred_merchant_id
+ .clone()
+ .or(user.preferred_merchant_id.clone()),
+ ..user.to_owned()
+ },
+ };
+ user.to_owned()
+ })
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No user available for user_email = {user_email}"
+ ))
+ .into(),
+ )
+ }
+
async fn delete_user_by_user_id(
&self,
user_id: &str,
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index d5aa9926130..c68907c2846 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -92,18 +92,21 @@ Email : {user_email}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct EmailToken {
email: String,
+ merchant_id: Option<String>,
exp: u64,
}
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
+ merchant_id: Option<String>,
settings: &configs::settings::Settings,
) -> CustomResult<String, UserErrors> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
+ merchant_id,
exp,
};
jwt::generate_jwt(&token_payload, settings).await
@@ -112,6 +115,10 @@ impl EmailToken {
pub fn get_email(&self) -> &str {
self.email.as_str()
}
+
+ pub fn get_merchant_id(&self) -> Option<&str> {
+ self.merchant_id.as_deref()
+ }
}
pub fn get_link_with_token(
@@ -132,7 +139,7 @@ pub struct VerifyEmail {
#[async_trait::async_trait]
impl EmailData for VerifyEmail {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings)
+ let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
.await
.change_context(EmailError::TokenGenerationFailure)?;
@@ -161,7 +168,7 @@ pub struct ResetPassword {
#[async_trait::async_trait]
impl EmailData for ResetPassword {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings)
+ let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
.await
.change_context(EmailError::TokenGenerationFailure)?;
@@ -191,7 +198,7 @@ pub struct MagicLink {
#[async_trait::async_trait]
impl EmailData for MagicLink {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings)
+ let token = EmailToken::new_token(self.recipient_email.clone(), None, &self.settings)
.await
.change_context(EmailError::TokenGenerationFailure)?;
@@ -216,14 +223,19 @@ pub struct InviteUser {
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::settings::Settings>,
pub subject: &'static str,
+ pub merchant_id: String,
}
#[async_trait::async_trait]
impl EmailData for InviteUser {
async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> {
- let token = EmailToken::new_token(self.recipient_email.clone(), &self.settings)
- .await
- .change_context(EmailError::TokenGenerationFailure)?;
+ let token = EmailToken::new_token(
+ self.recipient_email.clone(),
+ Some(self.merchant_id.clone()),
+ &self.settings,
+ )
+ .await
+ .change_context(EmailError::TokenGenerationFailure)?;
let invite_user_link =
get_link_with_token(&self.settings.email.base_url, token, "set_password");
| 2024-01-29T12:53:52Z |
## Description
<!-- Describe your changes in detail -->
This PR will add an optional `merchant_id` field in `EmailToken` struct. And also changes the status of the user from `invitation_sent` to `active` if the `EmailToken` has `merchant_id`.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 change the status of the user to active once the user resets the password.
# | dfb14a34c96ba05e7ff1993fdcd97ee294c02d65 |
Postman.
1. Invite a user using this curl
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '{
"email": "new email",
"name": "user name",
"role_id": "merchant_admin"
}'
```
You should get invite email to the email you have provided and this following response from the api.
```
{
"is_email_sent": true,
"password": null
}
```
2. Use the link in the email to hit the reset password api from the dashboard or the following curl can be used to hit the api if email token is extracted.
```
curl --location 'http://localhost:8080/user/reset_password' \
--header 'Content-Type: application/json' \
--data-raw '{
"token": "Email Token",
"password": "new password"
}'
```
You will get 200 OK and the status of the `user_role` with the corresponding `user_id` and `merchant_id` will be active.
| [
"crates/diesel_models/src/query/user.rs",
"crates/router/src/core/user.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user.rs",
"crates/router/src/services/email/types.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3491 | Bug: feat(logging): add flow field to logging framework
Add API Flow field to the root span & persistent keys | diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index 587a15693f2..702c3c70e6c 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -58,7 +58,7 @@ where
let request_id = request_id_fut.await?;
let request_id = request_id.as_hyphenated().to_string();
if let Some(upstream_request_id) = old_x_request_id {
- router_env::logger::info!(?request_id, ?upstream_request_id);
+ router_env::logger::info!(?upstream_request_id);
}
let mut response = response_fut.await?;
response.headers_mut().append(
@@ -146,7 +146,8 @@ where
"golden_log_line",
payment_id = Empty,
merchant_id = Empty,
- connector_name = Empty
+ connector_name = Empty,
+ flow = "UNKNOWN"
)
.or_current(),
),
diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs
index 961a77c65aa..036a73cf874 100644
--- a/crates/router_env/src/logger/storage.rs
+++ b/crates/router_env/src/logger/storage.rs
@@ -92,7 +92,7 @@ impl Visit for Storage<'_> {
}
}
-const PERSISTENT_KEYS: [&str; 3] = ["payment_id", "connector_name", "merchant_id"];
+const PERSISTENT_KEYS: [&str; 4] = ["payment_id", "connector_name", "merchant_id", "flow"];
impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S>
for StorageSubscription
| 2024-01-29T11:50:23Z |
## Description
<!-- Describe your changes in detail -->
- Adding flow to the persistent keys in subscriber layer
- Adding flow to the middle ware log
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Adding flow to the persistent keys in api's
# | a9638d118e0b68653fef3bec2ce8aa3c47feedd3 |
run the application locally
all api requests should have the following log line at the end of request
- the fields should be populated when available
- These log line will be generated even for health & non-existent paths (e.g `/` or `/favicon.ico`)
```json
{
"message": "[GOLDEN_LOG_LINE - EVENT] REQUEST MIDDLEWARE END",
"hostname": "<MY_MACHINE>.local",
"pid": 62901,
"env": "development",
"level": "INFO",
"target": "router::middleware",
"service": "router",
"line": 61,
"file": "crates/router/src/middleware.rs",
"fn": "golden_log_line",
"full_name": "router::middleware::golden_log_line",
"flow": "PaymentsCreate",
"time": "2024-01-24T06:35:06.771569000Z",
"merchant_id": "merchant_1706060159",
"request_id": "018d3a2d-e583-7581-8992-8596b3052995",
"extra": {
"trace_id": "00000000000000000000000000000000",
"http.method": "POST",
"http.route": "/payments",
"http.flavor": "1.1",
"http.user_agent": "PostmanRuntime/7.33.0",
"payment_id": "payment_intent_id = \"pay_y8XHx5whOaWTdoGrgAAf\"",
"otel.name": "HTTP POST /payments",
"http.client_ip": "::1",
"http.host": "localhost:8080",
"http.target": "/payments",
"http.scheme": "http",
"otel.kind": "server"
}
}
```
| [
"crates/router/src/middleware.rs",
"crates/router_env/src/logger/storage.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3468 | Bug: feat: blacklist user
Setup user blacklisting. | diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 3f0febcc592..325ca980243 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -21,7 +21,7 @@ pub mod routes {
routes::AppState,
services::{
api,
- authentication::{self as auth, AuthToken, AuthenticationData},
+ authentication::{self as auth, AuthenticationData},
authorization::permissions::Permission,
ApplicationResponse,
},
@@ -378,23 +378,13 @@ pub mod routes {
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
- let state_ref = &state;
- let req_headers = &req.headers();
-
let flow = AnalyticsFlow::GenerateRefundReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
- |state, auth: AuthenticationData, payload| async move {
- let jwt_payload =
- auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await;
-
- let user_id = jwt_payload
- .change_context(AnalyticsError::UnknownError)?
- .user_id;
-
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move {
let user = UserInterface::find_user_by_id(&*state.store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
@@ -430,23 +420,13 @@ pub mod routes {
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
- let state_ref = &state;
- let req_headers = &req.headers();
-
let flow = AnalyticsFlow::GenerateDisputeReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
- |state, auth: AuthenticationData, payload| async move {
- let jwt_payload =
- auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await;
-
- let user_id = jwt_payload
- .change_context(AnalyticsError::UnknownError)?
- .user_id;
-
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move {
let user = UserInterface::find_user_by_id(&*state.store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
@@ -482,23 +462,13 @@ pub mod routes {
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
- let state_ref = &state;
- let req_headers = &req.headers();
-
let flow = AnalyticsFlow::GeneratePaymentReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
- |state, auth: AuthenticationData, payload| async move {
- let jwt_payload =
- auth::parse_jwt_payload::<AppState, AuthToken>(req_headers, state_ref).await;
-
- let user_id = jwt_payload
- .change_context(AnalyticsError::UnknownError)?
- .user_id;
-
+ |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload| async move {
let user = UserInterface::find_user_by_id(&*state.store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 387da3c0641..12b688e3d3a 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -66,12 +66,16 @@ pub const ROUTING_CONFIG_ID_LENGTH: usize = 10;
pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN";
pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
-#[cfg(any(feature = "olap", feature = "oltp"))]
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
+pub const USER_BLACKLIST_PREFIX: &str = "BU_";
+
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
+#[cfg(feature = "email")]
+pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_";
+
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index ae66728e140..24b6eb9d127 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -264,6 +264,11 @@ pub async fn connect_account(
}
}
+pub async fn signout(state: AppState, user_from_token: auth::UserFromToken) -> UserResponse<()> {
+ auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
+ Ok(ApplicationResponse::StatusOk)
+}
+
pub async fn change_password(
state: AppState,
request: user_api::ChangePasswordRequest,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 4a726084c2c..a69220231f5 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -965,6 +965,7 @@ impl User {
web::resource("/signin").route(web::post().to(user_signin_without_invite_checks)),
)
.service(web::resource("/v2/signin").route(web::post().to(user_signin)))
+ .service(web::resource("/signout").route(web::post().to(signout)))
.service(web::resource("/change_password").route(web::post().to(change_password)))
.service(web::resource("/internal_signup").route(web::post().to(internal_user_signup)))
.service(web::resource("/switch_merchant").route(web::post().to(switch_merchant_id)))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 4cd85efe8d5..a5362162dbc 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -164,6 +164,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UserSignUp
| Flow::UserSignInWithoutInviteChecks
| Flow::UserSignIn
+ | Flow::Signout
| Flow::ChangePassword
| Flow::SetDashboardMetadata
| Flow::GetMutltipleDashboardMetadata
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 88e19ddf755..48721afff59 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -116,6 +116,20 @@ pub async fn user_connect_account(
.await
}
+pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
+ let flow = Flow::Signout;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &http_req,
+ (),
+ |state, user, _| user_core::signout(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn change_password(
state: web::Data<AppState>,
http_req: HttpRequest,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 7f1e078ad53..221106612f3 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -36,6 +36,7 @@ use crate::{
types::domain,
utils::OptionExt,
};
+pub mod blacklist;
#[derive(Clone, Debug)]
pub struct AuthenticationData {
@@ -333,6 +334,9 @@ where
state: &A,
) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
Ok((
UserWithoutMerchantFromToken {
@@ -495,6 +499,9 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
let permissions = authorization::get_permissions(&payload.role_id)?;
authorization::check_authorization(&self.0, permissions)?;
@@ -521,6 +528,9 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
let permissions = authorization::get_permissions(&payload.role_id)?;
authorization::check_authorization(&self.0, permissions)?;
@@ -556,6 +566,9 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
let permissions = authorization::get_permissions(&payload.role_id)?;
authorization::check_authorization(&self.required_permission, permissions)?;
@@ -585,12 +598,6 @@ where
Ok(payload)
}
-#[derive(serde::Deserialize)]
-struct JwtAuthPayloadFetchMerchantAccount {
- merchant_id: String,
- role_id: String,
-}
-
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth
where
@@ -601,9 +608,10 @@ where
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
- let payload =
- parse_jwt_payload::<A, JwtAuthPayloadFetchMerchantAccount>(request_headers, state)
- .await?;
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
let permissions = authorization::get_permissions(&payload.role_id)?;
authorization::check_authorization(&self.0, permissions)?;
@@ -638,6 +646,56 @@ where
}
}
+pub type AuthenticationDataWithUserId = (AuthenticationData, String);
+
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationDataWithUserId, A> for JWTAuth
+where
+ A: AppStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let permissions = authorization::get_permissions(&payload.role_id)?;
+ authorization::check_authorization(&self.0, permissions)?;
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ &payload.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
+
+ let auth = AuthenticationData {
+ merchant_account: merchant,
+ key_store,
+ };
+ Ok((
+ (auth.clone(), payload.user_id.clone()),
+ AuthenticationType::MerchantJwt {
+ merchant_id: auth.merchant_account.merchant_id.clone(),
+ user_id: None,
+ },
+ ))
+ }
+}
+
pub struct DashboardNoPermissionAuth;
#[cfg(feature = "olap")]
@@ -652,6 +710,9 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
Ok((
UserFromToken {
@@ -679,7 +740,10 @@ where
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
- parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
Ok(((), AuthenticationType::NoAuth))
}
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
new file mode 100644
index 00000000000..6fab28433b4
--- /dev/null
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -0,0 +1,63 @@
+use std::sync::Arc;
+
+#[cfg(feature = "olap")]
+use common_utils::date_time;
+use error_stack::{IntoReport, ResultExt};
+use redis_interface::RedisConnectionPool;
+
+use crate::{
+ consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX},
+ core::errors::{ApiErrorResponse, RouterResult},
+ routes::app::AppStateInfo,
+};
+#[cfg(feature = "olap")]
+use crate::{
+ core::errors::{UserErrors, UserResult},
+ routes::AppState,
+};
+
+#[cfg(feature = "olap")]
+pub async fn insert_user_in_blacklist(state: &AppState, user_id: &str) -> UserResult<()> {
+ let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
+ let expiry =
+ expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
+ let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
+ redis_conn
+ .set_key_with_expiry(
+ user_blacklist_key.as_str(),
+ date_time::now_unix_timestamp(),
+ expiry,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
+pub async fn check_user_in_blacklist<A: AppStateInfo>(
+ state: &A,
+ user_id: &str,
+ token_expiry: u64,
+) -> RouterResult<bool> {
+ let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
+ let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
+ let redis_conn = get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<i64>>(token.as_str())
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
+}
+
+fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
+ state
+ .store()
+ .get_redis_conn()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")
+}
+
+fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
+ expiry
+ .try_into()
+ .into_report()
+ .change_context(ApiErrorResponse::InternalServerError)
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index ac2dfb47c63..c78455ffbe6 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -285,6 +285,8 @@ pub enum Flow {
FrmFulfillment,
/// Change password flow
ChangePassword,
+ /// Signout flow
+ Signout,
/// Set Dashboard Metadata flow
SetDashboardMetadata,
/// Get Multiple Dashboard Metadata flow
| 2024-01-29T10:37:22Z |
## Description
Added blacklist for users.
<!-- Describe your changes in detail -->
## Motivation and Context
Invalidate the token after logout.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | d2accdef410319733d6174057bdca468bde1ae83 | Use the below api to logout.
```
curl --location --request POST '<URL>/user/signout' \
--header 'Authorization: Bearer JWT'
```
When you use the same token as above to test any other api then response will be `401`.
| [
"crates/router/src/analytics.rs",
"crates/router/src/consts.rs",
"crates/router/src/core/user.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/lock_utils.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/services/authentication.rs",
"crates/router/src/services/authentication... | |
juspay/hyperswitch | juspay__hyperswitch-3484 | Bug: fix: Change permissions for sample data
Change permission for Sample data to `PaymentWrite` instead of `MerchantAccountWrite` | diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 4cd85efe8d5..2837c1defa4 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -179,7 +179,6 @@ impl From<Flow> for ApiIdentifier {
| Flow::ResetPassword
| Flow::InviteUser
| Flow::InviteMultipleUser
- | Flow::DeleteUser
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmailWithoutInviteChecks
| Flow::VerifyEmail
@@ -191,7 +190,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::GetRoleFromToken
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
- | Flow::AcceptInvitation => Self::UserRole,
+ | Flow::AcceptInvitation
+ | Flow::DeleteUserRole => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 88e19ddf755..d4bdcaae87f 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -257,7 +257,7 @@ pub async fn generate_sample_data(
&http_req,
payload.into_inner(),
sample_data::generate_sample_data_for_user,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth(Permission::PaymentWrite),
api_locking::LockAction::NotApplicable,
))
.await
@@ -277,7 +277,7 @@ pub async fn delete_sample_data(
&http_req,
payload.into_inner(),
sample_data::delete_sample_data_for_user,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth(Permission::PaymentWrite),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 3f9ccda8651..ec05db1d615 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -121,7 +121,7 @@ pub async fn delete_user_role(
req: HttpRequest,
payload: web::Json<user_role_api::DeleteUserRoleRequest>,
) -> HttpResponse {
- let flow = Flow::DeleteUser;
+ let flow = Flow::DeleteUserRole;
Box::pin(api::server_wrap(
flow,
state.clone(),
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index ac2dfb47c63..8e32cb63334 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -327,8 +327,8 @@ pub enum Flow {
InviteUser,
/// Invite multiple users
InviteMultipleUser,
- /// Delete user
- DeleteUser,
+ /// Delete user role
+ DeleteUserRole,
/// Incremental Authorization flow
PaymentsIncrementalAuthorization,
/// Get action URL for connector onboarding
| 2024-01-25T14:36:39Z |
## Description
- Change permission for sample data generate and delete. Currently it is Merchants write but is as per new use case it should be Payment Write only.
- Change the flow name for delete user (it is delete user role as per functionality)
## Motivation and Context
Permission for sample data needs to be changed.
# | d2accdef410319733d6174057bdca468bde1ae83 | Tested locally
- singup
- generate sample data
- delete sample data
Curl to generate and delete sample data:
```
curl --location 'http://localhost:8080/user/sample_data' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
```
curl --location --request DELETE 'http://localhost:8080/user/sample_data' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
Response should be 200 Ok for both the cases.
| [
"crates/router/src/routes/lock_utils.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/routes/user_role.rs",
"crates/router_env/src/logger/types.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3443 | Bug: [REFACTOR] Inclusion of kill switch in `configs` table
## Description
This refactor will ensure to be presence of a kill switch(merchant-wise) for Blocklist Feature.
We will always check for a Boolean entry in `configs` table i.e `guard_blocklist_for_{merchant_id}` and all the blocklist flows(validation & fingerprint generation) will only run if the variable is set to be true.
Else if the data is not present it will take it false(as default) and blocklist flows will be disabled.
## Testing steps
### For testing when the blocklist flows are disabled(That are by default) :
```
1. Create a payment
2. Confirm it
After a successful confirm the `fingerprint` entry in the response should be null.
```
### For testing when the blocklist flows are enabled :
```
1. Set/Create the entry `guard_blocklist_for_{merchant_id}` in configs table and set it to true.
```
After this all further testing steps can be followed from the parent [issue](https://github.com/juspay/hyperswitch/issues/3344) | diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index c81145c5de7..eba32ca0a53 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -719,156 +719,175 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let m_db = state.clone().store;
// Validate Blocklist
+ let mut fingerprint_id = None;
+ let mut is_pm_blocklisted = false;
let merchant_id = payment_data.payment_attempt.merchant_id;
- let merchant_fingerprint_secret =
- blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?;
-
- // Hashed Fingerprint to check whether or not this payment should be blocked.
- let card_number_fingerprint = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_card_no().as_bytes(),
- )
- .attach_printable("error in pm fingerprint creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
- }
- _ => None,
- })
- .map(hex::encode);
+ let blocklist_enabled_key = format!("guard_blocklist_for_{merchant_id}");
+ let blocklist_guard_enabled = state
+ .store
+ .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
+ .await;
- // Hashed Cardbin to check whether or not this payment should be blocked.
- let card_bin_fingerprint = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_card_isin().as_bytes(),
- )
- .attach_printable("error in card bin hash creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
- }
- _ => None,
- })
- .map(hex::encode);
+ let blocklist_guard_enabled: bool = match blocklist_guard_enabled {
+ Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),
- // Hashed Extended Cardbin to check whether or not this payment should be blocked.
- let extended_card_bin_fingerprint = payment_data
- .payment_method_data
- .as_ref()
- .and_then(|pm_data| match pm_data {
- api_models::payments::PaymentMethodData::Card(card) => {
- crypto::HmacSha512::sign_message(
- &crypto::HmacSha512,
- merchant_fingerprint_secret.as_bytes(),
- card.card_number.clone().get_extended_card_bin().as_bytes(),
- )
- .attach_printable("error in extended card bin hash creation")
- .map_or_else(
- |err| {
- logger::error!(error=?err);
- None
- },
- Some,
- )
+ // If it is not present in db we are defaulting it to false
+ Err(inner) => {
+ if !inner.current_context().is_db_not_found() {
+ logger::error!("Error fetching guard blocklist enabled config {:?}", inner);
}
- _ => None,
- })
- .map(hex::encode);
-
- let mut fingerprint_id = None;
-
- //validating the payment method.
- let mut is_pm_blocklisted = false;
+ false
+ }
+ };
- let mut blocklist_futures = Vec::new();
- if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
- &merchant_id,
- card_number_fingerprint,
- ));
- }
+ if blocklist_guard_enabled {
+ let merchant_fingerprint_secret =
+ blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?;
+ // Hashed Fingerprint to check whether or not this payment should be blocked.
+ let card_number_fingerprint = payment_data
+ .payment_method_data
+ .as_ref()
+ .and_then(|pm_data| match pm_data {
+ api_models::payments::PaymentMethodData::Card(card) => {
+ crypto::HmacSha512::sign_message(
+ &crypto::HmacSha512,
+ merchant_fingerprint_secret.as_bytes(),
+ card.card_number.clone().get_card_no().as_bytes(),
+ )
+ .attach_printable("error in pm fingerprint creation")
+ .map_or_else(
+ |err| {
+ logger::error!(error=?err);
+ None
+ },
+ Some,
+ )
+ }
+ _ => None,
+ })
+ .map(hex::encode);
+
+ // Hashed Cardbin to check whether or not this payment should be blocked.
+ let card_bin_fingerprint = payment_data
+ .payment_method_data
+ .as_ref()
+ .and_then(|pm_data| match pm_data {
+ api_models::payments::PaymentMethodData::Card(card) => {
+ crypto::HmacSha512::sign_message(
+ &crypto::HmacSha512,
+ merchant_fingerprint_secret.as_bytes(),
+ card.card_number.clone().get_card_isin().as_bytes(),
+ )
+ .attach_printable("error in card bin hash creation")
+ .map_or_else(
+ |err| {
+ logger::error!(error=?err);
+ None
+ },
+ Some,
+ )
+ }
+ _ => None,
+ })
+ .map(hex::encode);
+
+ // Hashed Extended Cardbin to check whether or not this payment should be blocked.
+ let extended_card_bin_fingerprint = payment_data
+ .payment_method_data
+ .as_ref()
+ .and_then(|pm_data| match pm_data {
+ api_models::payments::PaymentMethodData::Card(card) => {
+ crypto::HmacSha512::sign_message(
+ &crypto::HmacSha512,
+ merchant_fingerprint_secret.as_bytes(),
+ card.card_number.clone().get_extended_card_bin().as_bytes(),
+ )
+ .attach_printable("error in extended card bin hash creation")
+ .map_or_else(
+ |err| {
+ logger::error!(error=?err);
+ None
+ },
+ Some,
+ )
+ }
+ _ => None,
+ })
+ .map(hex::encode);
+
+ //validating the payment method.
+ let mut blocklist_futures = Vec::new();
+ if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {
+ blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
+ &merchant_id,
+ card_number_fingerprint,
+ ));
+ }
- if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
- &merchant_id,
- card_bin_fingerprint,
- ));
- }
+ if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {
+ blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
+ &merchant_id,
+ card_bin_fingerprint,
+ ));
+ }
- if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {
- blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
- &merchant_id,
- extended_card_bin_fingerprint,
- ));
- }
+ if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {
+ blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint(
+ &merchant_id,
+ extended_card_bin_fingerprint,
+ ));
+ }
- let blocklist_lookups = futures::future::join_all(blocklist_futures).await;
+ let blocklist_lookups = futures::future::join_all(blocklist_futures).await;
- if blocklist_lookups.iter().any(|x| x.is_ok()) {
- intent_status = storage_enums::IntentStatus::Failed;
- attempt_status = storage_enums::AttemptStatus::Failure;
- is_pm_blocklisted = true;
- }
+ if blocklist_lookups.iter().any(|x| x.is_ok()) {
+ intent_status = storage_enums::IntentStatus::Failed;
+ attempt_status = storage_enums::AttemptStatus::Failure;
+ is_pm_blocklisted = true;
+ }
- if let Some(encoded_hash) = card_number_fingerprint {
- #[cfg(feature = "kms")]
- let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms)
- .await
- .encrypt(encoded_hash)
- .await
- .map_or_else(
- |e| {
- logger::error!(error=?e, "failed kms encryption of card fingerprint");
- None
- },
- Some,
- );
-
- #[cfg(not(feature = "kms"))]
- let encrypted_fingerprint = Some(encoded_hash);
-
- if let Some(encrypted_fingerprint) = encrypted_fingerprint {
- fingerprint_id = db
- .insert_blocklist_fingerprint_entry(
- diesel_models::blocklist_fingerprint::BlocklistFingerprintNew {
- merchant_id,
- fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"),
- encrypted_fingerprint,
- data_kind: common_enums::BlocklistDataKind::PaymentMethod,
- created_at: common_utils::date_time::now(),
- },
- )
+ if let Some(encoded_hash) = card_number_fingerprint {
+ #[cfg(feature = "kms")]
+ let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms)
+ .await
+ .encrypt(encoded_hash)
.await
.map_or_else(
|e| {
- logger::error!(error=?e, "failed storing card fingerprint in db");
+ logger::error!(error=?e, "failed kms encryption of card fingerprint");
None
},
- |fp| Some(fp.fingerprint_id),
+ Some,
);
+
+ #[cfg(not(feature = "kms"))]
+ let encrypted_fingerprint = Some(encoded_hash);
+
+ if let Some(encrypted_fingerprint) = encrypted_fingerprint {
+ fingerprint_id = db
+ .insert_blocklist_fingerprint_entry(
+ diesel_models::blocklist_fingerprint::BlocklistFingerprintNew {
+ merchant_id,
+ fingerprint_id: utils::generate_id(
+ consts::ID_LENGTH,
+ "fingerprint",
+ ),
+ encrypted_fingerprint,
+ data_kind: common_enums::BlocklistDataKind::PaymentMethod,
+ created_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_or_else(
+ |e| {
+ logger::error!(error=?e, "failed storing card fingerprint in db");
+ None
+ },
+ |fp| Some(fp.fingerprint_id),
+ );
+ }
}
}
-
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
| 2024-01-25T10:04:30Z |
## Description
<!-- Describe your changes in detail -->
This will allow us to enable and disable the blocklist feature based on each merchant's requirements.
The steps to test out this feature can be found in the mentioned issue.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 61439533594f93287f15aaffb5d65ed12e77e7ec | [
"crates/router/src/core/payments/operations/payment_confirm.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-3457 | Bug: [BUG] [HELCIM] 5XX Error Happening If Wrong Api Key Is Passed
### Bug Description
If wrong `api_key` is passed during `Payment Connector - Create` for connector Helcim then the server throws 5XX error when you create a payment.
### Expected Behavior
The connector should handle the error thrown during `Payments - Create` if wrong `api_key` is passed during `Payment Connector - Create`
### Actual Behavior
The connector throws 5XX Error during `Payments - Create` if wrong `api_key` is passed during `Payment Connector - Create`
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
If wrong `api_key` is passed during `Payment Connector - Create` for connector Helcim then the server throws 5XX error when you create a payment.
### Environment
SANDBOX
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/connector/helcim.rs b/crates/router/src/connector/helcim.rs
index c3a6c5e9f50..0b2cac5d766 100644
--- a/crates/router/src/connector/helcim.rs
+++ b/crates/router/src/connector/helcim.rs
@@ -128,9 +128,12 @@ impl ConnectorCommon for Helcim {
.response
.parse_struct("HelcimErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- let error_string = match response.errors {
- transformers::HelcimErrorTypes::StringType(error) => error,
- transformers::HelcimErrorTypes::JsonType(error) => error.to_string(),
+ let error_string = match response {
+ transformers::HelcimErrorResponse::Payment(response) => match response.errors {
+ transformers::HelcimErrorTypes::StringType(error) => error,
+ transformers::HelcimErrorTypes::JsonType(error) => error.to_string(),
+ },
+ transformers::HelcimErrorResponse::General(error_string) => error_string,
};
Ok(ErrorResponse {
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs
index 599054163c3..5e076be651f 100644
--- a/crates/router/src/connector/helcim/transformers.rs
+++ b/crates/router/src/connector/helcim/transformers.rs
@@ -756,6 +756,13 @@ pub enum HelcimErrorTypes {
}
#[derive(Debug, Deserialize)]
-pub struct HelcimErrorResponse {
+pub struct HelcimPaymentsErrorResponse {
pub errors: HelcimErrorTypes,
}
+
+#[derive(Debug, Deserialize)]
+#[serde(untagged)]
+pub enum HelcimErrorResponse {
+ Payment(HelcimPaymentsErrorResponse),
+ General(String),
+}
| 2024-01-25T09:51:47Z |
## Description
<!-- Describe your changes in detail -->
Earlier if wrong api_key is passed during Payment Connector - Create for connector Helcim then the server throws 5XX error when you create a payment.
The connector will now handle the error thrown during Payments - Create if wrong api_key is passed during Payment Connector - Create.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/3457
# | c2946cfe05ffa81a66643e04eff5e89b545d2d43 |
1. Testing can be done by creating a payment with wrong api credentials. You should get the following error.

```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 210,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"setup_future_usage": "on_session",
"payment_method_data": {
"card": {
"card_number": "5413330089099130",
"card_exp_month": "01",
"card_exp_year": "27",
"card_cvc": "123",
"card_holder_name": "John Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"zip": "94122",
"first_name": "John",
"last_name": "Doe"
}
},
"customer_id": "chethan"
}'
```
2. Testing for other error case like missing field error should also be done. You will get the following error:

```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 210,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"setup_future_usage": "on_session",
"payment_method_data": {
"card": {
"card_number": "5413330089099130",
"card_exp_month": "01",
"card_exp_year": "27",
"card_cvc": "123",
"card_holder_name": "John Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"billing": {
"address": {
"line1": "",
"zip": "94122",
"first_name": "John",
"last_name": "Doe"
}
},
"customer_id": "chethan"
}'
```
| [
"crates/router/src/connector/helcim.rs",
"crates/router/src/connector/helcim/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-3454 | Bug: fix(connector): fix connector template script
In Recent changes, get_request_body return type was changed and connector template script was not modified .This pr fixes the connector template script.
<img width="824" alt="Screenshot 2024-01-25 at 1 12 36 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/cf11184f-edd8-4c66-a6f3-8f40e2f7ddc7">
| diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index 6258d437076..c64ce431968 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -167,10 +167,8 @@ impl
req.request.amount,
req,
))?;
- let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?;
- let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::encode_to_string_of_json)
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- Ok(Some({{project-name | downcase}}_req))
+ let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -385,10 +383,8 @@ impl
req.request.refund_amount,
req,
))?;
- let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?;
- let {{project-name | downcase}}_req = types::RequestBody::log_and_get_request_body(&req_obj, utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest>::encode_to_string_of_json)
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- Ok(Some({{project-name | downcase}}_req))
+ let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::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> {
| 2024-01-25T07:18:33Z |
## Description
<!-- Describe your changes in detail -->
In Recent changes, `get_request_body` return type was changed and connector template script was not modified .This pr fixes the connector template script.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
In Recent changes of `get_request_body` return type was changed and connector template script was not modified .This pr fixes the connector template script.
# | b45e4ca2a3788823701bdeac2e2a8c1147bb071a |
run `sh scripts/add_connector.sh example [<connector-base-url>](https://www.google.com/)` on oss branch and it should compile with no errors.
<img width="1138" alt="Screenshot 2024-01-25 at 12 32 22 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/d4e75efc-5967-4b0f-8bc0-0f3bac0b955b">
| [
"connector-template/mod.rs"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.