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-2248 | Bug: [FEATURE]: [Tsys] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs
index 869aa535636..e7e818062e2 100644
--- a/crates/router/src/connector/tsys.rs
+++ b/crates/router/src/connector/tsys.rs
@@ -71,6 +71,10 @@ impl ConnectorCommon for Tsys {
"tsys"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -227,7 +231,16 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
&self,
req: &types::PaymentsSyncRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = tsys::TsysSyncRequest::try_from(req)?;
+
+ let connector_router_data = tsys::TsysRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+
+ let req_obj = tsys::TsysPaymentsRequest::try_from(&connector_router_data)?;
+
let tsys_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<tsys::TsysSyncRequest>::encode_to_string_of_json,
@@ -461,7 +474,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = tsys::TsysRefundRequest::try_from(req)?;
+ let connector_router_data = tsys::TsysRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let req_obj = tsys::TsysRefundRequest::try_from(&connector_router_data)?;
let tsys_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<tsys::TsysRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index a3bd1c4a074..857e5c06460 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -17,7 +17,37 @@ pub enum TsysPaymentsRequest {
Sale(TsysPaymentAuthSaleRequest),
}
-#[derive(Default, Debug, Serialize)]
+#[derive(Debug, Serialize)]
+pub struct TsysRouterData<T> {
+ pub amount: String,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for TsysRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (currency_unit, currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[serde(rename_all = "camelCase")]
pub struct TsysPaymentAuthSaleRequest {
#[serde(rename = "deviceID")]
@@ -37,9 +67,11 @@ pub struct TsysPaymentAuthSaleRequest {
order_number: String,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
+impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &TsysRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(ccard) => {
let connector_auth: TsysAuthType =
@@ -459,9 +491,9 @@ pub struct TsysRefundRequest {
return_request: TsysReturnRequest,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for TsysRefundRequest {
+impl<F> TryFrom<&TsysRouterData::RefundsRouterData<F>> for TsysRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &TsysRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let return_request = TsysReturnRequest {
device_id: connector_auth.device_id,
| 2023-10-31T16:54:55Z |
## Description
<!-- Describe your changes in detail -->
- This PR is related with #2248 which implements `get_currency_unit` fn. , `TsysRouterData<T>` struct and functionality
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 8e484ddab8d3f4463299c7f7e8ce75b8dd628599 |
Got to test it by paying using Tsys and test the currency unit.
| [
"crates/router/src/connector/tsys.rs",
"crates/router/src/connector/tsys/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2322 | Bug: [FEATURE]: [Airwallex] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index e38999d495b..d3824e9d0da 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -569,12 +569,12 @@ impl<F, T>
status,
reference_id: Some(item.response.id.clone()),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charge_id: None,
}),
@@ -612,12 +612,12 @@ impl
status,
reference_id: Some(item.response.id.clone()),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charge_id: None,
}),
| 2023-10-31T14:25:53Z |
## Description
The `connector_response_reference_id` parameter has been set for the Airwallex Payment Solutions for uniform reference and transaction tracking.
### File Changes
- [x] This PR modifies the Airwallex Transformers file.
**Location- router/src/connector/airwallex/transformers.rs**
## Motivation and Context
This PR was raised so that it Fixes #2322 !
# | 2798f575605cc4439166344e57ff19b612f1304a | - **I ran the following command, and all the errors were addressed properly, and the build was successful.**
```bash
cargo clippy --all-features
```

- The code changes were formatted with the following command to fix styling issues.
```bash
cargo +nightly fmt
```
| [
"crates/router/src/connector/airwallex/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2220 | Bug: [FEATURE]: [BitPay] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs
index 2dc634426f3..e8826e93390 100644
--- a/crates/router/src/connector/bitpay.rs
+++ b/crates/router/src/connector/bitpay.rs
@@ -82,6 +82,10 @@ impl ConnectorCommon for Bitpay {
"bitpay"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -169,7 +173,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?;
+ let connector_router_data = bitpay::BitpayRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = bitpay::BitpayPaymentsRequest::try_from(&connector_router_data)?;
let bitpay_req = types::RequestBody::log_and_get_request_body(
&req_obj,
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index f99729da16d..c5c20608a75 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -9,6 +9,37 @@ use crate::{
types::{self, api, storage::enums, ConnectorAuthType},
};
+#[derive(Debug, Serialize)]
+pub struct BitpayRouterData<T> {
+ pub amount: i64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for BitpayRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionSpeed {
@@ -31,9 +62,11 @@ pub struct BitpayPaymentsRequest {
token: Secret<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest {
+impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
@@ -152,11 +185,13 @@ pub struct BitpayRefundRequest {
pub amount: i64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BitpayRefundRequest {
+impl<F> TryFrom<&BitpayRouterData<&types::RefundsRouterData<F>>> for BitpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &BitpayRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.refund_amount,
+ amount: item.router_data.request.refund_amount,
})
}
}
@@ -232,14 +267,14 @@ pub struct BitpayErrorResponse {
}
fn get_crypto_specific_payment_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let price = item.request.amount;
- let currency = item.request.currency.to_string();
- let redirect_url = item.request.get_return_url()?;
- let notification_url = item.request.get_webhook_url()?;
+ let price = item.amount;
+ let currency = item.router_data.request.currency.to_string();
+ let redirect_url = item.router_data.request.get_return_url()?;
+ let notification_url = item.router_data.request.get_webhook_url()?;
let transaction_speed = TransactionSpeed::Medium;
- let auth_type = item.connector_auth_type.clone();
+ let auth_type = item.router_data.connector_auth_type.clone();
let token = match auth_type {
ConnectorAuthType::HeaderKey { api_key } => api_key,
_ => String::default().into(),
| 2023-10-30T14:53:06Z |
## 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).
-->
Fixes #2220
# | 0a44f5699ed7b0c0ea0352b67c65df496ebe61f3 |
We need to create a payment using bitpay and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/bitpay.rs",
"crates/router/src/connector/bitpay/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2306 | Bug: [FEATURE]: [NMI] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 3f64ff9eaca..582bb9f7367 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -49,6 +49,7 @@ pub struct NmiPaymentsRequest {
currency: enums::Currency,
#[serde(flatten)]
payment_method: PaymentMethod,
+ orderid: String,
}
#[derive(Debug, Serialize)]
@@ -94,6 +95,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest {
amount,
currency: item.request.currency,
payment_method,
+ orderid: item.connector_request_reference_id.clone(),
})
}
}
@@ -206,6 +208,7 @@ impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest {
amount: 0.0,
currency: item.request.currency,
payment_method,
+ orderid: item.connector_request_reference_id.clone(),
})
}
}
| 2023-10-30T02:40:45Z | Add orderid with value of connector_request_reference_id in NMI transformers.
Fixes #2306
## 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).
-->
# | 8125ea19912f6d6446412d13842e35545cc1a484 |
Make any Payment for connector NMI and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/nmi/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2351 | Bug: [FEATURE]: [Worldline] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index f11c2398080..8d18723f9ed 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -565,12 +565,12 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData
item.response.capture_method,
)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
}),
..item.data
})
@@ -616,12 +616,14 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp
item.response.payment.capture_method,
)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.payment.id.clone(),
+ ),
redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.payment.id),
}),
..item.data
})
| 2023-10-29T15:30:07Z |
## Description
<!-- Describe your changes in detail -->
https://github.com/juspay/hyperswitch/issues/2351
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 8125ea19912f6d6446412d13842e35545cc1a484 |
Make any Payment for connector Worldline and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be null.
| [
"crates/router/src/connector/worldline/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2282 | Bug: [REFACTOR]: [Payme] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 4ced1a9bcda..1b7ce27439b 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -651,7 +651,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
language: LANGUAGE.to_string(),
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("payme"),
+ ))?,
}
}
}
| 2023-10-29T12:15:07Z |
## Description
This PR removes the default case handling and adds error handling for all the available cases.
Fixes #2282
# | 4afe552563c6a0cb9544a9a2f870bb9d07d7cf18 | No test cases. As In this PR only error message have been populated for all default cases.
| [
"crates/router/src/connector/payme/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2225 | Bug: [FEATURE]: [Fiserv] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs
index 70f58ffe6eb..35d40f1a3fb 100644
--- a/crates/router/src/connector/fiserv.rs
+++ b/crates/router/src/connector/fiserv.rs
@@ -104,6 +104,10 @@ impl ConnectorCommon for Fiserv {
"fiserv"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -400,7 +404,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = fiserv::FiservCaptureRequest::try_from(req)?;
+ let router_obj = fiserv::FiservRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let connector_request = fiserv::FiservCaptureRequest::try_from(&router_obj)?;
let fiserv_payments_capture_request = types::RequestBody::log_and_get_request_body(
&connector_request,
utils::Encode::<fiserv::FiservCaptureRequest>::encode_to_string_of_json,
@@ -505,7 +515,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = fiserv::FiservPaymentsRequest::try_from(req)?;
+ let router_obj = fiserv::FiservRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_request = fiserv::FiservPaymentsRequest::try_from(&router_obj)?;
let fiserv_payments_request = types::RequestBody::log_and_get_request_body(
&connector_request,
utils::Encode::<fiserv::FiservPaymentsRequest>::encode_to_string_of_json,
@@ -592,7 +608,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = fiserv::FiservRefundRequest::try_from(req)?;
+ let router_obj = fiserv::FiservRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_request = fiserv::FiservRefundRequest::try_from(&router_obj)?;
let fiserv_refund_request = types::RequestBody::log_and_get_request_body(
&connector_request,
utils::Encode::<fiserv::FiservRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index ae8eed0af31..2d07da7f47a 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -9,6 +9,38 @@ use crate::{
types::{self, api, storage::enums},
};
+#[derive(Debug, Serialize)]
+pub struct FiservRouterData<T> {
+ pub amount: String,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for FiservRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (currency_unit, currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FiservPaymentsRequest {
@@ -99,23 +131,25 @@ pub enum TransactionInteractionPosConditionCode {
CardNotPresentEcom,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest {
+impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
+ fn try_from(
+ item: &FiservRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let amount = Amount {
- total: utils::to_currency_base_unit(item.request.amount, item.request.currency)?,
- currency: item.request.currency.to_string(),
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency.to_string(),
};
let transaction_details = TransactionDetails {
capture_flag: Some(matches!(
- item.request.capture_method,
+ item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
reversal_reason_code: None,
- merchant_transaction_id: item.connector_request_reference_id.clone(),
+ merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
};
- let metadata = item.get_connector_meta()?;
+ let metadata = item.router_data.get_connector_meta()?;
let session: SessionObject = metadata
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
@@ -133,7 +167,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest {
//card not present in online transaction
pos_condition_code: TransactionInteractionPosConditionCode::CardNotPresentEcom,
};
- let source = match item.request.payment_method_data.clone() {
+ let source = match item.router_data.request.payment_method_data.clone() {
api::PaymentMethodData::Card(ref ccard) => {
let card = CardData {
card_data: ccard.card_number.clone(),
@@ -389,35 +423,40 @@ pub struct SessionObject {
pub terminal_id: String,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for FiservCaptureRequest {
+impl TryFrom<&FiservRouterData<&types::PaymentsCaptureRouterData>> for FiservCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
- let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
+ fn try_from(
+ item: &FiservRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
+ .router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let session: SessionObject = metadata
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
- let amount =
- utils::to_currency_base_unit(item.request.amount_to_capture, item.request.currency)?;
Ok(Self {
amount: Amount {
- total: amount,
- currency: item.request.currency.to_string(),
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency.to_string(),
},
transaction_details: TransactionDetails {
capture_flag: Some(true),
reversal_reason_code: None,
- merchant_transaction_id: item.connector_request_reference_id.clone(),
+ merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
- reference_transaction_id: item.request.connector_transaction_id.to_string(),
+ reference_transaction_id: item
+ .router_data
+ .request
+ .connector_transaction_id
+ .to_string(),
},
})
}
@@ -477,11 +516,14 @@ pub struct FiservRefundRequest {
reference_transaction_details: ReferenceTransactionDetails,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for FiservRefundRequest {
+impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let auth: FiservAuthType = FiservAuthType::try_from(&item.connector_auth_type)?;
+ fn try_from(
+ item: &FiservRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?;
let metadata = item
+ .router_data
.connector_meta_data
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
@@ -490,18 +532,19 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for FiservRefundRequest {
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
amount: Amount {
- total: utils::to_currency_base_unit(
- item.request.refund_amount,
- item.request.currency,
- )?,
- currency: item.request.currency.to_string(),
+ total: item.amount.clone(),
+ currency: item.router_data.request.currency.to_string(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
terminal_id: Some(session.terminal_id),
},
reference_transaction_details: ReferenceTransactionDetails {
- reference_transaction_id: item.request.connector_transaction_id.to_string(),
+ reference_transaction_id: item
+ .router_data
+ .request
+ .connector_transaction_id
+ .to_string(),
},
})
}
| 2023-10-28T02:46:57Z |
## Description
- Addressing Issue: #2225
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `fiserv.rs`
- Implement `get_currency_unit` function
- Modify `ConnectorIntegration` implementations for `Fiserv`
- `fiserv/transformers.rs`
- Implement `FiservRouterData<T>` structure and functionality
- Modify implementation for `FiservPaymentsRequest` and `FiservRefundRequest`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 53b8fefbc2f8b58d1be7e9f35ca8b7e44e327bfb |
We need to create a payment using Fiserv and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/fiserv.rs",
"crates/router/src/connector/fiserv/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2281 | Bug: [REFACTOR]: [Payeezy] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 98e8ea12c00..efcd1b36d5b 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -37,11 +37,14 @@ impl TryFrom<utils::CardIssuer> for PayeezyCardType {
utils::CardIssuer::Master => Ok(Self::Mastercard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
- _ => Err(errors::ConnectorError::NotSupported {
- message: issuer.to_string(),
- connector: "Payeezy",
+
+ utils::CardIssuer::Maestro | utils::CardIssuer::DinersClub | utils::CardIssuer::JCB => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Payeezy",
+ }
+ .into())
}
- .into()),
}
}
}
@@ -97,7 +100,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest {
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.payment_method {
diesel_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item),
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+
+ diesel_models::enums::PaymentMethod::CardRedirect
+ | diesel_models::enums::PaymentMethod::PayLater
+ | diesel_models::enums::PaymentMethod::Wallet
+ | diesel_models::enums::PaymentMethod::BankRedirect
+ | diesel_models::enums::PaymentMethod::BankTransfer
+ | diesel_models::enums::PaymentMethod::Crypto
+ | diesel_models::enums::PaymentMethod::BankDebit
+ | diesel_models::enums::PaymentMethod::Reward
+ | diesel_models::enums::PaymentMethod::Upi
+ | diesel_models::enums::PaymentMethod::Voucher
+ | diesel_models::enums::PaymentMethod::GiftCard => {
+ Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
+ }
}
}
}
@@ -165,7 +181,10 @@ fn get_transaction_type_and_stored_creds(
Some(diesel_models::enums::CaptureMethod::Automatic) => {
Ok((PayeezyTransactionType::Purchase, None))
}
- _ => Err(errors::ConnectorError::FlowNotSupported {
+
+ Some(diesel_models::enums::CaptureMethod::ManualMultiple)
+ | Some(diesel_models::enums::CaptureMethod::Scheduled)
+ | None => Err(errors::ConnectorError::FlowNotSupported {
flow: item.request.capture_method.unwrap_or_default().to_string(),
connector: "Payeezy".to_string(),
}),
@@ -196,7 +215,23 @@ fn get_payment_method_data(
};
Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card))
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Payeezy",
+ }
+ .into()),
}
}
@@ -383,7 +418,7 @@ impl ForeignFrom<(PayeezyPaymentStatus, PayeezyTransactionType)> for enums::Atte
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => Self::Charged,
PayeezyTransactionType::Void => Self::Voided,
- _ => Self::Pending,
+ PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending,
},
PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
PayeezyTransactionType::Capture => Self::CaptureFailed,
@@ -391,7 +426,7 @@ impl ForeignFrom<(PayeezyPaymentStatus, PayeezyTransactionType)> for enums::Atte
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => Self::AuthorizationFailed,
PayeezyTransactionType::Void => Self::VoidFailed,
- _ => Self::Pending,
+ PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending,
},
}
}
| 2023-10-27T14:47:44Z |
## Description
<!-- Describe your changes in detail -->
- Fix issue #2281
- Changes to be made : Remove default case handling
- File changed: ```transformers.rs``` (crates/router/src/connector/payeezy/transformers.rs)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | ca77c7ce3c6b806ff60e83725cc4e50855422037 |
No test cases. As In this PR only error message have been populated for all default cases.
| [
"crates/router/src/connector/payeezy/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2246 | Bug: [FEATURE]: [Stax] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs
index 82a4c7ff323..7f5fde71938 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/router/src/connector/stax.rs
@@ -70,6 +70,10 @@ impl ConnectorCommon for Stax {
"stax"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -347,7 +351,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = stax::StaxPaymentsRequest::try_from(req)?;
+ let connector_router_data = stax::StaxRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = stax::StaxPaymentsRequest::try_from(&connector_router_data)?;
let stax_req = types::RequestBody::log_and_get_request_body(
&req_obj,
@@ -503,7 +513,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = stax::StaxCaptureRequest::try_from(req)?;
+ let connector_router_data = stax::StaxRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let connector_req = stax::StaxCaptureRequest::try_from(&connector_router_data)?;
let stax_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<stax::StaxCaptureRequest>::encode_to_string_of_json,
@@ -657,7 +673,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = stax::StaxRefundRequest::try_from(req)?;
+ let connector_router_data = stax::StaxRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let req_obj = stax::StaxRefundRequest::try_from(&connector_router_data)?;
let stax_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<stax::StaxRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 4ee28be1937..f2aae442ddd 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -11,6 +11,37 @@ use crate::{
types::{self, api, storage::enums},
};
+#[derive(Debug, Serialize)]
+pub struct StaxRouterData<T> {
+ pub amount: f64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for StaxRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (currency_unit, currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Debug, Serialize)]
pub struct StaxPaymentsRequestMetaData {
tax: i64,
@@ -26,21 +57,23 @@ pub struct StaxPaymentsRequest {
idempotency_id: Option<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
+impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- if item.request.currency != enums::Currency::USD {
+ fn try_from(
+ item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ if item.router_data.request.currency != enums::Currency::USD {
Err(errors::ConnectorError::NotSupported {
- message: item.request.currency.to_string(),
+ message: item.router_data.request.currency.to_string(),
connector: "Stax",
})?
}
- let total = utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
+ let total = item.amount;
- match item.request.payment_method_data.clone() {
+ match item.router_data.request.payment_method_data.clone() {
api::PaymentMethodData::Card(_) => {
- let pm_token = item.get_payment_method_token()?;
- let pre_auth = !item.request.is_auto_capture()?;
+ let pm_token = item.router_data.get_payment_method_token()?;
+ let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
meta: StaxPaymentsRequestMetaData { tax: 0 },
total,
@@ -52,14 +85,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
- idempotency_id: Some(item.connector_request_reference_id.clone()),
+ idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(
api_models::payments::BankDebitData::AchBankDebit { .. },
) => {
- let pm_token = item.get_payment_method_token()?;
- let pre_auth = !item.request.is_auto_capture()?;
+ let pm_token = item.router_data.get_payment_method_token()?;
+ let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
meta: StaxPaymentsRequestMetaData { tax: 0 },
total,
@@ -71,7 +104,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
- idempotency_id: Some(item.connector_request_reference_id.clone()),
+ idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(_)
@@ -347,13 +380,12 @@ pub struct StaxCaptureRequest {
total: Option<f64>,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for StaxCaptureRequest {
+impl TryFrom<&StaxRouterData<&types::PaymentsCaptureRouterData>> for StaxCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
- let total = utils::to_currency_base_unit_asf64(
- item.request.amount_to_capture,
- item.request.currency,
- )?;
+ fn try_from(
+ item: &StaxRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let total = item.amount;
Ok(Self { total: Some(total) })
}
}
@@ -365,15 +397,10 @@ pub struct StaxRefundRequest {
pub total: f64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for StaxRefundRequest {
+impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- Ok(Self {
- total: utils::to_currency_base_unit_asf64(
- item.request.refund_amount,
- item.request.currency,
- )?,
- })
+ fn try_from(item: &StaxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self { total: item.amount })
}
}
| 2023-10-27T14:45:03Z |
## Description
<!-- Describe your changes in detail -->
This PR solves the Currency Unit Conversion for STAX Connector and fixes issue #2246
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | e40a29351c7aa7b86a5684959a84f0236104cafd |
We need to create a payment using Stax and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/stax.rs",
"crates/router/src/connector/stax/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2241 | Bug: [FEATURE]: [Payeezy] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs
index da712605437..03e76af907c 100644
--- a/crates/router/src/connector/payeezy.rs
+++ b/crates/router/src/connector/payeezy.rs
@@ -90,6 +90,10 @@ impl ConnectorCommon for Payeezy {
"payeezy"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -292,12 +296,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?;
+ let router_obj = payeezy::PayeezyRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let req_obj = payeezy::PayeezyCaptureOrVoidRequest::try_from(&router_obj)?;
let payeezy_req = types::RequestBody::log_and_get_request_body(
- &connector_req,
+ &req_obj,
utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
Ok(Some(payeezy_req))
}
@@ -380,9 +391,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = payeezy::PayeezyPaymentsRequest::try_from(req)?;
+ let router_obj = payeezy::PayeezyRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = payeezy::PayeezyPaymentsRequest::try_from(&router_obj)?;
+
let payeezy_req = types::RequestBody::log_and_get_request_body(
- &connector_req,
+ &req_obj,
utils::Encode::<payeezy::PayeezyPaymentsRequest>::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
@@ -469,10 +487,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = payeezy::PayeezyRefundRequest::try_from(req)?;
+ let router_obj = payeezy::PayeezyRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let req_obj = payeezy::PayeezyRefundRequest::try_from(&router_obj)?;
let payeezy_req = types::RequestBody::log_and_get_request_body(
- &connector_req,
- utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json,
+ &req_obj,
+ utils::Encode::<payeezy::PayeezyRefundRequest>::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(payeezy_req))
@@ -499,16 +523,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
data: &types::RefundsRouterData<api::Execute>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ // Parse the response into a payeezy::RefundResponse
let response: payeezy::RefundResponse = res
.response
.parse_struct("payeezy RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- types::RefundsRouterData::try_from(types::ResponseRouterData {
+
+ // Create a new instance of types::RefundsRouterData based on the response, input data, and HTTP code
+ let response_data = types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
- })
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ };
+ let router_data = types::RefundsRouterData::try_from(response_data)
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(router_data)
}
fn get_error_response(
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index efcd1b36d5b..3a859b32530 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -9,6 +9,37 @@ use crate::{
core::errors,
types::{self, api, storage::enums, transformers::ForeignFrom},
};
+#[derive(Debug, Serialize)]
+pub struct PayeezyRouterData<T> {
+ pub amount: String,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for PayeezyRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (currency_unit, currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
#[derive(Serialize, Debug)]
pub struct PayeezyCard {
@@ -66,7 +97,7 @@ pub struct PayeezyPaymentsRequest {
pub merchant_ref: String,
pub transaction_type: PayeezyTransactionType,
pub method: PayeezyPaymentMethodType,
- pub amount: i64,
+ pub amount: String,
pub currency_code: String,
pub credit_card: PayeezyPaymentMethod,
pub stored_credentials: Option<StoredCredentials>,
@@ -95,10 +126,12 @@ pub enum Initiator {
CardHolder,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest {
+impl TryFrom<&PayeezyRouterData<&types::PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- match item.payment_method {
+ fn try_from(
+ item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.payment_method {
diesel_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item),
diesel_models::enums::PaymentMethod::CardRedirect
@@ -119,14 +152,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest {
}
fn get_card_specific_payment_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let merchant_ref = item.attempt_id.to_string();
+ let merchant_ref = item.router_data.attempt_id.to_string();
let method = PayeezyPaymentMethodType::CreditCard;
- let amount = item.request.amount;
- let currency_code = item.request.currency.to_string();
+ let amount = item.amount.clone();
+ let currency_code = item.router_data.request.currency.to_string();
let credit_card = get_payment_method_data(item)?;
- let (transaction_type, stored_credentials) = get_transaction_type_and_stored_creds(item)?;
+ let (transaction_type, stored_credentials) =
+ get_transaction_type_and_stored_creds(item.router_data)?;
Ok(PayeezyPaymentsRequest {
merchant_ref,
transaction_type,
@@ -135,7 +169,7 @@ fn get_card_specific_payment_data(
currency_code,
credit_card,
stored_credentials,
- reference: item.connector_request_reference_id.clone(),
+ reference: item.router_data.connector_request_reference_id.clone(),
})
}
fn get_transaction_type_and_stored_creds(
@@ -201,9 +235,9 @@ fn is_mandate_payment(
}
fn get_payment_method_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentMethod, error_stack::Report<errors::ConnectorError>> {
- match item.request.payment_method_data {
+ match item.router_data.request.payment_method_data {
api::PaymentMethodData::Card(ref card) => {
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
@@ -305,16 +339,20 @@ pub struct PayeezyCaptureOrVoidRequest {
currency_code: String,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for PayeezyCaptureOrVoidRequest {
+impl TryFrom<&PayeezyRouterData<&types::PaymentsCaptureRouterData>>
+ for PayeezyCaptureOrVoidRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &PayeezyRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
- utils::to_connector_meta(item.request.connector_meta.clone())
+ utils::to_connector_meta(item.router_data.request.connector_meta.clone())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Capture,
- amount: item.request.amount_to_capture.to_string(),
- currency_code: item.request.currency.to_string(),
+ amount: item.amount.clone(),
+ currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
@@ -338,6 +376,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
})
}
}
+
#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyTransactionType {
@@ -442,16 +481,18 @@ pub struct PayeezyRefundRequest {
currency_code: String,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for PayeezyRefundRequest {
+impl<F> TryFrom<&PayeezyRouterData<&types::RefundsRouterData<F>>> for PayeezyRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &PayeezyRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
- utils::to_connector_meta(item.request.connector_metadata.clone())
+ utils::to_connector_meta(item.router_data.request.connector_metadata.clone())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Refund,
- amount: item.request.refund_amount.to_string(),
- currency_code: item.request.currency.to_string(),
+ amount: item.amount.clone(),
+ currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
| 2023-10-27T13:51:28Z |
## 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).
-->
Fixes #2241
# | cdca284b2a7a77cb22074fa8b3b380a088c10f00 |
We need to create a payment using payeezy and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/payeezy.rs",
"crates/router/src/connector/payeezy/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2236 | Bug: [FEATURE]: [NMI] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index cdeb9c99d5e..4f7ee15d730 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -58,6 +58,10 @@ impl ConnectorCommon for Nmi {
"nmi"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
connectors.nmi.base_url.as_ref()
}
@@ -210,7 +214,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = nmi::NmiPaymentsRequest::try_from(req)?;
+ let connector_router_data = nmi::NmiRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = nmi::NmiPaymentsRequest::try_from(&connector_router_data)?;
let nmi_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<nmi::NmiPaymentsRequest>::url_encode,
@@ -351,7 +361,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = nmi::NmiCaptureRequest::try_from(req)?;
+ let connector_router_data = nmi::NmiRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let connector_req = nmi::NmiCaptureRequest::try_from(&connector_router_data)?;
let nmi_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<NmiCaptureRequest>::url_encode,
@@ -491,7 +507,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = nmi::NmiRefundRequest::try_from(req)?;
+ let connector_router_data = nmi::NmiRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = nmi::NmiRefundRequest::try_from(&connector_router_data)?;
let nmi_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<nmi::NmiRefundRequest>::url_encode,
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 582bb9f7367..995341fefd9 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -40,6 +40,37 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType {
}
}
+#[derive(Debug, Serialize)]
+pub struct NmiRouterData<T> {
+ pub amount: f64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for NmiRouterData<T>
+{
+ type Error = Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: utils::to_currency_base_unit_asf64(amount, currency)?,
+ router_data,
+ })
+ }
+}
+
#[derive(Debug, Serialize)]
pub struct NmiPaymentsRequest {
#[serde(rename = "type")]
@@ -77,25 +108,27 @@ pub struct ApplePayData {
applepay_payment_data: Secret<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest {
+impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPaymentsRequest {
type Error = Error;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let transaction_type = match item.request.is_auto_capture()? {
+ fn try_from(
+ item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
- let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
- let amount =
- utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
- let payment_method = PaymentMethod::try_from(&item.request.payment_method_data)?;
+ let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
+ let amount = item.amount;
+ let payment_method =
+ PaymentMethod::try_from(&item.router_data.request.payment_method_data)?;
Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
- currency: item.request.currency,
+ currency: item.router_data.request.currency,
payment_method,
- orderid: item.connector_request_reference_id.clone(),
+ orderid: item.router_data.connector_request_reference_id.clone(),
})
}
}
@@ -243,18 +276,17 @@ pub struct NmiCaptureRequest {
pub amount: Option<f64>,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for NmiCaptureRequest {
+impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRequest {
type Error = Error;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
- let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
+ fn try_from(
+ item: &NmiRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
transaction_type: TransactionType::Capture,
security_key: auth.api_key,
- transactionid: item.request.connector_transaction_id.clone(),
- amount: Some(utils::to_currency_base_unit_asf64(
- item.request.amount_to_capture,
- item.request.currency,
- )?),
+ transactionid: item.router_data.request.connector_transaction_id.clone(),
+ amount: Some(item.amount),
})
}
}
@@ -577,18 +609,15 @@ pub struct NmiRefundRequest {
amount: f64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for NmiRefundRequest {
+impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundRequest {
type Error = Error;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
+ fn try_from(item: &NmiRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
Ok(Self {
transaction_type: TransactionType::Refund,
security_key: auth_type.api_key,
- transactionid: item.request.connector_transaction_id.clone(),
- amount: utils::to_currency_base_unit_asf64(
- item.request.refund_amount,
- item.request.currency,
- )?,
+ transactionid: item.router_data.request.connector_transaction_id.clone(),
+ amount: item.amount,
})
}
}
| 2023-10-27T09:20:15Z |
## Description
- Addressing Issue: #2236
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `nmi.rs`
- Implement `get_currency_unit` function
- Modify `ConnectorIntegration` implementations for `Nmi`
- `nmi/transformers.rs`
- Implement `NmiRouterData<T>` structure and functionality
- Modify implementation for `NmiPaymentsRequest`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 53b8fefbc2f8b58d1be7e9f35ca8b7e44e327bfb |
We need to create a payment using NMI and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/nmi.rs",
"crates/router/src/connector/nmi/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2268 | Bug: [REFACTOR]: [Cybersource] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 9b0bf61c545..324fe77d0bc 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -193,9 +193,22 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?,
},
- _ => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Cybersource"),
- ))?,
+ payments::PaymentMethodData::CardRedirect(_)
+ | payments::PaymentMethodData::PayLater(_)
+ | payments::PaymentMethodData::BankRedirect(_)
+ | payments::PaymentMethodData::BankDebit(_)
+ | payments::PaymentMethodData::BankTransfer(_)
+ | payments::PaymentMethodData::Crypto(_)
+ | payments::PaymentMethodData::MandatePayment
+ | payments::PaymentMethodData::Reward
+ | payments::PaymentMethodData::Upi(_)
+ | payments::PaymentMethodData::Voucher(_)
+ | payments::PaymentMethodData::GiftCard(_)
+ | payments::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Cybersource"),
+ ))?
+ }
};
let processing_information = ProcessingInformation {
| 2023-10-26T21:29:00Z |
## 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).
-->
https://github.com/juspay/hyperswitch/issues/2268
# | a8c74321dbba5c7be6468fff7680d703d726a781 |
Make a mandate payment for cybersource, for the payment method which is not implemented like bank_debit or bank_transfer and check for the error message - it should be PM not implemented
| [
"crates/router/src/connector/cybersource/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2297 | Bug: [FEATURE]: [Dlocal] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 5146dd0ea03..668a335cce8 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -145,7 +145,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
.clone()
.map(|_| "1".to_string()),
}),
- order_id: item.router_data.payment_id.clone(),
+ order_id: item.router_data.connector_request_reference_id.clone(),
three_dsecure: match item.router_data.auth_type {
diesel_models::enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
@@ -237,7 +237,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for DlocalPaymentsCaptureRequest
authorization_id: item.request.connector_transaction_id.clone(),
amount: item.request.amount_to_capture,
currency: item.request.currency.to_string(),
- order_id: item.payment_id.clone(),
+ order_id: item.connector_request_reference_id.clone(),
})
}
}
| 2023-10-26T19:01:06Z | …cal connector #2297
## Description
Use connector_request_reference_id as reference to the connector #2297
## Motivation and Context
To solve inconsistency in RouterData and it solves the Issue #2297
# | 6dc71fe9923a793b76eee2ea1ac1060ab584a303 | Make any Payment for connector Dlocal and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/dlocal/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2262 | Bug: [REFACTOR]: [Airwallex] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 51258643c64..031a8276bb0 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -186,8 +186,18 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
}))
}
api::PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Unknown payment method".to_string(),
+ api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("airwallex"),
)),
}?;
@@ -215,9 +225,35 @@ fn get_wallet_details(
payment_method_type: AirwallexPaymentType::Googlepay,
}))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- ))?,
+ api_models::payments::WalletData::AliPayQr(_)
+ | api_models::payments::WalletData::AliPayRedirect(_)
+ | api_models::payments::WalletData::AliPayHkRedirect(_)
+ | api_models::payments::WalletData::MomoRedirect(_)
+ | api_models::payments::WalletData::KakaoPayRedirect(_)
+ | api_models::payments::WalletData::GoPayRedirect(_)
+ | api_models::payments::WalletData::GcashRedirect(_)
+ | api_models::payments::WalletData::ApplePay(_)
+ | api_models::payments::WalletData::ApplePayRedirect(_)
+ | api_models::payments::WalletData::ApplePayThirdPartySdk(_)
+ | api_models::payments::WalletData::DanaRedirect {}
+ | api_models::payments::WalletData::GooglePayRedirect(_)
+ | api_models::payments::WalletData::GooglePayThirdPartySdk(_)
+ | api_models::payments::WalletData::MbWayRedirect(_)
+ | api_models::payments::WalletData::MobilePayRedirect(_)
+ | api_models::payments::WalletData::PaypalRedirect(_)
+ | api_models::payments::WalletData::PaypalSdk(_)
+ | api_models::payments::WalletData::SamsungPay(_)
+ | api_models::payments::WalletData::TwintRedirect {}
+ | api_models::payments::WalletData::VippsRedirect {}
+ | api_models::payments::WalletData::TouchNGoRedirect(_)
+ | api_models::payments::WalletData::WeChatPayRedirect(_)
+ | api_models::payments::WalletData::WeChatPayQr(_)
+ | api_models::payments::WalletData::CashappQr(_)
+ | api_models::payments::WalletData::SwishQr(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("airwallex"),
+ ))?
+ }
};
Ok(wallet_details)
}
| 2023-10-26T18:19:54Z |
## Description
<!-- Describe your changes in detail -->
#2262
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 6dc71fe9923a793b76eee2ea1ac1060ab584a303 | No test cases. As In this PR only error message have been populated for all default cases.
| [
"crates/router/src/connector/airwallex/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2338 | Bug: [FEATURE]: [NMI] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 5b486aae600..926f2c300d2 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -727,7 +727,7 @@ impl<T>
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transactionid.to_owned(),
+ item.response.transactionid.clone(),
),
redirection_data: None,
mandate_reference: None,
@@ -783,7 +783,7 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>>
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transactionid.to_owned(),
+ item.response.transactionid.clone(),
),
redirection_data: None,
mandate_reference: None,
@@ -833,7 +833,7 @@ impl<T>
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transactionid.to_owned(),
+ item.response.transactionid.clone(),
),
redirection_data: None,
mandate_reference: None,
| 2023-10-26T17:24:03Z |
## 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).
-->
# | 8ac4c205e8876ce596ff9a729e1f034360624ec2 |
Make any Payment for connector NMI and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be null.
| [
"crates/router/src/connector/nmi/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2286 | Bug: [REFACTOR]: [Square] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 01ed507bf34..54a7c461dbf 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -23,7 +23,10 @@ impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenReq
"Payment Method".to_string(),
))
.into_report(),
- _ => Err(errors::ConnectorError::NotSupported {
+
+ BankDebitData::SepaBankDebit { .. }
+ | BankDebitData::BecsBankDebit { .. }
+ | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotSupported {
message: format!("{:?}", item.request.payment_method_data),
connector: "Square",
})?,
@@ -85,7 +88,14 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ
errors::ConnectorError::NotImplemented("Payment Method".to_string()),
)
.into_report(),
- _ => Err(errors::ConnectorError::NotSupported {
+
+ PayLaterData::KlarnaRedirect { .. }
+ | PayLaterData::KlarnaSdk { .. }
+ | PayLaterData::AffirmRedirect { .. }
+ | PayLaterData::PayBrightRedirect { .. }
+ | PayLaterData::WalleyRedirect { .. }
+ | PayLaterData::AlmaRedirect { .. }
+ | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotSupported {
message: format!("{:?}", item.request.payment_method_data),
connector: "Square",
})?,
@@ -106,7 +116,31 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques
"Payment Method".to_string(),
))
.into_report(),
- _ => Err(errors::ConnectorError::NotSupported {
+
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported {
message: format!("{:?}", item.request.payment_method_data),
connector: "Square",
})?,
@@ -295,7 +329,14 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
}),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+
+ types::ConnectorAuthType::HeaderKey { .. }
+ | types::ConnectorAuthType::SignatureKey { .. }
+ | types::ConnectorAuthType::MultiAuthKey { .. }
+ | types::ConnectorAuthType::CurrencyAuthKey { .. }
+ | types::ConnectorAuthType::NoKey { .. } => {
+ Err(errors::ConnectorError::FailedToObtainAuthType.into())
+ }
}
}
}
| 2023-10-26T14:35:57Z |
## Description
<!-- Describe your changes in detail -->
- Fix issue #2286
- Changes to be made : Remove default case handling
- File changed: ```transformers.rs``` (crates/router/src/connector/square/transformers.rs)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/2286
# | 88e1f29dae13622bc58b8f5df1cd84b929b28ac6 |
No test cases. As In this PR only error message have been populated for all default cases.
| [
"crates/router/src/connector/square/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2298 | Bug: [FEATURE]: [Fiserv] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index c9c2f0c4087..ae8eed0af31 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -62,6 +62,7 @@ pub struct Amount {
pub struct TransactionDetails {
capture_flag: Option<bool>,
reversal_reason_code: Option<String>,
+ merchant_transaction_id: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -112,6 +113,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest {
Some(enums::CaptureMethod::Automatic) | None
)),
reversal_reason_code: None,
+ merchant_transaction_id: item.connector_request_reference_id.clone(),
};
let metadata = item.get_connector_meta()?;
let session: SessionObject = metadata
@@ -208,6 +210,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest {
transaction_details: TransactionDetails {
capture_flag: None,
reversal_reason_code: Some(item.request.get_cancellation_reason()?),
+ merchant_transaction_id: item.connector_request_reference_id.clone(),
},
})
}
@@ -407,6 +410,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for FiservCaptureRequest {
transaction_details: TransactionDetails {
capture_flag: Some(true),
reversal_reason_code: None,
+ merchant_transaction_id: item.connector_request_reference_id.clone(),
},
merchant_details: MerchantDetails {
merchant_id: auth.merchant_account,
| 2023-10-26T11:51:29Z |
## 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).
-->
# | 6dc71fe9923a793b76eee2ea1ac1060ab584a303 | Make any Payment for connector Fiserv and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/fiserv/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2294 | Bug: [FEATURE]: [Bitpay] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index c5c20608a75..5af20d6423f 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -60,6 +60,7 @@ pub struct BitpayPaymentsRequest {
notification_url: String,
transaction_speed: TransactionSpeed,
token: Secret<String>,
+ order_id: String,
}
impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest {
@@ -279,6 +280,7 @@ fn get_crypto_specific_payment_data(
ConnectorAuthType::HeaderKey { api_key } => api_key,
_ => String::default().into(),
};
+ let order_id = item.router_data.connector_request_reference_id.clone();
Ok(BitpayPaymentsRequest {
price,
@@ -287,6 +289,7 @@ fn get_crypto_specific_payment_data(
notification_url,
transaction_speed,
token,
+ order_id,
})
}
| 2023-10-26T09:49:02Z |
## 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).
-->
# | e40a29351c7aa7b86a5684959a84f0236104cafd |
Make any Payment for connector Bitpay and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/bitpay/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2335 | Bug: [FEATURE]: [Mollie] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 3c23c9f1d39..56f280d288a 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -590,7 +590,7 @@ pub struct RefundResponse {
status: MollieRefundStatus,
description: Option<String>,
metadata: serde_json::Value,
- payment_id: String,
+ connector_response_reference_id: String,
#[serde(rename = "_links")]
links: Links,
}
| 2023-10-26T04:17:27Z |
## 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).
-->
Motivation can be found https://github.com/juspay/hyperswitch/issues/2335
# | 8e484ddab8d3f4463299c7f7e8ce75b8dd628599 |
Make any Payment for connector Mollie and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be null.
| [
"crates/router/src/connector/mollie/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2302 | Bug: [FEATURE]: [Iatapay] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index f98798fe5be..d4731b024c8 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -110,7 +110,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest {
utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
let payload = Self {
merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id,
- merchant_payment_id: Some(item.payment_id.clone()),
+ merchant_payment_id: Some(item.connector_request_reference_id.clone()),
amount,
currency: item.request.currency.to_string(),
country: country.clone(),
| 2023-10-25T18:56:03Z |
## Description
<!-- Describe your changes in detail -->
fixes #2302
# | 2815443c1b147e005a2384ff817292b1845a9f88 |
Make any Payment for connector Iatapay and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/iatapay/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2279 | Bug: [REFACTOR]: [Opayo] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index d828232dbc1..41bcc1500ed 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -2,7 +2,7 @@ use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils::{self, PaymentsAuthorizeRequestData},
core::errors,
types::{self, api, storage::enums},
};
@@ -41,7 +41,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest {
card,
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Opayo"),
+ )
+ .into()),
}
}
}
| 2023-10-25T12:28:59Z |
## Description
<!-- Describe your changes in detail -->
#2279
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 27b97626245cab12dd9aefb4d85a77b5c913dba0 | [
"crates/router/src/connector/opayo/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2233 | Bug: [FEATURE]: [Nexi Nets] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs
index 30ae4ab25e5..ac0d7494d2d 100644
--- a/crates/router/src/connector/nexinets.rs
+++ b/crates/router/src/connector/nexinets.rs
@@ -76,6 +76,10 @@ impl ConnectorCommon for Nexinets {
"nexinets"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -200,9 +204,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = nexinets::NexinetsPaymentsRequest::try_from(req)?;
+ let connector_router_data = nexinets::NexinetsRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = nexinets::NexinetsPaymentsRequest::try_from(&connector_router_data)?;
let nexinets_req = types::RequestBody::log_and_get_request_body(
- &req_obj,
+ &connector_req,
utils::Encode::<nexinets::NexinetsPaymentsRequest>::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 2af3ee0a1bb..ce34fe8f5a2 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -14,7 +14,10 @@ use crate::{
consts,
core::errors,
services,
- types::{self, api, storage::enums, transformers::ForeignFrom},
+ types::{
+ self, api, storage::enums, transformers::ForeignFrom, PaymentsAuthorizeData,
+ PaymentsResponseData,
+ },
};
#[derive(Debug, Serialize)]
@@ -27,7 +30,6 @@ pub struct NexinetsPaymentsRequest {
payment: Option<NexinetsPaymentDetails>,
#[serde(rename = "async")]
nexinets_async: NexinetsAsyncDetails,
- merchant_order_id: Option<String>,
}
#[derive(Debug, Serialize, Default)]
@@ -163,29 +165,70 @@ pub struct ApplepayPaymentMethod {
token_type: String,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
+#[derive(Debug, Serialize)]
+pub struct NexinetsRouterData<T> {
+ amount: i64,
+ router_data: T,
+}
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for NexinetsRouterData<T>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let return_url = item.request.router_return_url.clone();
+ fn try_from(
+ (_currency_unit, _currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
+impl
+ TryFrom<
+ &NexinetsRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ > for NexinetsPaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &NexinetsRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let return_url = item.router_data.request.router_return_url.clone();
let nexinets_async = NexinetsAsyncDetails {
success_url: return_url.clone(),
cancel_url: return_url.clone(),
failure_url: return_url,
};
- let (payment, product) = get_payment_details_and_product(item)?;
- let merchant_order_id = match item.payment_method {
- // Merchant order id is sent only in case of card payment
- enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()),
- _ => None,
- };
+ let (payment, product) = get_payment_details_and_product(&item.router_data)?;
Ok(Self {
- initial_amount: item.request.amount,
- currency: item.request.currency,
+ initial_amount: item.router_data.request.amount,
+ currency: item.router_data.request.currency,
channel: NexinetsChannel::Ecom,
product,
payment,
nexinets_async,
- merchant_order_id,
})
}
}
@@ -312,23 +355,12 @@ pub struct NexinetsPaymentsMetadata {
}
impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- NexinetsPreAuthOrDebitResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ TryFrom<types::ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- NexinetsPreAuthOrDebitResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: types::ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction = match item.response.transactions.first() {
Some(order) => order,
@@ -421,13 +453,12 @@ pub struct NexinetsPaymentResponse {
pub transaction_type: NexinetsTransactionType,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = Some(item.response.transaction_id.clone());
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
| 2023-10-25T01:48:47Z |
## Description
This pull request implements the get_currency_unit from the ConnectorCommon trait for the Nexinets connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Nexinets it accepts currency as Minor units.
## Motivation and Context
Closes #2233
# | 8e484ddab8d3f4463299c7f7e8ce75b8dd628599 |
We need to create a payment using Nexinets and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/nexinets.rs",
"crates/router/src/connector/nexinets/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2277 | Bug: [REFACTOR]: [Noon] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index cde6de2e43b..4a2128f7ec6 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -245,13 +245,51 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
return_url: item.request.get_router_return_url()?,
}))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Wallets".to_string(),
- )),
+ api_models::payments::WalletData::AliPayQr(_)
+ | api_models::payments::WalletData::AliPayRedirect(_)
+ | api_models::payments::WalletData::AliPayHkRedirect(_)
+ | api_models::payments::WalletData::MomoRedirect(_)
+ | api_models::payments::WalletData::KakaoPayRedirect(_)
+ | api_models::payments::WalletData::GoPayRedirect(_)
+ | api_models::payments::WalletData::GcashRedirect(_)
+ | api_models::payments::WalletData::ApplePayRedirect(_)
+ | api_models::payments::WalletData::ApplePayThirdPartySdk(_)
+ | api_models::payments::WalletData::DanaRedirect {}
+ | api_models::payments::WalletData::GooglePayRedirect(_)
+ | api_models::payments::WalletData::GooglePayThirdPartySdk(_)
+ | api_models::payments::WalletData::MbWayRedirect(_)
+ | api_models::payments::WalletData::MobilePayRedirect(_)
+ | api_models::payments::WalletData::PaypalSdk(_)
+ | api_models::payments::WalletData::SamsungPay(_)
+ | api_models::payments::WalletData::TwintRedirect {}
+ | api_models::payments::WalletData::VippsRedirect {}
+ | api_models::payments::WalletData::TouchNGoRedirect(_)
+ | api_models::payments::WalletData::WeChatPayRedirect(_)
+ | api_models::payments::WalletData::WeChatPayQr(_)
+ | api_models::payments::WalletData::CashappQr(_)
+ | api_models::payments::WalletData::SwishQr(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Noon",
+ })
+ }
},
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
- )),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment {}
+ | api::PaymentMethodData::Reward {}
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Noon",
+ })
+ }
}?,
Some(item.request.currency),
item.request.order_category.clone(),
| 2023-10-25T00:59:43Z |
## Description
- Addresses Issue #2277
- Modified `crates/router/src/connector/noon/transformers.rs`
- Convert `NotImplemented` to `NotSupported` in default case
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 2815443c1b147e005a2384ff817292b1845a9f88 | No test cases. As In this PR only error message have been populated for all default cases.
| [
"crates/router/src/connector/noon/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2289 | Bug: [REFACTOR]: [Worldline] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index f11c2398080..80378215a45 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -247,11 +247,19 @@ impl
make_bank_redirect_request(&item.router_data.request, bank_redirect)?,
))
}
- _ => {
- return Err(
- errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
- )
- }
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldline"),
+ ))?,
};
let customer =
@@ -393,10 +401,25 @@ fn make_bank_redirect_request(
},
809,
),
- _ => {
- return Err(
- errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
+ payments::BankRedirectData::BancontactCard { .. }
+ | payments::BankRedirectData::Bizum {}
+ | payments::BankRedirectData::Blik { .. }
+ | payments::BankRedirectData::Eps { .. }
+ | payments::BankRedirectData::Interac { .. }
+ | payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | payments::BankRedirectData::OnlineBankingFinland { .. }
+ | payments::BankRedirectData::OnlineBankingPoland { .. }
+ | payments::BankRedirectData::OnlineBankingSlovakia { .. }
+ | payments::BankRedirectData::OpenBankingUk { .. }
+ | payments::BankRedirectData::Przelewy24 { .. }
+ | payments::BankRedirectData::Sofort { .. }
+ | payments::BankRedirectData::Trustly { .. }
+ | payments::BankRedirectData::OnlineBankingFpx { .. }
+ | payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ return Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldline"),
)
+ .into())
}
};
Ok(RedirectPaymentMethod {
| 2023-10-24T09:39:40Z |
## Description
<!-- Describe your changes in detail -->
https://github.com/juspay/hyperswitch/issues/2289
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | eaa972052024678ade122eec14261f9f33788e45 | [
"crates/router/src/connector/worldline/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2288 | Bug: [REFACTOR]: [Tsys] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index 83134568c05..a3bd1c4a074 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -3,7 +3,7 @@ use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{CardData, PaymentsAuthorizeRequestData, RefundsRequestData},
+ connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RefundsRequestData},
core::errors,
types::{
self, api,
@@ -66,7 +66,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
Ok(Self::Auth(auth_data))
}
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("tsys"),
+ ))?,
}
}
}
| 2023-10-23T21:26:08Z |
## Description
<!-- https://github.com/juspay/hyperswitch/issues/2288 -->
Resolves: #2288
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | eaa972052024678ade122eec14261f9f33788e45 | [
"crates/router/src/connector/tsys/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2244 | Bug: [FEATURE]: [Rapyd] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index 292e6c55f26..29f21f37381 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -64,6 +64,10 @@ impl ConnectorCommon for Rapyd {
"rapyd"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -179,7 +183,13 @@ impl
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = rapyd::RapydPaymentsRequest::try_from(req)?;
+ let connector_router_data = rapyd::RapydRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = rapyd::RapydPaymentsRequest::try_from(&connector_router_data)?;
let rapyd_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<rapyd::RapydPaymentsRequest>::encode_to_string_of_json,
@@ -483,7 +493,13 @@ impl
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = rapyd::CaptureRequest::try_from(req)?;
+ let connector_router_data = rapyd::RapydRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let req_obj = rapyd::CaptureRequest::try_from(&connector_router_data)?;
let rapyd_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<rapyd::CaptureRequest>::encode_to_string_of_json,
@@ -615,7 +631,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = rapyd::RapydRefundRequest::try_from(req)?;
+ let connector_router_data = rapyd::RapydRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let req_obj = rapyd::RapydRefundRequest::try_from(&connector_router_data)?;
let rapyd_req = types::RequestBody::log_and_get_request_body(
&req_obj,
utils::Encode::<rapyd::RapydRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 79ad6838ac3..9df699b938b 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -13,6 +13,36 @@ use crate::{
utils::OptionExt,
};
+#[derive(Debug, Serialize)]
+pub struct RapydRouterData<T> {
+ pub amount: i64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for RapydRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (_currency_unit, _currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize)]
pub struct RapydPaymentsRequest {
pub amount: i64,
@@ -69,18 +99,23 @@ pub struct RapydWallet {
token: Option<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest {
+impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let (capture, payment_method_options) = match item.payment_method {
+ fn try_from(
+ item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let (capture, payment_method_options) = match item.router_data.payment_method {
diesel_models::enums::PaymentMethod::Card => {
- let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs);
+ let three_ds_enabled = matches!(
+ item.router_data.auth_type,
+ enums::AuthenticationType::ThreeDs
+ );
let payment_method_options = PaymentMethodOptions {
three_ds: three_ds_enabled,
};
(
Some(matches!(
- item.request.capture_method,
+ item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
Some(payment_method_options),
@@ -88,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest {
}
_ => (None, None),
};
- let payment_method = match item.request.payment_method_data {
+ let payment_method = match item.router_data.request.payment_method_data {
api_models::payments::PaymentMethodData::Card(ref ccard) => {
Some(PaymentMethod {
pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country
@@ -128,10 +163,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest {
.change_context(errors::ConnectorError::NotImplemented(
"payment_method".to_owned(),
))?;
- let return_url = item.request.get_return_url()?;
+ let return_url = item.router_data.request.get_return_url()?;
Ok(Self {
- amount: item.request.amount,
- currency: item.request.currency,
+ amount: item.amount,
+ currency: item.router_data.request.currency,
payment_method,
capture,
payment_method_options,
@@ -276,13 +311,17 @@ pub struct RapydRefundRequest {
pub currency: Option<enums::Currency>,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for RapydRefundRequest {
+impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
- payment: item.request.connector_transaction_id.to_string(),
- amount: Some(item.request.refund_amount),
- currency: Some(item.request.currency),
+ payment: item
+ .router_data
+ .request
+ .connector_transaction_id
+ .to_string(),
+ amount: Some(item.amount),
+ currency: Some(item.router_data.request.currency),
})
}
}
@@ -380,11 +419,13 @@ pub struct CaptureRequest {
statement_descriptor: Option<String>,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for CaptureRequest {
+impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &RapydRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: Some(item.request.amount_to_capture),
+ amount: Some(item.amount),
receipt_email: None,
statement_descriptor: None,
})
| 2023-10-22T19:22:53Z |
## Description
<!-- Describe your changes in detail -->
This PR solves issue number #2244 for currency unit conversion in Rapyd Connector
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #2244.
# | af90089010e06ed45a70c51d4143260eec45b6dc | Create a payment via hyperswitch, (Rapyd connector) and match the amount you are passing in your request with amount you are getting in connector response. Both should be same
| [
"crates/router/src/connector/rapyd.rs",
"crates/router/src/connector/rapyd/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-1793 | Bug: [BUG] Add Create Merchant and Create Merchant Key Store in a DB transaction
Currently MerchantAccount and MerchantKeyStore are getting inserted seperately. Since both of them are interdependent we need to make sure both are consistent with each other. If one of them fails other shouldn't get inserted.
We need to add this in a db_transaction
https://github.com/juspay/hyperswitch/blob/4805a94ab905da520edacdddab41e9e74bd3a956/crates/router/src/core/admin.rs#L133-L186
For reference of how to do it in a db transaction
```rust
pool.transaction_async(|conn| async move {
diesel::update(dsl::users)
.filter(dsl::id.eq(0))
.set(dsl::name.eq("Let's change the name again"))
.execute_async(&conn)
.await
.map_err(|e| PoolError::Connection(e))
})
``` | diff --git a/crates/diesel_models/src/errors.rs b/crates/diesel_models/src/errors.rs
index 0a8422131ae..30e4273fdb5 100644
--- a/crates/diesel_models/src/errors.rs
+++ b/crates/diesel_models/src/errors.rs
@@ -10,7 +10,15 @@ pub enum DatabaseError {
NoFieldsToUpdate,
#[error("An error occurred when generating typed SQL query")]
QueryGenerationFailed,
+ #[error("DB transaction failure")]
+ TransactionFailed(String),
// InsertFailed,
#[error("An unknown error occurred")]
Others,
}
+
+impl From<diesel::result::Error> for DatabaseError {
+ fn from(err: diesel::result::Error) -> Self {
+ Self::TransactionFailed(err.to_string())
+ }
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c0d6c576dd5..0472ffb4198 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -111,10 +111,6 @@ pub async fn create_merchant_account(
.payment_response_hash_key
.or(Some(generate_cryptographically_secure_random_string(64)));
- db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into())
- .await
- .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
-
let parent_merchant_id = get_parent_merchant(
db,
req.sub_merchants_enabled,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index e0bff7d9069..5f533eabc9f 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -1,3 +1,4 @@
+use async_bb8_diesel::AsyncConnection;
use common_utils::ext_traits::AsyncExt;
use error_stack::{IntoReport, ResultExt};
#[cfg(feature = "accounts_cache")]
@@ -72,20 +73,36 @@ impl MerchantAccountInterface for Store {
async fn insert_merchant(
&self,
merchant_account: domain::MerchantAccount,
- merchant_key_store: &domain::MerchantKeyStore,
+ merchant_key_store: domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- merchant_account
- .construct_new()
- .await
- .change_context(errors::StorageError::EncryptionError)?
- .insert(&conn)
- .await
- .map_err(Into::into)
- .into_report()?
- .convert(merchant_key_store.key.get_inner())
- .await
- .change_context(errors::StorageError::DecryptionError)
+
+ conn.transaction_async(|e| async move {
+ let key_store = merchant_key_store
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&e)
+ .await
+ .map_err(Into::into)
+ .into_report()?
+ .convert(&self.get_master_key().to_vec().into())
+ .await
+ .change_context(errors::StorageError::DecryptionError);
+
+ merchant_account
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&e)
+ .await
+ .map_err(Into::into)
+ .into_report()?
+ .convert(merchant_key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
}
async fn find_merchant_account_by_merchant_id(
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index bc68986cb8e..c8abccdf4b6 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -98,6 +98,9 @@ impl Into<DataStorageError> for &StorageError {
storage_errors::DatabaseError::QueryGenerationFailed => {
DataStorageError::DatabaseError("Query generation failed".to_string())
}
+ storage_errors::DatabaseError::TransactionFailed(e) => {
+ DataStorageError::DatabaseError(e.to_string())
+ }
storage_errors::DatabaseError::Others => {
DataStorageError::DatabaseError("Unknown database error".to_string())
}
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index dd8d71fc701..406c6ee9ab8 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -245,6 +245,9 @@ pub(crate) fn diesel_error_to_data_error(
diesel_models::errors::DatabaseError::QueryGenerationFailed => {
StorageError::DatabaseError("Query generation failed".to_string())
}
+ store::errors::DatabaseError::TransactionFailed(e) => {
+ StorageError::DatabaseError(e.to_string())
+ }
diesel_models::errors::DatabaseError::Others => {
StorageError::DatabaseError("Others".to_string())
}
| 2023-10-22T14:35:52Z |
## Description
Merchant account creation and respective key store creation now happen in a DB transaction
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 8e484ddab8d3f4463299c7f7e8ce75b8dd628599 |
- Create a merchant account.
- Check if both merchant account and merchant key store exists
```
SELECT * from merchant_account;
SELECT * from merchant_key_store;
```
| [
"crates/diesel_models/src/errors.rs",
"crates/router/src/core/admin.rs",
"crates/router/src/db/merchant_account.rs",
"crates/storage_impl/src/errors.rs",
"crates/storage_impl/src/lib.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2221 | Bug: [FEATURE]: [Coinbase] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs
index d50e490cfc3..5b9bedbd9c1 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/router/src/connector/coinbase.rs
@@ -74,6 +74,10 @@ impl ConnectorCommon for Coinbase {
"coinbase"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -184,7 +188,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = coinbase::CoinbasePaymentsRequest::try_from(req)?;
+ let connector_router_data = coinbase::CoinbaseRouterData::try_from({
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ })?;
+ let req_obj = coinbase::CoinbasePaymentsRequest::try_from(&connector_router_data)?;
let coinbase_payment_request = types::RequestBody::log_and_get_request_body(
&connector_request,
Encode::<coinbase::CoinbasePaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index 6cc097bc9d8..971c8332c2e 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -10,6 +10,39 @@ use crate::{
types::{self, api, storage::enums},
};
+#[derive(Debug, Serialize)]
+pub struct CoinbaseRouterdata<T> {
+ amount: String,
+ router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for CoinbaseRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error>
+ {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct LocalPrice {
pub amount: String,
@@ -32,10 +65,10 @@ pub struct CoinbasePaymentsRequest {
pub cancel_url: String,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest {
+impl TryFrom<CoinbseRouterData<&types::PaymentsAuthorizeRouterData> for CoinbasePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- get_crypto_specific_payment_data(item)
+ fn try_from(item:&CoinbseRouterData<&types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ get_crypto_specific_payment_data(item.RouterData)
}
}
| 2023-10-20T17:28:07Z |
## Description
This pull request introduces the get_currecny_unit from ConnectorCommon trait for `CoinBase`. This function allows connectors to declare their accepted currency unit as either "Base" or "Minor" .For coinbase it accepts currency as Base.
# | 8e484ddab8d3f4463299c7f7e8ce75b8dd628599 |
We need to create a payment using coinbase and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/coinbase.rs",
"crates/router/src/connector/coinbase/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2240 | Bug: [FEATURE]: [OpenNode] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs
index 6fad0f47205..07d33382a21 100644
--- a/crates/router/src/connector/opennode.rs
+++ b/crates/router/src/connector/opennode.rs
@@ -72,6 +72,10 @@ impl ConnectorCommon for Opennode {
"opennode"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -169,7 +173,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = opennode::OpennodePaymentsRequest::try_from(req)?;
+ let connector_router_data = opennode::OpennodeRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = opennode::OpennodePaymentsRequest::try_from(&connector_router_data)?;
let opennode_req = types::RequestBody::log_and_get_request_body(
&req_obj,
Encode::<opennode::OpennodePaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index b367012ca75..794fc857341 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -10,6 +10,37 @@ use crate::{
types::{self, api, storage::enums},
};
+#[derive(Debug, Serialize)]
+pub struct OpennodeRouterData<T> {
+ pub amount: i64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for OpennodeRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpennodePaymentsRequest {
@@ -22,9 +53,11 @@ pub struct OpennodePaymentsRequest {
order_id: String,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest {
+impl TryFrom<&OpennodeRouterData<&types::PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
@@ -146,11 +179,13 @@ pub struct OpennodeRefundRequest {
pub amount: i64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for OpennodeRefundRequest {
+impl<F> TryFrom<&OpennodeRouterData<&types::RefundsRouterData<F>>> for OpennodeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &OpennodeRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.refund_amount,
+ amount: item.router_data.request.refund_amount,
})
}
}
@@ -222,14 +257,15 @@ pub struct OpennodeErrorResponse {
}
fn get_crypto_specific_payment_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let amount = item.request.amount;
- let currency = item.request.currency.to_string();
- let description = item.get_description()?;
+ let amount = item.amount;
+ let currency = item.router_data.request.currency.to_string();
+ let description = item.router_data.get_description()?;
let auto_settle = true;
- let success_url = item.get_return_url()?;
- let callback_url = item.request.get_webhook_url()?;
+ let success_url = item.router_data.get_return_url()?;
+ let callback_url = item.router_data.request.get_webhook_url()?;
+ let order_id = item.router_data.connector_request_reference_id.clone();
Ok(OpennodePaymentsRequest {
amount,
@@ -238,7 +274,7 @@ fn get_crypto_specific_payment_data(
auto_settle,
success_url,
callback_url,
- order_id: item.connector_request_reference_id.clone(),
+ order_id,
})
}
| 2023-10-19T15:45:27Z |
## Description
- Addressing Issue: #2240
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `opennode.rs`
- Implement `get_currency_unit` function
- Modify `ConnectorIntegration` implementations for `Opennode`
- `opennode/transformers.rs`
- Implement `OpennodeRouterData<T>` structure and functionality
- Modify implementation for `OpennodePaymentsRequest`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 62d5727092ac482dd086ab9e814a8ba5e3011849 |
We need to create a payment using opennode and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/opennode.rs",
"crates/router/src/connector/opennode/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2267 | Bug: [REFACTOR]: [CryptoPay] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index a49380cb365..8d9f277dd0f 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -69,9 +69,23 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "payment method".to_string(),
- )),
+ api_models::payments::PaymentMethodData::Card(_)
+ | api_models::payments::PaymentMethodData::CardRedirect(_)
+ | api_models::payments::PaymentMethodData::Wallet(_)
+ | api_models::payments::PaymentMethodData::PayLater(_)
+ | api_models::payments::PaymentMethodData::BankRedirect(_)
+ | api_models::payments::PaymentMethodData::BankDebit(_)
+ | api_models::payments::PaymentMethodData::BankTransfer(_)
+ | api_models::payments::PaymentMethodData::MandatePayment {}
+ | api_models::payments::PaymentMethodData::Reward {}
+ | api_models::payments::PaymentMethodData::Upi(_)
+ | api_models::payments::PaymentMethodData::Voucher(_)
+ | api_models::payments::PaymentMethodData::GiftCard(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "CryptoPay",
+ })
+ }
}?;
Ok(cryptopay_request)
}
| 2023-10-19T10:21:04Z |
## Description
<!-- Describe your changes in detail -->
Removed the default match case as mentioned in the 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).
-->
# | 664093dc79743203196d912c17570885718b1c02 | [
"crates/router/src/connector/cryptopay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2275 | Bug: [REFACTOR]: [Nexi nets] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 897d8f639d3..2af3ee0a1bb 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -9,7 +9,7 @@ use url::Url;
use crate::{
connector::utils::{
- CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData,
+ self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData,
},
consts,
core::errors,
@@ -597,12 +597,35 @@ fn get_payment_details_and_product(
api_models::payments::BankRedirectData::Sofort { .. } => {
Ok((None, NexinetsProduct::Sofort))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
- ))?,
+ api_models::payments::BankRedirectData::BancontactCard { .. }
+ | api_models::payments::BankRedirectData::Blik { .. }
+ | api_models::payments::BankRedirectData::Bizum { .. }
+ | api_models::payments::BankRedirectData::Interac { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
+ | api_models::payments::BankRedirectData::OpenBankingUk { .. }
+ | api_models::payments::BankRedirectData::Przelewy24 { .. }
+ | api_models::payments::BankRedirectData::Trustly { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("nexinets"),
+ ))?
+ }
},
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
}
@@ -677,9 +700,34 @@ fn get_wallet_details(
))),
NexinetsProduct::Applepay,
)),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
- ))?,
+ api_models::payments::WalletData::AliPayQr(_)
+ | api_models::payments::WalletData::AliPayRedirect(_)
+ | api_models::payments::WalletData::AliPayHkRedirect(_)
+ | api_models::payments::WalletData::MomoRedirect(_)
+ | api_models::payments::WalletData::KakaoPayRedirect(_)
+ | api_models::payments::WalletData::GoPayRedirect(_)
+ | api_models::payments::WalletData::GcashRedirect(_)
+ | api_models::payments::WalletData::ApplePayRedirect(_)
+ | api_models::payments::WalletData::ApplePayThirdPartySdk(_)
+ | api_models::payments::WalletData::DanaRedirect { .. }
+ | api_models::payments::WalletData::GooglePay(_)
+ | api_models::payments::WalletData::GooglePayRedirect(_)
+ | api_models::payments::WalletData::GooglePayThirdPartySdk(_)
+ | api_models::payments::WalletData::MbWayRedirect(_)
+ | api_models::payments::WalletData::MobilePayRedirect(_)
+ | api_models::payments::WalletData::PaypalSdk(_)
+ | api_models::payments::WalletData::SamsungPay(_)
+ | api_models::payments::WalletData::TwintRedirect { .. }
+ | api_models::payments::WalletData::VippsRedirect { .. }
+ | api_models::payments::WalletData::TouchNGoRedirect(_)
+ | api_models::payments::WalletData::WeChatPayRedirect(_)
+ | api_models::payments::WalletData::WeChatPayQr(_)
+ | api_models::payments::WalletData::CashappQr(_)
+ | api_models::payments::WalletData::SwishQr(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("nexinets"),
+ ))?
+ }
}
}
| 2023-10-19T03:44:35Z |
## Description
<!-- https://github.com/juspay/hyperswitch/issues/2275 -->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cc0b42263257b6cf6c7f94350442a74d3c02750b | [
"crates/router/src/connector/nexinets/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2646 | Bug: [FEATURE] Add custom-headers support for Rustman
### Feature Description
This will open up wide range of possibility for all the developers out there to add custom headers of their wish to test out new things and what not?
### Possible Implementation
Pass the headers in the form of a key-value pair in the run command itself such that it injects the value to the `pre-request script` of the collection dir such that after the completion, it should restore the file to its original form.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/test_utils/README.md b/crates/test_utils/README.md
index 1e92174b333..2edbc7104c2 100644
--- a/crates/test_utils/README.md
+++ b/crates/test_utils/README.md
@@ -28,9 +28,16 @@ Required fields:
Optional fields:
+- `--delay` -- To add a delay between requests in milliseconds.
+ - Maximum delay is 4294967295 milliseconds or 4294967.295 seconds or 71616 minutes or 1193.6 hours or 49.733 days
+ - Example: `--delay 1000` (for 1 second delay)
- `--folder` -- To run individual folders in the collection
- Use double quotes to specify folder name. If you wish to run multiple folders, separate them with a comma (`,`)
- Example: `--folder "QuickStart"` or `--folder "Health check,QuickStart"`
+- `--header` -- If you wish to add custom headers to the requests, you can pass them as a string
+ - Example: `--header "key:value"`
+ - If you want to pass multiple custom headers, you can pass multiple `--header` flags
+ - Example: `--header "key1:value1" --header "key2:value2"`
- `--verbose` -- A boolean to print detailed logs (requests and responses)
**Note:** Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository.
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs
index 637122e468e..22c91e063d8 100644
--- a/crates/test_utils/src/main.rs
+++ b/crates/test_utils/src/main.rs
@@ -3,10 +3,10 @@ use std::process::{exit, Command};
use test_utils::newman_runner;
fn main() {
- let mut newman_command: Command = newman_runner::command_generate();
+ let mut runner = newman_runner::generate_newman_command();
// Execute the newman command
- let output = newman_command.spawn();
+ let output = runner.newman_command.spawn();
let mut child = match output {
Ok(child) => child,
Err(err) => {
@@ -16,6 +16,30 @@ fn main() {
};
let status = child.wait();
+ if runner.file_modified_flag {
+ let git_status = Command::new("git")
+ .args([
+ "restore",
+ format!("{}/event.prerequest.js", runner.collection_path).as_str(),
+ ])
+ .output();
+
+ match git_status {
+ Ok(output) => {
+ if output.status.success() {
+ let stdout_str = String::from_utf8_lossy(&output.stdout);
+ println!("Git command executed successfully: {stdout_str}");
+ } else {
+ let stderr_str = String::from_utf8_lossy(&output.stderr);
+ eprintln!("Git command failed with error: {stderr_str}");
+ }
+ }
+ Err(e) => {
+ eprintln!("Error running Git: {e}");
+ }
+ }
+ }
+
let exit_code = match status {
Ok(exit_status) => {
if exit_status.success() {
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index c51556f8f25..af7fb559281 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -1,22 +1,34 @@
-use std::{env, process::Command};
+use std::{
+ env,
+ fs::OpenOptions,
+ io::{self, Write},
+ path::Path,
+ process::Command,
+};
use clap::{arg, command, Parser};
use masking::PeekInterface;
use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap};
-
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
struct Args {
/// Admin API Key of the environment
- #[arg(short, long = "admin_api_key")]
+ #[arg(short, long)]
admin_api_key: String,
/// Base URL of the Hyperswitch environment
- #[arg(short, long = "base_url")]
+ #[arg(short, long)]
base_url: String,
/// Name of the connector
- #[arg(short, long = "connector_name")]
+ #[arg(short, long)]
connector_name: String,
+ /// Custom headers
+ #[arg(short = 'H', long = "header")]
+ custom_headers: Option<Vec<String>>,
+ /// Minimum delay in milliseconds to be added before sending a request
+ /// By default, 7 milliseconds will be the delay
+ #[arg(short, long, default_value_t = 7)]
+ delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
@@ -25,6 +37,12 @@ struct Args {
verbose: bool,
}
+pub struct ReturnArgs {
+ pub newman_command: Command,
+ pub file_modified_flag: bool,
+ pub collection_path: String,
+}
+
// Just by the name of the connector, this function generates the name of the collection dir
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
@@ -32,7 +50,29 @@ fn get_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
-pub fn command_generate() -> Command {
+// This function currently allows you to add only custom headers.
+// In future, as we scale, this can be modified based on the need
+fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
+where
+ T: AsRef<Path> + std::fmt::Debug,
+ U: AsRef<str> + std::fmt::Debug,
+{
+ let file_name = "event.prerequest.js";
+ let file_path = dir.as_ref().join(file_name);
+
+ // Open the file in write mode or create it if it doesn't exist
+ let mut file = OpenOptions::new()
+ .write(true)
+ .append(true)
+ .create(true)
+ .open(file_path)?;
+
+ write!(file, "\n{:#?}", content_to_insert)?;
+
+ Ok(())
+}
+
+pub fn generate_newman_command() -> ReturnArgs {
let args = Args::parse();
let connector_name = args.connector_name;
@@ -129,7 +169,10 @@ pub fn command_generate() -> Command {
]);
}
- newman_command.arg("--delay-request").arg("7"); // 7 milli seconds delay
+ newman_command.args([
+ "--delay-request",
+ format!("{}", &args.delay_request).as_str(),
+ ]);
newman_command.arg("--color").arg("on");
@@ -151,5 +194,24 @@ pub fn command_generate() -> Command {
newman_command.arg("--verbose");
}
- newman_command
+ let mut modified = false;
+ if let Some(headers) = &args.custom_headers {
+ for header in headers {
+ if let Some((key, value)) = header.split_once(':') {
+ let content_to_insert =
+ format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
+ if insert_content(&collection_path, &content_to_insert).is_ok() {
+ modified = true;
+ }
+ } else {
+ eprintln!("Invalid header format: {}", header);
+ }
+ }
+ }
+
+ ReturnArgs {
+ newman_command,
+ file_modified_flag: modified,
+ collection_path,
+ }
}
| 2023-10-18T17:58:48Z |
## Description
<!-- Describe your changes in detail -->
Closes #2646
This PR as usual, narrows the main aim of rustman by making specific to Hyperswitch. With this, you should now be able to:
- Set delay between each request sent as per your own wish while default being `7` milliseconds
- Pass in custom-headers of your wish in run time
### How custom-headers works
Custom headers inject the headers that you pass in command line into the `event.prerequest.js` file and sets a flag to `true`. After the collection is run, it checks the flag and depending on that, it will `git checkout HEAD -- <collection_name>/event.prerequest.js` to restore the file to same as before.
We can also pass `-e environment.json` where you pass in custom headers but that requires some significant changes to be done to the collections to support that.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This will allow us to pass different headers in run-time to test new things and also allow you to set delay of your wish. You can now set the delay to `100000000000` and wait for ages to run a single test :D
# | cdca284b2a7a77cb22074fa8b3b380a088c10f00 |
Command used: (Custom headers taken from #2116)
Delay set to 0.5 seconds
```sh
cargo run --bin test_utils -- --base_url=http://127.0.0.1:8080 --admin_api_key=test_admin --connector_name=stripe --folder "QuickStart" --header "payment_confirm_source:merchant_server" --header "another_header_key:and_its_value" --delay_request 4294967295
```
In run-time, we can see the custom-headers being injected here:


Value being stored in DB:

Ran Stripe Collection:
<img width="511" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/aaefe649-f782-47a9-9166-d6bec893c52c">
| [
"crates/test_utils/README.md",
"crates/test_utils/src/main.rs",
"crates/test_utils/src/newman_runner.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2324 | Bug: [FEATURE]: [Bambora] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index bfcd9846292..e686186c901 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -214,7 +214,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(pg_response.order_number.to_string()),
}),
..item.data
}),
@@ -238,7 +238,9 @@ impl<F, T>
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ item.data.connector_request_reference_id.to_string(),
+ ),
}),
..item.data
})
| 2023-10-18T17:09:58Z |
## Description
The `connector_response_reference_id` parameter has been set for the Bambora Payment Solutions for uniform reference and transaction tracking.
### File Changes
- [x] This PR modifies the Bambora Transformers file.
**Location- router/src/connector/bambora/transformers.rs**
## Motivation and Context
This PR was raised so that it Fixes #2324 !
# | 03b6eaebeccd628115b8f4c52aa8645abbccdd29 | - **I ran the following command, and all the errors were addressed properly, and the build was successful.**
```bash
cargo clippy --all-features
```

- The code changes were formatted with the following command to fix styling issues.
```bash
cargo +nightly fmt
```
| [
"crates/router/src/connector/bambora/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2930 | Bug: [FEATURE]: Add partner flow for PayPal
### Feature Description
PayPal offers an onboarding flow, where merchants can be onboarded directly from a partner account. But for that, we need to change the authentication logic for PayPal request.
We should be able to take a 3rd field in the connector_account_details. So we need to support SignatureKey as well.
### Possible Implementation
Add support for SignatureKey
### 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/paypal.rs b/crates/router/src/connector/paypal.rs
index e514ebbed2f..0e8cff8c056 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -5,10 +5,10 @@ use base64::Engine;
use common_utils::ext_traits::ByteSliceExt;
use diesel_models::enums;
use error_stack::{IntoReport, ResultExt};
-use masking::PeekInterface;
+use masking::{ExposeInterface, PeekInterface, Secret};
use transformers as paypal;
-use self::transformers::{PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType};
+use self::transformers::{auth_headers, PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType};
use super::utils::PaymentsCompleteAuthorizeRequestData;
use crate::{
configs::settings,
@@ -31,7 +31,7 @@ use crate::{
self,
api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource},
transformers::ForeignFrom,
- ErrorResponse, Response,
+ ConnectorAuthType, ErrorResponse, Response,
},
utils::{self, BytesExt},
};
@@ -110,8 +110,8 @@ where
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let key = &req.attempt_id;
-
- Ok(vec![
+ let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
+ let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -121,17 +121,57 @@ where
format!("Bearer {}", access_token.token.peek()).into_masked(),
),
(
- "Prefer".to_string(),
+ auth_headers::PREFER.to_string(),
"return=representation".to_string().into(),
),
(
- "PayPal-Request-Id".to_string(),
+ auth_headers::PAYPAL_REQUEST_ID.to_string(),
key.to_string().into_masked(),
),
- ])
+ ];
+ if let Ok(paypal::PaypalConnectorCredentials::PartnerIntegration(credentials)) =
+ auth.get_credentials()
+ {
+ let auth_assertion_header =
+ construct_auth_assertion_header(&credentials.payer_id, &credentials.client_id);
+ headers.extend(vec![
+ (
+ auth_headers::PAYPAL_AUTH_ASSERTION.to_string(),
+ auth_assertion_header.to_string().into_masked(),
+ ),
+ (
+ auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
+ "HyperSwitchPPCP_SP".to_string().into(),
+ ),
+ ])
+ } else {
+ headers.extend(vec![(
+ auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
+ "HyperSwitchlegacy_Ecom".to_string().into(),
+ )])
+ }
+ Ok(headers)
}
}
+fn construct_auth_assertion_header(
+ payer_id: &Secret<String>,
+ client_id: &Secret<String>,
+) -> String {
+ let algorithm = consts::BASE64_ENGINE
+ .encode("{\"alg\":\"none\"}")
+ .to_string();
+ let merchant_credentials = format!(
+ "{{\"iss\":\"{}\",\"payer_id\":\"{}\"}}",
+ client_id.clone().expose(),
+ payer_id.clone().expose()
+ );
+ let encoded_credentials = consts::BASE64_ENGINE
+ .encode(merchant_credentials)
+ .to_string();
+ format!("{algorithm}.{encoded_credentials}.")
+}
+
impl ConnectorCommon for Paypal {
fn id(&self) -> &'static str {
"paypal"
@@ -151,14 +191,14 @@ impl ConnectorCommon for Paypal {
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
+ auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth: paypal::PaypalAuthType = auth_type
- .try_into()
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let auth = paypal::PaypalAuthType::try_from(auth_type)?;
+ let credentials = auth.get_credentials()?;
+
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.api_key.into_masked(),
+ credentials.get_client_secret().into_masked(),
)])
}
@@ -260,15 +300,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
req: &types::RefreshTokenRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth: paypal::PaypalAuthType = (&req.connector_auth_type)
- .try_into()
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
-
- let auth_id = auth
- .key1
- .zip(auth.api_key)
- .map(|(key1, api_key)| format!("{}:{}", key1, api_key));
- let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id.peek()));
+ let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
+ let credentials = auth.get_credentials()?;
+ let auth_val = credentials.generate_authorization_value();
Ok(vec![
(
@@ -998,15 +1032,9 @@ impl
>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth: paypal::PaypalAuthType = (&req.connector_auth_type)
- .try_into()
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
-
- let auth_id = auth
- .key1
- .zip(auth.api_key)
- .map(|(key1, api_key)| format!("{}:{}", key1, api_key));
- let auth_val = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id.peek()));
+ let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
+ let credentials = auth.get_credentials()?;
+ let auth_val = credentials.generate_authorization_value();
Ok(vec![
(
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 5468c6bb806..d023077ff00 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1,7 +1,8 @@
use api_models::{enums, payments::BankRedirectData};
+use base64::Engine;
use common_utils::errors::CustomResult;
use error_stack::{IntoReport, ResultExt};
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
@@ -11,10 +12,11 @@ use crate::{
self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData,
BankRedirectBillingData, CardData, PaymentsAuthorizeRequestData,
},
+ consts,
core::errors,
services,
types::{
- self, api, storage::enums as storage_enums, transformers::ForeignFrom,
+ self, api, storage::enums as storage_enums, transformers::ForeignFrom, ConnectorAuthType,
VerifyWebhookSourceResponseData,
},
};
@@ -57,6 +59,12 @@ mod webhook_headers {
pub const PAYPAL_CERT_URL: &str = "paypal-cert-url";
pub const PAYPAL_AUTH_ALGO: &str = "paypal-auth-algo";
}
+pub mod auth_headers {
+ pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id";
+ pub const PREFER: &str = "Prefer";
+ pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id";
+ pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion";
+}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
@@ -72,19 +80,111 @@ pub struct OrderAmount {
pub value: String,
}
+#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
+pub struct OrderRequestAmount {
+ pub currency_code: storage_enums::Currency,
+ pub value: String,
+ pub breakdown: AmountBreakdown,
+}
+
+impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for OrderRequestAmount {
+ fn from(item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+ Self {
+ currency_code: item.router_data.request.currency,
+ value: item.amount.to_owned(),
+ breakdown: AmountBreakdown {
+ item_total: OrderAmount {
+ currency_code: item.router_data.request.currency,
+ value: item.amount.to_owned(),
+ },
+ },
+ }
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
+pub struct AmountBreakdown {
+ item_total: OrderAmount,
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct PurchaseUnitRequest {
reference_id: Option<String>, //reference for an item in purchase_units
invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions.
- amount: OrderAmount,
+ amount: OrderRequestAmount,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ payee: Option<Payee>,
+ shipping: Option<ShippingAddress>,
+ items: Vec<ItemDetails>,
}
-#[derive(Debug, Serialize)]
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct Payee {
+ merchant_id: Secret<String>,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct ItemDetails {
+ name: String,
+ quantity: u16,
+ unit_amount: OrderAmount,
+}
+
+impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetails {
+ fn from(item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+ Self {
+ name: format!(
+ "Payment for invoice {}",
+ item.router_data.connector_request_reference_id
+ ),
+ quantity: 1,
+ unit_amount: OrderAmount {
+ currency_code: item.router_data.request.currency,
+ value: item.amount.to_string(),
+ },
+ }
+ }
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct Address {
address_line_1: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country_code: api_models::enums::CountryAlpha2,
+ admin_area_2: Option<String>,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct ShippingAddress {
+ address: Option<Address>,
+ name: Option<ShippingName>,
+}
+
+impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAddress {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ address: get_address_info(item.router_data.address.shipping.as_ref())?,
+ name: Some(ShippingName {
+ full_name: item
+ .router_data
+ .address
+ .shipping
+ .as_ref()
+ .and_then(|inner_data| inner_data.address.as_ref())
+ .and_then(|inner_data| inner_data.first_name.clone()),
+ }),
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct ShippingName {
+ full_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
@@ -124,6 +224,22 @@ pub struct RedirectRequest {
pub struct ContextStruct {
return_url: Option<String>,
cancel_url: Option<String>,
+ user_action: Option<UserAction>,
+ shipping_preference: ShippingPreference,
+}
+
+#[derive(Debug, Serialize)]
+pub enum UserAction {
+ #[serde(rename = "PAY_NOW")]
+ PayNow,
+}
+
+#[derive(Debug, Serialize)]
+pub enum ShippingPreference {
+ #[serde(rename = "SET_PROVIDED_ADDRESS")]
+ SetProvidedAddress,
+ #[serde(rename = "GET_FROM_FILE")]
+ GetFromFile,
}
#[derive(Debug, Serialize)]
@@ -158,6 +274,7 @@ fn get_address_info(
country_code: address.get_country()?.to_owned(),
address_line_1: address.line1.clone(),
postal_code: address.zip.clone(),
+ admin_area_2: address.city.clone(),
}),
None => None,
};
@@ -180,6 +297,12 @@ fn get_payment_source(
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
+ shipping_preference: if item.address.shipping.is_some() {
+ ShippingPreference::SetProvidedAddress
+ } else {
+ ShippingPreference::GetFromFile
+ },
+ user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Giropay {
@@ -194,6 +317,12 @@ fn get_payment_source(
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
+ shipping_preference: if item.address.shipping.is_some() {
+ ShippingPreference::SetProvidedAddress
+ } else {
+ ShippingPreference::GetFromFile
+ },
+ user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Ideal {
@@ -208,6 +337,12 @@ fn get_payment_source(
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
+ shipping_preference: if item.address.shipping.is_some() {
+ ShippingPreference::SetProvidedAddress
+ } else {
+ ShippingPreference::GetFromFile
+ },
+ user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Sofort {
@@ -220,6 +355,12 @@ fn get_payment_source(
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
+ shipping_preference: if item.address.shipping.is_some() {
+ ShippingPreference::SetProvidedAddress
+ } else {
+ ShippingPreference::GetFromFile
+ },
+ user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::BancontactCard { .. }
@@ -247,11 +388,24 @@ fn get_payment_source(
}
}
+fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> {
+ auth_type
+ .get_credentials()
+ .ok()
+ .and_then(|credentials| credentials.get_payer_id())
+ .map(|payer_id| Payee {
+ merchant_id: payer_id,
+ })
+}
+
impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
+ let paypal_auth: PaypalAuthType =
+ PaypalAuthType::try_from(&item.router_data.connector_auth_type)?;
+ let payee = get_payee(&paypal_auth);
match item.router_data.request.payment_method_data {
api_models::payments::PaymentMethodData::Card(ref ccard) => {
let intent = if item.router_data.request.is_auto_capture()? {
@@ -259,18 +413,20 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
} else {
PaypalPaymentIntent::Authorize
};
- let amount = OrderAmount {
- currency_code: item.router_data.request.currency,
- value: item.amount.to_owned(),
- };
+ let amount = OrderRequestAmount::from(item);
let connector_request_reference_id =
item.router_data.connector_request_reference_id.clone();
+ let shipping_address = ShippingAddress::try_from(item)?;
+ let item_details = vec![ItemDetails::from(item)];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_request_reference_id.clone()),
custom_id: Some(connector_request_reference_id.clone()),
invoice_id: Some(connector_request_reference_id),
amount,
+ payee,
+ shipping: Some(shipping_address),
+ items: item_details,
}];
let card = item.router_data.request.get_card()?;
let expiry = Some(card.get_expiry_date_as_yyyymm("-"));
@@ -306,25 +462,29 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
} else {
PaypalPaymentIntent::Authorize
};
- let amount = OrderAmount {
- currency_code: item.router_data.request.currency,
- value: item.amount.to_owned(),
- };
+ let amount = OrderRequestAmount::from(item);
let connector_req_reference_id =
item.router_data.connector_request_reference_id.clone();
+ let shipping_address = ShippingAddress::try_from(item)?;
+ let item_details = vec![ItemDetails::from(item)];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_req_reference_id.clone()),
custom_id: Some(connector_req_reference_id.clone()),
invoice_id: Some(connector_req_reference_id),
amount,
+ payee,
+ shipping: Some(shipping_address),
+ items: item_details,
}];
let payment_source =
Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {
experience_context: ContextStruct {
return_url: item.router_data.request.complete_authorize_url.clone(),
cancel_url: item.router_data.request.complete_authorize_url.clone(),
+ shipping_preference: ShippingPreference::SetProvidedAddress,
+ user_action: Some(UserAction::PayNow),
},
}));
@@ -374,18 +534,20 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
connector: "Paypal".to_string(),
})?
};
- let amount = OrderAmount {
- currency_code: item.router_data.request.currency,
- value: item.amount.to_owned(),
- };
+ let amount = OrderRequestAmount::from(item);
let connector_req_reference_id =
item.router_data.connector_request_reference_id.clone();
+ let shipping_address = ShippingAddress::try_from(item)?;
+ let item_details = vec![ItemDetails::from(item)];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_req_reference_id.clone()),
custom_id: Some(connector_req_reference_id.clone()),
invoice_id: Some(connector_req_reference_id),
amount,
+ payee,
+ shipping: Some(shipping_address),
+ items: item_details,
}];
let payment_source =
Some(get_payment_source(item.router_data, bank_redirection_data)?);
@@ -604,19 +766,98 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalAuthUpdateResponse, T, typ
}
#[derive(Debug)]
-pub struct PaypalAuthType {
- pub(super) api_key: Secret<String>,
- pub(super) key1: Secret<String>,
+pub enum PaypalAuthType {
+ TemporaryAuth,
+ AuthWithDetails(PaypalConnectorCredentials),
+}
+
+#[derive(Debug)]
+pub enum PaypalConnectorCredentials {
+ StandardIntegration(StandardFlowCredentials),
+ PartnerIntegration(PartnerFlowCredentials),
}
-impl TryFrom<&types::ConnectorAuthType> for PaypalAuthType {
+impl PaypalConnectorCredentials {
+ pub fn get_client_id(&self) -> Secret<String> {
+ match self {
+ Self::StandardIntegration(item) => item.client_id.clone(),
+ Self::PartnerIntegration(item) => item.client_id.clone(),
+ }
+ }
+
+ pub fn get_client_secret(&self) -> Secret<String> {
+ match self {
+ Self::StandardIntegration(item) => item.client_secret.clone(),
+ Self::PartnerIntegration(item) => item.client_secret.clone(),
+ }
+ }
+
+ pub fn get_payer_id(&self) -> Option<Secret<String>> {
+ match self {
+ Self::StandardIntegration(_) => None,
+ Self::PartnerIntegration(item) => Some(item.payer_id.clone()),
+ }
+ }
+
+ pub fn generate_authorization_value(&self) -> String {
+ let auth_id = format!(
+ "{}:{}",
+ self.get_client_id().expose(),
+ self.get_client_secret().expose(),
+ );
+ format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id))
+ }
+}
+
+#[derive(Debug)]
+pub struct StandardFlowCredentials {
+ pub(super) client_id: Secret<String>,
+ pub(super) client_secret: Secret<String>,
+}
+
+#[derive(Debug)]
+pub struct PartnerFlowCredentials {
+ pub(super) client_id: Secret<String>,
+ pub(super) client_secret: Secret<String>,
+ pub(super) payer_id: Secret<String>,
+}
+
+impl PaypalAuthType {
+ pub fn get_credentials(
+ &self,
+ ) -> CustomResult<&PaypalConnectorCredentials, errors::ConnectorError> {
+ match self {
+ Self::TemporaryAuth => Err(errors::ConnectorError::InvalidConnectorConfig {
+ config: "TemporaryAuth found in connector_account_details",
+ }
+ .into()),
+ Self::AuthWithDetails(credentials) => Ok(credentials),
+ }
+ }
+}
+
+impl TryFrom<&ConnectorAuthType> for PaypalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
- api_key: api_key.to_owned(),
- key1: key1.to_owned(),
- }),
+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails(
+ PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials {
+ client_id: key1.to_owned(),
+ client_secret: api_key.to_owned(),
+ }),
+ )),
+ types::ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => Ok(Self::AuthWithDetails(
+ PaypalConnectorCredentials::PartnerIntegration(PartnerFlowCredentials {
+ client_id: key1.to_owned(),
+ client_secret: api_key.to_owned(),
+ payer_id: api_secret.to_owned(),
+ }),
+ )),
+ types::ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
| 2023-10-18T14:16:43Z |
## Description
<!-- Describe your changes in detail -->
- Make PayPal support `SignatureKey` `auth_type`.
- Add extra fields in `orders` request.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 PayPal onboarding flow.
#
### Payment Connector - Create
Paypal now supports `TemporaryAuth` in the `auth_type`. You can find more details about this in this PR #2833.
Paypal also support `SignatureKey` in the `auth_type`.
```
curl --location 'http://localhost:8080/account/merchant_1700133263/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "paypal",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "client_secret",
"key1": "client_id",
"api_secret": "partner_id"
},
"status": "active",
"disabled": false
}'
```
If all the fields are passed correctly you will a normal mca response. | 938b63a1fceb87b4aae4211dac4d051e024028b1 |
Postman.
### Payment Connector - Create
Paypal now supports `TemporaryAuth` in the `auth_type`. You can find more details about this in this PR #2833.
Paypal also support `SignatureKey` in the `auth_type`.
```
curl --location 'http://localhost:8080/account/merchant_1700133263/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "paypal",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "client_secret",
"key1": "client_id",
"api_secret": "partner_id"
},
"status": "active",
"disabled": false
}'
```
If all the fields are passed correctly you will a normal mca response.
| [
"crates/router/src/connector/paypal.rs",
"crates/router/src/connector/paypal/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2319 | Bug: [FEATURE]: [Tsys] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index d8516c8293b..83134568c05 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -34,6 +34,7 @@ pub struct TsysPaymentAuthSaleRequest {
cardholder_authentication_method: String,
#[serde(rename = "developerID")]
developer_id: Secret<String>,
+ order_number: String,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
@@ -57,6 +58,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
terminal_operating_environment: "ON_MERCHANT_PREMISES_ATTENDED".to_string(),
cardholder_authentication_method: "NOT_AUTHENTICATED".to_string(),
developer_id: connector_auth.developer_id,
+ order_number: item.connector_request_reference_id.clone(),
};
if item.request.is_auto_capture()? {
Ok(Self::Sale(auth_data))
| 2023-10-18T13:20:35Z |
## Description
The `connector_request_reference_id` parameter has been set for the Tsys Payment Solutions for uniform reference and transaction tracking.
### File Changes
- [x] This PR modifies the Tsys Transformers file.
**Location- router/src/connector/tsys/transformers.rs**
## Motivation and Context
This PR was raised so that it Fixes #2319 !
# | 6cf8f0582cfa4f6a58c67a868cb67846970b3835 | - **I ran the following command, and all the errors were addressed properly, and the build was successful.**
```bash
cargo clippy --all-features
```

- The code changes were formatted with the following command to fix styling issues.
```bash
cargo +nightly fmt
```
| [
"crates/router/src/connector/tsys/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2222 | Bug: [FEATURE]: [Cybersource] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index d1ad36b26d1..0a13aa0cf14 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -93,6 +93,10 @@ impl ConnectorCommon for Cybersource {
connectors.cybersource.base_url.as_ref()
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn build_error_response(
&self,
res: types::Response,
@@ -468,7 +472,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = cybersource::CybersourcePaymentsRequest::try_from(req)?;
+ let connector_router_data = cybersource::CybersourceRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_request =
+ cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?;
let cybersource_payments_request = types::RequestBody::log_and_get_request_body(
&connector_request,
utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 5a3060f99eb..55507e4f490 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -15,6 +15,37 @@ use crate::{
},
};
+#[derive(Debug, Serialize)]
+pub struct CybersourceRouterData<T> {
+ pub amount: String,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for CybersourceRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (currency_unit, currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsRequest {
@@ -109,27 +140,33 @@ fn build_bill_to(
})
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest {
+impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
+ for CybersourcePaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- match item.request.payment_method_data.clone() {
+ fn try_from(
+ item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
api::PaymentMethodData::Card(ccard) => {
- let phone = item.get_billing_phone()?;
+ let phone = item.router_data.get_billing_phone()?;
let phone_number = phone.get_number()?;
let country_code = phone.get_country_code()?;
let number_with_code =
Secret::new(format!("{}{}", country_code, phone_number.peek()));
let email = item
+ .router_data
.request
.email
.clone()
.ok_or_else(utils::missing_field_err("email"))?;
- let bill_to = build_bill_to(item.get_billing()?, email, number_with_code)?;
+ let bill_to =
+ build_bill_to(item.router_data.get_billing()?, email, number_with_code)?;
let order_information = OrderInformationWithBill {
amount_details: Amount {
- total_amount: item.request.amount.to_string(),
- currency: item.request.currency.to_string().to_uppercase(),
+ total_amount: item.amount.to_owned(),
+ currency: item.router_data.request.currency.to_string().to_uppercase(),
},
bill_to,
};
@@ -145,14 +182,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest
let processing_information = ProcessingInformation {
capture: matches!(
- item.request.capture_method,
+ item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
),
capture_options: None,
};
let client_reference_information = ClientReferenceInformation {
- code: Some(item.connector_request_reference_id.clone()),
+ code: Some(item.router_data.connector_request_reference_id.clone()),
};
Ok(Self {
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 3a8cae3a631..6f1566a35b0 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1077,7 +1077,7 @@ pub fn get_amount_as_string(
currency: diesel_models::enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
- types::api::CurrencyUnit::Minor => amount.to_string(),
+ types::api::CurrencyUnit::Minor => to_currency_lower_unit(amount.to_string(), currency)?,
types::api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
| 2023-10-18T09:03:55Z |
## Description
This PR implements `get_currency_unit` for cybersource to convert payments from `Base` to `Minor` it also implements router data to handle the conversion.
## Motivation and Context
Closes #2222
# | 664093dc79743203196d912c17570885718b1c02 | I tested by sending a payment request & verifying the amount is showed in minor units in the cybersource console

| [
"crates/router/src/connector/cybersource.rs",
"crates/router/src/connector/cybersource/transformers.rs",
"crates/router/src/connector/utils.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2270 | Bug: [REFACTOR]: [Forte] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index bc7c55c4f87..7851608d11b 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -101,9 +101,23 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
card,
})
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment Method".to_string(),
- ))?,
+ api_models::payments::PaymentMethodData::CardRedirect(_)
+ | api_models::payments::PaymentMethodData::Wallet(_)
+ | api_models::payments::PaymentMethodData::PayLater(_)
+ | api_models::payments::PaymentMethodData::BankRedirect(_)
+ | api_models::payments::PaymentMethodData::BankDebit(_)
+ | api_models::payments::PaymentMethodData::BankTransfer(_)
+ | api_models::payments::PaymentMethodData::Crypto(_)
+ | api_models::payments::PaymentMethodData::MandatePayment {}
+ | api_models::payments::PaymentMethodData::Reward {}
+ | api_models::payments::PaymentMethodData::Upi(_)
+ | api_models::payments::PaymentMethodData::Voucher(_)
+ | api_models::payments::PaymentMethodData::GiftCard(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Forte",
+ })?
+ }
}
}
}
| 2023-10-18T08:56:41Z |
## Description
- Addresses Issue #2270
- Modified `crates/router/src/connector/forte/transformers.rs`
- Convert `NotImplemented` to `NotSupported` in default case
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 6cf8f0582cfa4f6a58c67a868cb67846970b3835 | [
"crates/router/src/connector/forte/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2269 | Bug: [REFACTOR]: [Dlocal] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 8558836372e..18a6ad46755 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -118,7 +118,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest {
};
Ok(payment_request)
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ crate::connector::utils::get_unimplemented_payment_method_error_message("Dlocal"),
+ ))?,
}
}
}
| 2023-10-18T08:01:14Z |
## Description
removed all the default case in dlocal and handle all the missing cases
closes #2269
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | a1472c6b78afa819cbe026a7db1e0c2b9016715e | [
"crates/router/src/connector/dlocal/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2223 | Bug: [FEATURE]: [Dlocal] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs
index 90be2399ba0..b706d694a3d 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/router/src/connector/dlocal.rs
@@ -109,6 +109,10 @@ impl ConnectorCommon for Dlocal {
"dlocal"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -207,7 +211,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = dlocal::DlocalPaymentsRequest::try_from(req)?;
+ let connector_router_data = dlocal::DlocalRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_request = dlocal::DlocalPaymentsRequest::try_from(&connector_router_data)?;
let dlocal_payments_request = types::RequestBody::log_and_get_request_body(
&connector_request,
utils::Encode::<dlocal::DlocalPaymentsRequest>::encode_to_string_of_json,
@@ -508,10 +518,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = dlocal::RefundRequest::try_from(req)?;
+ let connector_router_data = dlocal::DlocalRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_request = dlocal::DlocalRefundRequest::try_from(&connector_router_data)?;
let dlocal_refund_request = types::RequestBody::log_and_get_request_body(
&connector_request,
- utils::Encode::<dlocal::RefundRequest>::encode_to_string_of_json,
+ utils::Encode::<dlocal::DlocalRefundRequest>::encode_to_string_of_json,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some(dlocal_refund_request))
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 8558836372e..87562fa3344 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -51,6 +51,37 @@ pub enum PaymentMethodFlow {
ReDirect,
}
+#[derive(Debug, Serialize)]
+pub struct DlocalRouterData<T> {
+ pub amount: i64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for DlocalRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsRequest {
pub amount: i64,
@@ -66,22 +97,24 @@ pub struct DlocalPaymentsRequest {
pub description: Option<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest {
+impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let email = item.request.email.clone();
- let address = item.get_billing_address()?;
+ fn try_from(
+ item: &DlocalRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let email = item.router_data.request.email.clone();
+ let address = item.router_data.get_billing_address()?;
let country = address.get_country()?;
let name = get_payer_name(address);
- match item.request.payment_method_data {
+ match item.router_data.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => {
let should_capture = matches!(
- item.request.capture_method,
+ item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
);
let payment_request = Self {
- amount: item.request.amount,
- currency: item.request.currency,
+ amount: item.amount,
+ currency: item.router_data.request.currency,
payment_method_id: PaymentMethodId::Card,
payment_method_flow: PaymentMethodFlow::Direct,
country: country.to_string(),
@@ -99,22 +132,28 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest {
expiration_year: ccard.card_exp_year.clone(),
capture: should_capture.to_string(),
installments_id: item
+ .router_data
.request
.mandate_id
.as_ref()
.map(|ids| ids.mandate_id.clone()),
// [#595[FEATURE] Pass Mandate history information in payment flows/request]
- installments: item.request.mandate_id.clone().map(|_| "1".to_string()),
+ installments: item
+ .router_data
+ .request
+ .mandate_id
+ .clone()
+ .map(|_| "1".to_string()),
}),
- order_id: item.payment_id.clone(),
- three_dsecure: match item.auth_type {
+ order_id: item.router_data.payment_id.clone(),
+ three_dsecure: match item.router_data.auth_type {
diesel_models::enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
}
diesel_models::enums::AuthenticationType::NoThreeDs => None,
},
- callback_url: Some(item.request.get_router_return_url()?),
- description: item.description.clone(),
+ callback_url: Some(item.router_data.request.get_router_return_url()?),
+ description: item.router_data.description.clone(),
};
Ok(payment_request)
}
@@ -399,22 +438,24 @@ impl<F, T>
// REFUND :
#[derive(Default, Debug, Serialize)]
-pub struct RefundRequest {
+pub struct DlocalRefundRequest {
pub amount: String,
pub payment_id: String,
pub currency: enums::Currency,
pub id: String,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest {
+impl<F> TryFrom<&DlocalRouterData<&types::RefundsRouterData<F>>> for DlocalRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let amount_to_refund = item.request.refund_amount.to_string();
+ fn try_from(
+ item: &DlocalRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let amount_to_refund = item.router_data.request.refund_amount.to_string();
Ok(Self {
amount: amount_to_refund,
- payment_id: item.request.connector_transaction_id.clone(),
- currency: item.request.currency,
- id: item.request.refund_id.clone(),
+ payment_id: item.router_data.request.connector_transaction_id.clone(),
+ currency: item.router_data.request.currency,
+ id: item.router_data.request.refund_id.clone(),
})
}
}
| 2023-10-17T13:50:19Z |
## Description
- Addressing Issue: #2223
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `dlocal.rs`
- Implement `get_currency_unit` function
- Modify `ConnectorIntegration` implementations for `Dlocal`
- `dlocal/transformers.rs`
- Implement `DlocalRouterData<T>` structure and functionality
- Modify implementation for `DlocalPaymentsRequest`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 6cf8f0582cfa4f6a58c67a868cb67846970b3835 | [
"crates/router/src/connector/dlocal.rs",
"crates/router/src/connector/dlocal/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2334 | Bug: [FEATURE]: [Klarna] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 31e356d4765..563410ee99d 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -159,12 +159,14 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
}),
status: item.response.fraud_status.into(),
..item.data
| 2023-10-17T13:15:34Z |
## 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).
-->
Resolves #2334
# | 67d006272158372a4b9ec65cbbe7b2ae8f35eb69 | [
"crates/router/src/connector/klarna/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2598 | Bug: [CI] Add ci workflow for validating hotfix pr
### Feature Description
Add support for creating a new workflow for validating the hotfix pr.
Workflow should be triggered when baseRef is prefixed with hotfix-
### Possible Implementation
Assumption -
Hotfix PR description contains one or more original PR's link
If description contains any issues link, it would be ignored
Validations include -
Among all the Original PR links added in Hotfix PR description, at least one has to satisfy the below conditions
Original PR author should be same as Hotfix PR author
Original PR title should be same as Hotfix PR title
Original PR's baseRef has to be main
Original PR should be merged to main
If no Original PR has been found in description or if above condition doesn't satisfy for even one original PR's, CI check will fail
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | 2023-10-16T07:23:49Z |
## Description
<!-- Describe your changes in detail -->
This PR adds a new workflow for validating the hotfix PR.
Workflow is triggered when baseRef of hotfix PR is prefixed with `hotfix-`
**Assumption** -
* Hotfix PR description contains one or more original PR's link
* If description contains any issues link, it would be ignored
**Validations include** -
Among all the Original PR links added in Hotfix PR description, at least one has to satisfy the below conditions
* Original PR author should be same as Hotfix PR author
* Original PR title should be same as Hotfix PR title
* Original PR's baseRef has to be main
* Original PR should be merged to main
If no Original PR has been found in description or if above condition doesn't satisfy for even one original PR's, CI check will fail
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cecea8718a48b4e896b2bafce0f909ef8d9a6e8a |
CI passing

CI failing because Original PR is not merged

CI failing because Original PR title does not match with hotfix PR title

| [] | ||
juspay/hyperswitch | juspay__hyperswitch-2311 | Bug: [FEATURE]: [OpenNode] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index aa3fae3a516..b367012ca75 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -19,6 +19,7 @@ pub struct OpennodePaymentsRequest {
auto_settle: bool,
success_url: String,
callback_url: String,
+ order_id: String,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest {
@@ -237,6 +238,7 @@ fn get_crypto_specific_payment_data(
auto_settle,
success_url,
callback_url,
+ order_id: item.connector_request_reference_id.clone(),
})
}
| 2023-10-15T19:43:10Z |
## Description
<!-- Describe your changes in detail -->
Use connector_request_reference_id as reference to the connector #2311
## Motivation and Context
To solve inconsistency in RouterData and it solves the Issue #2311
# | 027385eca6e76c5cbe65450f058ececa012d1175 | Need help in doing test?
| [
"crates/router/src/connector/opennode/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2292 | Bug: [FEATURE]: [Authorizedotnet] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented. Please find api documentation for authorizedotnet [here](https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card).
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 20d78729a1b..561723be46c 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -261,6 +261,7 @@ struct TransactionVoidOrCaptureRequest {
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionRequest,
+ ref_id: String,
}
#[derive(Debug, Serialize)]
@@ -332,6 +333,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
create_transaction_request: AuthorizedotnetPaymentsRequest {
merchant_authentication,
transaction_request,
+ ref_id: item.router_data.connector_request_reference_id.clone(),
},
})
}
| 2023-10-15T08:07:18Z | …ference to the connector
## 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).
-->
# | 94947bdb33ca4eb91daad13b2a427592d3b69851 |
Make any Payment for connector Authorizedotnet and see that you are getting "reference_id" field in the logs of payment request.
| [
"crates/router/src/connector/authorizedotnet/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2229 | Bug: [FEATURE]: [IataPay] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs
index 3a813c50cf6..4db2faa2d42 100644
--- a/crates/router/src/connector/iatapay.rs
+++ b/crates/router/src/connector/iatapay.rs
@@ -90,6 +90,10 @@ impl ConnectorCommon for Iatapay {
"application/json"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
connectors.iatapay.base_url.as_ref()
}
@@ -271,7 +275,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = iatapay::IatapayPaymentsRequest::try_from(req)?;
+ let connector_router_data = iatapay::IatapayRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = iatapay::IatapayPaymentsRequest::try_from(&connector_router_data)?;
let iatapay_req = types::RequestBody::log_and_get_request_body(
&req_obj,
Encode::<iatapay::IatapayPaymentsRequest>::encode_to_string_of_json,
@@ -451,7 +461,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = iatapay::IatapayRefundRequest::try_from(req)?;
+ let connector_router_data = iatapay::IatapayRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.payment_amount,
+ req,
+ ))?;
+ let req_obj = iatapay::IatapayRefundRequest::try_from(&connector_router_data)?;
let iatapay_req = types::RequestBody::log_and_get_request_body(
&req_obj,
Encode::<iatapay::IatapayRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index d4731b024c8..7cdfafc858b 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -8,7 +8,7 @@ use crate::{
connector::utils::{self, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData},
core::errors,
services,
- types::{self, api, storage::enums},
+ types::{self, api, storage::enums, PaymentsAuthorizeData},
};
// Every access token will be valid for 5 minutes. It contains grant_type and scope for different type of access, but for our usecases it should be only 'client_credentials' and 'payment' resp(as per doc) for all type of api call.
@@ -26,7 +26,34 @@ impl TryFrom<&types::RefreshTokenRouterData> for IatapayAuthUpdateRequest {
})
}
}
-
+#[derive(Debug, Serialize)]
+pub struct IatapayRouterData<T> {
+ amount: f64,
+ router_data: T,
+}
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for IatapayRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (_currency_unit, _currency, _amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: utils::to_currency_base_unit_asf64(_amount, _currency)?,
+ router_data: item,
+ })
+ }
+}
#[derive(Debug, Deserialize)]
pub struct IatapayAuthUpdateResponse {
pub access_token: Secret<String>,
@@ -80,10 +107,29 @@ pub struct IatapayPaymentsRequest {
payer_info: Option<PayerInfo>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest {
+impl
+ TryFrom<
+ &IatapayRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ >,
+ > for IatapayPaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let payment_method = item.payment_method;
+
+ fn try_from(
+ item: &IatapayRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let payment_method = item.router_data.payment_method;
let country = match payment_method {
PaymentMethod::Upi => "IN".to_string(),
@@ -97,27 +143,26 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest {
| PaymentMethod::BankDebit
| PaymentMethod::Reward
| PaymentMethod::Voucher
- | PaymentMethod::GiftCard => item.get_billing_country()?.to_string(),
+ | PaymentMethod::GiftCard => item.router_data.get_billing_country()?.to_string(),
};
- let return_url = item.get_return_url()?;
- let payer_info = match item.request.payment_method_data.clone() {
+ let return_url = item.router_data.get_return_url()?;
+ let payer_info = match item.router_data.request.payment_method_data.clone() {
api::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo {
token_id: id.switch_strategy(),
}),
_ => None,
};
- let amount =
- utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
let payload = Self {
- merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id,
- merchant_payment_id: Some(item.connector_request_reference_id.clone()),
- amount,
- currency: item.request.currency.to_string(),
+ merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)?
+ .merchant_id,
+ merchant_payment_id: Some(item.router_data.connector_request_reference_id.clone()),
+ amount: item.amount,
+ currency: item.router_data.request.currency.to_string(),
country: country.clone(),
locale: format!("en-{}", country),
redirect_urls: get_redirect_url(return_url),
payer_info,
- notification_url: item.request.get_webhook_url()?,
+ notification_url: item.router_data.request.get_webhook_url()?,
};
Ok(payload)
}
@@ -275,18 +320,19 @@ pub struct IatapayRefundRequest {
pub notification_url: String,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for IatapayRefundRequest {
+impl<F> TryFrom<&IatapayRouterData<&types::RefundsRouterData<F>>> for IatapayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let amount =
- utils::to_currency_base_unit_asf64(item.request.refund_amount, item.request.currency)?;
+ fn try_from(
+ item: &IatapayRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount,
- merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id,
- merchant_refund_id: Some(item.request.refund_id.clone()),
- currency: item.request.currency.to_string(),
- bank_transfer_description: item.request.reason.clone(),
- notification_url: item.request.get_webhook_url()?,
+ amount: item.amount,
+ merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)?
+ .merchant_id,
+ merchant_refund_id: Some(item.router_data.request.refund_id.clone()),
+ currency: item.router_data.request.currency.to_string(),
+ bank_transfer_description: item.router_data.request.reason.clone(),
+ notification_url: item.router_data.request.get_webhook_url()?,
})
}
}
| 2023-10-15T07:21:50Z |
## Description
- Addresses issue #2229
- Modified the files `hyperswitch/crates/router/src/connector/iatapay/transformers.rs` and `hyperswitch/crates/router/src/connector/iatapay.rs`
- Rebased with most recent changes
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | ca77c7ce3c6b806ff60e83725cc4e50855422037 |
We need to create a payment using Iatapay and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/iatapay.rs",
"crates/router/src/connector/iatapay/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2325 | Bug: [FEATURE]: [Bitpay] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index 5af20d6423f..89dd2368b2b 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -134,6 +134,7 @@ pub struct BitpayPaymentResponseData {
pub expiration_time: Option<i64>,
pub current_time: Option<i64>,
pub id: String,
+ pub order_id: Option<String>,
pub low_fee_detected: Option<bool>,
pub display_amount_paid: Option<String>,
pub exception_status: ExceptionStatus,
@@ -162,7 +163,7 @@ impl<F, T>
.data
.url
.map(|x| services::RedirectForm::from((x, services::Method::Get)));
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id);
+ let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = item.response.data.status;
Ok(Self {
status: enums::AttemptStatus::from(attempt_status),
@@ -172,7 +173,11 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .data
+ .order_id
+ .or(Some(item.response.data.id)),
}),
..item.data
})
| 2023-10-15T04:51:11Z |
## Description
<!-- Describe your changes in detail -->
[Relevant documentation](https://developer.bitpay.com/docs/create-invoice#notificationurl)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #2325
# | 4563935372d2cdff3f746fa86a47f1166ffd32ac |
Make any Payment for connector Bitpay and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be null.
| [
"crates/router/src/connector/bitpay/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2272 | Bug: [REFACTOR]: [Iatapay] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 9d4ecdff197..f98798fe5be 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -86,7 +86,18 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest {
let payment_method = item.payment_method;
let country = match payment_method {
PaymentMethod::Upi => "IN".to_string(),
- _ => item.get_billing_country()?.to_string(),
+
+ PaymentMethod::Card
+ | PaymentMethod::CardRedirect
+ | PaymentMethod::PayLater
+ | PaymentMethod::Wallet
+ | PaymentMethod::BankRedirect
+ | PaymentMethod::BankTransfer
+ | PaymentMethod::Crypto
+ | PaymentMethod::BankDebit
+ | PaymentMethod::Reward
+ | PaymentMethod::Voucher
+ | PaymentMethod::GiftCard => item.get_billing_country()?.to_string(),
};
let return_url = item.get_return_url()?;
let payer_info = match item.request.payment_method_data.clone() {
| 2023-10-14T15:42:37Z |
## Description
<!-- Describe your changes in detail -->
- Fix issue https://github.com/juspay/hyperswitch/issues/2272
- Changes to be made : Remove default case handling
- Added all the ```ConnectorAuthType``` (which are not ```auth_type``` ) against the default case
- File **changed: transformers.rs** (crates/router/src/connector/iatapay/transformers.rs)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 5d88dbc92ce470c951717debe246e182b3fe5656 | [
"crates/router/src/connector/iatapay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2274 | Bug: [REFACTOR]: [Multisafepay] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index a8366fadf81..385c85e0aa6 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -229,11 +229,13 @@ impl TryFrom<utils::CardIssuer> for Gateway {
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
- _ => Err(errors::ConnectorError::NotSupported {
- message: issuer.to_string(),
- connector: "Multisafe pay",
+ utils::CardIssuer::DinersClub | utils::CardIssuer::JCB => {
+ Err(errors::ConnectorError::NotSupported {
+ message: issuer.to_string(),
+ connector: "Multisafe pay",
+ }
+ .into())
}
- .into()),
}
}
}
@@ -247,8 +249,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
api::WalletData::GooglePay(_) => Type::Direct,
api::WalletData::PaypalRedirect(_) => Type::Redirect,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
api::PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
@@ -262,8 +287,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
api::PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data {
api::WalletData::GooglePay(_) => Gateway::Googlepay,
api::WalletData::PaypalRedirect(_) => Gateway::Paypal,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
api::PaymentMethodData::PayLater(
@@ -273,8 +321,17 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
},
) => Some(Gateway::Klarna),
api::PaymentMethodData::MandatePayment => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
};
let description = item.get_description()?;
@@ -354,8 +411,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
})))
}
api::WalletData::PaypalRedirect(_) => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::WalletData::AliPayQr(_)
+ | api::WalletData::AliPayRedirect(_)
+ | api::WalletData::AliPayHkRedirect(_)
+ | api::WalletData::MomoRedirect(_)
+ | api::WalletData::KakaoPayRedirect(_)
+ | api::WalletData::GoPayRedirect(_)
+ | api::WalletData::GcashRedirect(_)
+ | api::WalletData::ApplePay(_)
+ | api::WalletData::ApplePayRedirect(_)
+ | api::WalletData::ApplePayThirdPartySdk(_)
+ | api::WalletData::DanaRedirect {}
+ | api::WalletData::GooglePayRedirect(_)
+ | api::WalletData::GooglePayThirdPartySdk(_)
+ | api::WalletData::MbWayRedirect(_)
+ | api::WalletData::MobilePayRedirect(_)
+ | api::WalletData::PaypalSdk(_)
+ | api::WalletData::SamsungPay(_)
+ | api::WalletData::TwintRedirect {}
+ | api::WalletData::VippsRedirect {}
+ | api::WalletData::TouchNGoRedirect(_)
+ | api::WalletData::WeChatPayRedirect(_)
+ | api::WalletData::WeChatPayQr(_)
+ | api::WalletData::CashappQr(_)
+ | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
api::PaymentMethodData::PayLater(ref paylater) => {
@@ -365,15 +445,36 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
billing_email,
..
} => billing_email.clone(),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- ))?,
+ api_models::payments::PayLaterData::KlarnaSdk { token: _ }
+ | api_models::payments::PayLaterData::AffirmRedirect {}
+ | api_models::payments::PayLaterData::AfterpayClearpayRedirect {
+ billing_email: _,
+ billing_name: _,
+ }
+ | api_models::payments::PayLaterData::PayBrightRedirect {}
+ | api_models::payments::PayLaterData::WalleyRedirect {}
+ | api_models::payments::PayLaterData::AlmaRedirect {}
+ | api_models::payments::PayLaterData::AtomeRedirect {} => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "multisafepay",
+ ),
+ ))?
+ }
}),
}))
}
api::PaymentMethodData::MandatePayment => None,
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
};
| 2023-10-14T13:54:31Z |
## Description
Removed all the default case handling in multisafepay and handle all the missing cases.
Closes: #2274
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 500405d78938772e0e9f8e3ce4f930d782c670fa | [
"crates/router/src/connector/multisafepay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2683 | Bug: [FEATURE] Add support for tokenising bank details and fetching masked details while listing
### Feature Description
Add support for tokenising the fetched bank details during list_customer_payment_method and return masked bank details
### Possible Implementation
For each bank account fetched from payment_methods_table, tokenize each account and store it in redis, so that it could be fetched during /confirm
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index c40dffe4cf3..8710c69aa5c 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -811,10 +811,20 @@ pub struct CustomerPaymentMethod {
#[schema(value_type = Option<Bank>)]
pub bank_transfer: Option<payouts::Bank>,
+ /// Masked bank details from PM auth services
+ #[schema(example = json!({"mask": "0000"}))]
+ pub bank: Option<MaskedBankDetails>,
+
/// Whether this payment method requires CVV to be collected
#[schema(example = true)]
pub requires_cvv: bool,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct MaskedBankDetails {
+ pub mask: String,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodId {
pub payment_method_id: String,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 60fd3f315ea..85a0ca5f244 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -7,9 +7,10 @@ use api_models::{
admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
- CardDetailsPaymentMethod, CardNetworkTypes, PaymentExperienceTypes, PaymentMethodsData,
- RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate,
- ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled,
+ BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails,
+ PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo,
+ ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
+ ResponsePaymentMethodsEnabled,
},
payments::BankCodeResponse,
surcharge_decision_configs as api_surcharge_decision_configs,
@@ -2210,6 +2211,22 @@ pub async fn list_customer_payment_method(
)
}
+ enums::PaymentMethod::BankDebit => {
+ // Retrieve the pm_auth connector details so that it can be tokenized
+ let bank_account_connector_details = get_bank_account_connector_details(&pm, key)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ });
+ if let Some(connector_details) = bank_account_connector_details {
+ let token_data = PaymentTokenData::AuthBankDebit(connector_details);
+ (None, None, token_data)
+ } else {
+ continue;
+ }
+ }
+
_ => (
None,
None,
@@ -2217,6 +2234,18 @@ pub async fn list_customer_payment_method(
),
};
+ // Retrieve the masked bank details to be sent as a response
+ let bank_details = if pm.payment_method == enums::PaymentMethod::BankDebit {
+ get_masked_bank_details(&pm, key)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
+ } else {
+ None
+ };
+
//Need validation for enabled payment method ,querying MCA
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
@@ -2232,6 +2261,7 @@ pub async fn list_customer_payment_method(
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
bank_transfer: pmd,
+ bank: bank_details,
requires_cvv,
};
customer_pms.push(pma.to_owned());
@@ -2356,6 +2386,84 @@ pub async fn get_lookup_key_from_locker(
Ok(resp)
}
+async fn get_masked_bank_details(
+ pm: &payment_method::PaymentMethod,
+ key: &[u8],
+) -> errors::RouterResult<Option<MaskedBankDetails>> {
+ let payment_method_data =
+ decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt bank details")?
+ .map(|x| x.into_inner().expose())
+ .map(
+ |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
+ v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ },
+ )
+ .transpose()?;
+
+ match payment_method_data {
+ Some(pmd) => match pmd {
+ PaymentMethodsData::Card(_) => Ok(None),
+ PaymentMethodsData::BankDetails(bank_details) => Ok(Some(MaskedBankDetails {
+ mask: bank_details.mask,
+ })),
+ },
+ None => Err(errors::ApiErrorResponse::InternalServerError.into())
+ .attach_printable("Unable to fetch payment method data"),
+ }
+}
+
+async fn get_bank_account_connector_details(
+ pm: &payment_method::PaymentMethod,
+ key: &[u8],
+) -> errors::RouterResult<Option<BankAccountConnectorDetails>> {
+ let payment_method_data =
+ decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to decrypt bank details")?
+ .map(|x| x.into_inner().expose())
+ .map(
+ |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
+ v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize Payment Method Auth config")
+ },
+ )
+ .transpose()?;
+
+ match payment_method_data {
+ Some(pmd) => match pmd {
+ PaymentMethodsData::Card(_) => Err(errors::ApiErrorResponse::UnprocessableEntity {
+ message: "Card is not a valid entity".to_string(),
+ })
+ .into_report(),
+ PaymentMethodsData::BankDetails(bank_details) => {
+ let connector_details = bank_details
+ .connector_details
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ Ok(Some(BankAccountConnectorDetails {
+ connector: connector_details.connector.clone(),
+ account_id: connector_details.account_id.clone(),
+ mca_id: connector_details.mca_id.clone(),
+ access_token: connector_details.access_token.clone(),
+ }))
+ }
+ },
+ None => Err(errors::ApiErrorResponse::InternalServerError.into())
+ .attach_printable("Unable to fetch payment method data"),
+ }
+}
+
#[cfg(feature = "payouts")]
pub async fn get_lookup_key_for_payout_method(
state: &routes::AppState,
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index 04ef90546cf..d191890b8cd 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -315,6 +315,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payment_methods::RequiredFieldInfo,
+ api_models::payment_methods::MaskedBankDetails,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::TimeRange,
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 9ca4dea4a1a..b26c030c367 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4828,6 +4828,14 @@
],
"nullable": true
},
+ "bank": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MaskedBankDetails"
+ }
+ ],
+ "nullable": true
+ },
"requires_cvv": {
"type": "boolean",
"description": "Whether this payment method requires CVV to be collected",
@@ -6434,6 +6442,17 @@
}
]
},
+ "MaskedBankDetails": {
+ "type": "object",
+ "required": [
+ "mask"
+ ],
+ "properties": {
+ "mask": {
+ "type": "string"
+ }
+ }
+ },
"MbWayRedirection": {
"type": "object",
"required": [
| 2023-10-14T12:17:42Z |
## Description
<!-- Describe your changes in detail -->
This PR includes changes for tokenising the fetched bank details and return masked bank details while fetching the customer payment methods
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 037e310aab5fac90ba33cdff2acda2f031261a6c |
List customer payment method -

Redis Entry -

| [
"crates/api_models/src/payment_methods.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/openapi.rs",
"openapi/openapi_spec.json"
] | |
juspay/hyperswitch | juspay__hyperswitch-2278 | Bug: [REFACTOR]: [Nuvei] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 2fd1a9c272f..88ebe1d8dbe 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -490,11 +490,145 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC {
api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers),
api_models::enums::BankNames::Moneyou => Ok(Self::Moneyou),
- _ => Err(errors::ConnectorError::FlowNotSupported {
- flow: bank.to_string(),
- connector: "Nuvei".to_string(),
+
+ api_models::enums::BankNames::AmericanExpress
+ | api_models::enums::BankNames::AffinBank
+ | api_models::enums::BankNames::AgroBank
+ | api_models::enums::BankNames::AllianceBank
+ | api_models::enums::BankNames::AmBank
+ | api_models::enums::BankNames::BankOfAmerica
+ | api_models::enums::BankNames::BankIslam
+ | api_models::enums::BankNames::BankMuamalat
+ | api_models::enums::BankNames::BankRakyat
+ | api_models::enums::BankNames::BankSimpananNasional
+ | api_models::enums::BankNames::Barclays
+ | api_models::enums::BankNames::BlikPSP
+ | api_models::enums::BankNames::CapitalOne
+ | api_models::enums::BankNames::Chase
+ | api_models::enums::BankNames::Citi
+ | api_models::enums::BankNames::CimbBank
+ | api_models::enums::BankNames::Discover
+ | api_models::enums::BankNames::NavyFederalCreditUnion
+ | api_models::enums::BankNames::PentagonFederalCreditUnion
+ | api_models::enums::BankNames::SynchronyBank
+ | api_models::enums::BankNames::WellsFargo
+ | api_models::enums::BankNames::Handelsbanken
+ | api_models::enums::BankNames::HongLeongBank
+ | api_models::enums::BankNames::HsbcBank
+ | api_models::enums::BankNames::KuwaitFinanceHouse
+ | api_models::enums::BankNames::Regiobank
+ | api_models::enums::BankNames::Revolut
+ | api_models::enums::BankNames::ArzteUndApothekerBank
+ | api_models::enums::BankNames::AustrianAnadiBankAg
+ | api_models::enums::BankNames::BankAustria
+ | api_models::enums::BankNames::Bank99Ag
+ | api_models::enums::BankNames::BankhausCarlSpangler
+ | api_models::enums::BankNames::BankhausSchelhammerUndSchatteraAg
+ | api_models::enums::BankNames::BankMillennium
+ | api_models::enums::BankNames::BankPEKAOSA
+ | api_models::enums::BankNames::BawagPskAg
+ | api_models::enums::BankNames::BksBankAg
+ | api_models::enums::BankNames::BrullKallmusBankAg
+ | api_models::enums::BankNames::BtvVierLanderBank
+ | api_models::enums::BankNames::CapitalBankGraweGruppeAg
+ | api_models::enums::BankNames::CeskaSporitelna
+ | api_models::enums::BankNames::Dolomitenbank
+ | api_models::enums::BankNames::EasybankAg
+ | api_models::enums::BankNames::EPlatbyVUB
+ | api_models::enums::BankNames::ErsteBankUndSparkassen
+ | api_models::enums::BankNames::FrieslandBank
+ | api_models::enums::BankNames::HypoAlpeadriabankInternationalAg
+ | api_models::enums::BankNames::HypoNoeLbFurNiederosterreichUWien
+ | api_models::enums::BankNames::HypoOberosterreichSalzburgSteiermark
+ | api_models::enums::BankNames::HypoTirolBankAg
+ | api_models::enums::BankNames::HypoVorarlbergBankAg
+ | api_models::enums::BankNames::HypoBankBurgenlandAktiengesellschaft
+ | api_models::enums::BankNames::KomercniBanka
+ | api_models::enums::BankNames::MBank
+ | api_models::enums::BankNames::MarchfelderBank
+ | api_models::enums::BankNames::Maybank
+ | api_models::enums::BankNames::OberbankAg
+ | api_models::enums::BankNames::OsterreichischeArzteUndApothekerbank
+ | api_models::enums::BankNames::OcbcBank
+ | api_models::enums::BankNames::PayWithING
+ | api_models::enums::BankNames::PlaceZIPKO
+ | api_models::enums::BankNames::PlatnoscOnlineKartaPlatnicza
+ | api_models::enums::BankNames::PosojilnicaBankEGen
+ | api_models::enums::BankNames::PostovaBanka
+ | api_models::enums::BankNames::PublicBank
+ | api_models::enums::BankNames::RaiffeisenBankengruppeOsterreich
+ | api_models::enums::BankNames::RhbBank
+ | api_models::enums::BankNames::SchelhammerCapitalBankAg
+ | api_models::enums::BankNames::StandardCharteredBank
+ | api_models::enums::BankNames::SchoellerbankAg
+ | api_models::enums::BankNames::SpardaBankWien
+ | api_models::enums::BankNames::SporoPay
+ | api_models::enums::BankNames::SantanderPrzelew24
+ | api_models::enums::BankNames::TatraPay
+ | api_models::enums::BankNames::Viamo
+ | api_models::enums::BankNames::VolksbankGruppe
+ | api_models::enums::BankNames::VolkskreditbankAg
+ | api_models::enums::BankNames::VrBankBraunau
+ | api_models::enums::BankNames::UobBank
+ | api_models::enums::BankNames::PayWithAliorBank
+ | api_models::enums::BankNames::BankiSpoldzielcze
+ | api_models::enums::BankNames::PayWithInteligo
+ | api_models::enums::BankNames::BNPParibasPoland
+ | api_models::enums::BankNames::BankNowySA
+ | api_models::enums::BankNames::CreditAgricole
+ | api_models::enums::BankNames::PayWithBOS
+ | api_models::enums::BankNames::PayWithCitiHandlowy
+ | api_models::enums::BankNames::PayWithPlusBank
+ | api_models::enums::BankNames::ToyotaBank
+ | api_models::enums::BankNames::VeloBank
+ | api_models::enums::BankNames::ETransferPocztowy24
+ | api_models::enums::BankNames::PlusBank
+ | api_models::enums::BankNames::EtransferPocztowy24
+ | api_models::enums::BankNames::BankiSpbdzielcze
+ | api_models::enums::BankNames::BankNowyBfgSa
+ | api_models::enums::BankNames::GetinBank
+ | api_models::enums::BankNames::Blik
+ | api_models::enums::BankNames::NoblePay
+ | api_models::enums::BankNames::IdeaBank
+ | api_models::enums::BankNames::EnveloBank
+ | api_models::enums::BankNames::NestPrzelew
+ | api_models::enums::BankNames::MbankMtransfer
+ | api_models::enums::BankNames::Inteligo
+ | api_models::enums::BankNames::PbacZIpko
+ | api_models::enums::BankNames::BnpParibas
+ | api_models::enums::BankNames::BankPekaoSa
+ | api_models::enums::BankNames::VolkswagenBank
+ | api_models::enums::BankNames::AliorBank
+ | api_models::enums::BankNames::Boz
+ | api_models::enums::BankNames::BangkokBank
+ | api_models::enums::BankNames::KrungsriBank
+ | api_models::enums::BankNames::KrungThaiBank
+ | api_models::enums::BankNames::TheSiamCommercialBank
+ | api_models::enums::BankNames::KasikornBank
+ | api_models::enums::BankNames::OpenBankSuccess
+ | api_models::enums::BankNames::OpenBankFailure
+ | api_models::enums::BankNames::OpenBankCancelled
+ | api_models::enums::BankNames::Aib
+ | api_models::enums::BankNames::BankOfScotland
+ | api_models::enums::BankNames::DanskeBank
+ | api_models::enums::BankNames::FirstDirect
+ | api_models::enums::BankNames::FirstTrust
+ | api_models::enums::BankNames::Halifax
+ | api_models::enums::BankNames::Lloyds
+ | api_models::enums::BankNames::Monzo
+ | api_models::enums::BankNames::NatWest
+ | api_models::enums::BankNames::NationwideBank
+ | api_models::enums::BankNames::RoyalBankOfScotland
+ | api_models::enums::BankNames::Starling
+ | api_models::enums::BankNames::TsbBank
+ | api_models::enums::BankNames::TescoBank
+ | api_models::enums::BankNames::UlsterBank => {
+ Err(errors::ConnectorError::NotSupported {
+ message: bank.to_string(),
+ connector: "Nuvei",
+ }
+ .into())
}
- .into()),
}
}
}
| 2023-10-13T18:46:35Z |
## Description
<!-- Describe your changes in detail -->
- Fix issue #2278
- Changes to be made : Remove default case handling
- Added all the ```Banknames``` (which are not ```NuveiBIC``` ) against the default case
- File changed: **```transformers.rs```** (crates/router/src/connector/nuvei/transformers.rs)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 5d88dbc92ce470c951717debe246e182b3fe5656 | [
"crates/router/src/connector/nuvei/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2215 | Bug: [FEATURE]: [Airwallex] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index 8a22c14dd32..8ef7ba08211 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -66,6 +66,10 @@ impl ConnectorCommon for Airwallex {
"airwallex"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -369,7 +373,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = airwallex::AirwallexPaymentsRequest::try_from(req)?;
+ let connector_router_data = airwallex::AirwallexRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = airwallex::AirwallexPaymentsRequest::try_from(&connector_router_data)?;
let airwallex_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<airwallex::AirwallexPaymentsRequest>::encode_to_string_of_json,
@@ -810,7 +820,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = airwallex::AirwallexRefundRequest::try_from(req)?;
+ let connector_router_data = airwallex::AirwallexRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = airwallex::AirwallexRefundRequest::try_from(&connector_router_data)?;
let airwallex_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<airwallex::AirwallexRefundRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 3343f41c554..51258643c64 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -53,6 +53,38 @@ impl TryFrom<&types::PaymentsInitRouterData> for AirwallexIntentRequest {
}
}
+#[derive(Debug, Serialize)]
+pub struct AirwallexRouterData<T> {
+ pub amount: String,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for AirwallexRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (currency_unit, currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Debug, Serialize)]
pub struct AirwallexPaymentsRequest {
// Unique ID to be sent for each transaction/operation request to the connector
@@ -125,16 +157,21 @@ pub struct AirwallexCardPaymentOptions {
auto_capture: bool,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest {
+impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
+ for AirwallexPaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
let mut payment_method_options = None;
- let payment_method = match item.request.payment_method_data.clone() {
+ let request = &item.router_data.request;
+ let payment_method = match request.payment_method_data.clone() {
api::PaymentMethodData::Card(ccard) => {
payment_method_options =
Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions {
auto_capture: matches!(
- item.request.capture_method,
+ request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
),
}));
@@ -158,7 +195,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest {
request_id: Uuid::new_v4().to_string(),
payment_method,
payment_method_options,
- return_url: item.request.complete_authorize_url.clone(),
+ return_url: request.complete_authorize_url.clone(),
})
}
}
@@ -538,17 +575,16 @@ pub struct AirwallexRefundRequest {
payment_intent_id: String,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for AirwallexRefundRequest {
+impl<F> TryFrom<&AirwallexRouterData<&types::RefundsRouterData<F>>> for AirwallexRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AirwallexRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Uuid::new_v4().to_string(),
- amount: Some(utils::to_currency_base_unit(
- item.request.refund_amount,
- item.request.currency,
- )?),
- reason: item.request.reason.clone(),
- payment_intent_id: item.request.connector_transaction_id.clone(),
+ amount: Some(item.amount.to_owned()),
+ reason: item.router_data.request.reason.clone(),
+ payment_intent_id: item.router_data.request.connector_transaction_id.clone(),
})
}
}
| 2023-10-13T07:44:28Z |
## Description
- Addressing Issue: #2215
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `airwallex.rs`
- Implement `get_currency_unit` function
- Modify `ConnectorIntegration` implementations for `Airwallex`
- `airwallex/transformers.rs`
- Implement `AirwallexRouterData<T>` structure and functionality
- Modify implementation for `AirwallexPaymentsRequest`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #2215.
# | 500405d78938772e0e9f8e3ce4f930d782c670fa | [
"crates/router/src/connector/airwallex.rs",
"crates/router/src/connector/airwallex/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2218 | Bug: [FEATURE]: [Authorizedotnet] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 99e87ca1edf..7ff2098344e 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -49,6 +49,10 @@ impl ConnectorCommon for Authorizedotnet {
"authorizedotnet"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -142,7 +146,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
&self,
req: &types::PaymentsCaptureRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?;
+ let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount_to_capture,
+ req,
+ ))?;
+ let connector_req =
+ authorizedotnet::CancelOrCaptureTransactionRequest::try_from(&connector_router_data)?;
let authorizedotnet_req = types::RequestBody::log_and_get_request_body(
&connector_req,
@@ -315,7 +326,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = authorizedotnet::CreateTransactionRequest::try_from(req)?;
+ let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req =
+ authorizedotnet::CreateTransactionRequest::try_from(&connector_router_data)?;
let authorizedotnet_req = types::RequestBody::log_and_get_request_body(
&connector_req,
@@ -496,7 +514,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
&self,
req: &types::RefundsRouterData<api::Execute>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = authorizedotnet::CreateRefundRequest::try_from(req)?;
+ let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = authorizedotnet::CreateRefundRequest::try_from(&connector_router_data)?;
let authorizedotnet_req = types::RequestBody::log_and_get_request_body(
&connector_req,
@@ -583,7 +607,15 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
&self,
req: &types::RefundsRouterData<api::RSync>,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?;
+ let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req =
+ authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(&connector_router_data)?;
+
let sync_request = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json,
@@ -670,7 +702,15 @@ impl
&self,
req: &types::PaymentsCompleteAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = authorizedotnet::PaypalConfirmRequest::try_from(req)?;
+ let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req =
+ authorizedotnet::PaypalConfirmRequest::try_from(&connector_router_data)?;
+
let authorizedotnet_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<authorizedotnet::PaypalConfirmRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 1b7480f78e4..cd7e070b16f 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -31,6 +31,38 @@ pub enum TransactionType {
#[serde(rename = "authCaptureContinueTransaction")]
ContinueCapture,
}
+
+#[derive(Debug, Serialize)]
+pub struct AuthorizedotnetRouterData<T> {
+ pub amount: f64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for AuthorizedotnetRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (currency_unit, currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetAuthType {
@@ -99,7 +131,7 @@ pub enum WalletMethod {
}
fn get_pm_and_subsequent_auth_detail(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<
(
PaymentDetails,
@@ -109,6 +141,7 @@ fn get_pm_and_subsequent_auth_detail(
error_stack::Report<errors::ConnectorError>,
> {
match item
+ .router_data
.request
.mandate_id
.to_owned()
@@ -124,7 +157,7 @@ fn get_pm_and_subsequent_auth_detail(
original_network_trans_id,
reason: Reason::Resubmission,
});
- match item.request.payment_method_data {
+ match item.router_data.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => {
let payment_details = PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
@@ -134,12 +167,12 @@ fn get_pm_and_subsequent_auth_detail(
Ok((payment_details, processing_options, subseuent_auth_info))
}
_ => Err(errors::ConnectorError::NotSupported {
- message: format!("{:?}", item.request.payment_method_data),
+ message: format!("{:?}", item.router_data.request.payment_method_data),
connector: "AuthorizeDotNet",
})?,
}
}
- _ => match item.request.payment_method_data {
+ _ => match item.router_data.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => {
Ok((
PaymentDetails::CreditCard(CreditCardDetails {
@@ -155,12 +188,15 @@ fn get_pm_and_subsequent_auth_detail(
))
}
api::PaymentMethodData::Wallet(ref wallet_data) => Ok((
- get_wallet_data(wallet_data, &item.request.complete_authorize_url)?,
+ get_wallet_data(
+ wallet_data,
+ &item.router_data.request.complete_authorize_url,
+ )?,
None,
None,
)),
_ => Err(errors::ConnectorError::NotSupported {
- message: format!("{:?}", item.request.payment_method_data),
+ message: format!("{:?}", item.router_data.request.payment_method_data),
connector: "AuthorizeDotNet",
})?,
},
@@ -263,26 +299,34 @@ impl From<enums::CaptureMethod> for AuthorizationType {
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for CreateTransactionRequest {
+impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
+ for CreateTransactionRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
let (payment_details, processing_options, subsequent_auth_information) =
get_pm_and_subsequent_auth_detail(item)?;
let authorization_indicator_type =
- item.request.capture_method.map(|c| AuthorizationIndicator {
- authorization_indicator: c.into(),
- });
+ item.router_data
+ .request
+ .capture_method
+ .map(|c| AuthorizationIndicator {
+ authorization_indicator: c.into(),
+ });
let transaction_request = TransactionRequest {
- transaction_type: TransactionType::from(item.request.capture_method),
- amount: utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?,
+ transaction_type: TransactionType::from(item.router_data.request.capture_method),
+ amount: item.amount,
payment: payment_details,
- currency_code: item.request.currency.to_string(),
+ currency_code: item.router_data.request.currency.to_string(),
processing_options,
subsequent_auth_information,
authorization_indicator_type,
};
- let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentsRequest {
@@ -313,19 +357,25 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelOrCaptureTransactionReq
}
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for CancelOrCaptureTransactionRequest {
+impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>>
+ for CancelOrCaptureTransactionRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
- amount: Some(utils::to_currency_base_unit_asf64(
- item.request.amount_to_capture,
- item.request.currency,
- )?),
+ amount: Some(item.amount),
transaction_type: TransactionType::Capture,
- ref_trans_id: item.request.connector_transaction_id.to_string(),
+ ref_trans_id: item
+ .router_data
+ .request
+ .connector_transaction_id
+ .to_string(),
};
- let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
@@ -648,10 +698,13 @@ pub struct CreateRefundRequest {
create_transaction_request: AuthorizedotnetRefundRequest,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest {
+impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>> for CreateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
let payment_details = item
+ .router_data
.request
.connector_metadata
.as_ref()
@@ -661,21 +714,19 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest {
})?
.clone();
- let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_request = RefundTransactionRequest {
transaction_type: TransactionType::Refund,
- amount: utils::to_currency_base_unit_asf64(
- item.request.refund_amount,
- item.request.currency,
- )?,
+ amount: item.amount,
payment: payment_details
.parse_value("PaymentDetails")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "payment_details",
})?,
- currency_code: item.request.currency.to_string(),
- reference_transaction_id: item.request.connector_transaction_id.clone(),
+ currency_code: item.router_data.request.currency.to_string(),
+ reference_transaction_id: item.router_data.request.connector_transaction_id.clone(),
};
Ok(Self {
@@ -750,12 +801,17 @@ pub struct AuthorizedotnetCreateSyncRequest {
get_transaction_details_request: TransactionDetails,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for AuthorizedotnetCreateSyncRequest {
+impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>>
+ for AuthorizedotnetCreateSyncRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let transaction_id = item.request.get_connector_refund_id()?;
- let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ fn try_from(
+ item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let transaction_id = item.router_data.request.get_connector_refund_id()?;
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
@@ -1131,10 +1187,15 @@ pub struct PaypalQueryParams {
payer_id: String,
}
-impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmRequest {
+impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+ for PaypalConfirmRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
let params = item
+ .router_data
.request
.redirect_response
.as_ref()
@@ -1146,7 +1207,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmReque
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
.payer_id,
);
- let transaction_type = match item.request.capture_method {
+ let transaction_type = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization,
_ => TransactionType::ContinueCapture,
};
@@ -1155,10 +1216,11 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for PaypalConfirmReque
payment: PaypalPaymentConfirm {
pay_pal: Paypal { payer_id },
},
- ref_trans_id: item.request.connector_transaction_id.clone(),
+ ref_trans_id: item.router_data.request.connector_transaction_id.clone(),
};
- let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: PaypalConfirmTransactionRequest {
| 2023-10-12T19:48:15Z |
## 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).
-->
Fixes #2218 | fbf3c03d418242b1f5f1a15c69029023d0b25b4e | [
"crates/router/src/connector/authorizedotnet.rs",
"crates/router/src/connector/authorizedotnet/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2249 | Bug: [FEATURE]: [Worldline] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs
index 4e69fd5ca0a..b10e3dcd74c 100644
--- a/crates/router/src/connector/worldline.rs
+++ b/crates/router/src/connector/worldline.rs
@@ -112,6 +112,10 @@ impl ConnectorCommon for Worldline {
"worldline"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.worldline.base_url.as_ref()
}
@@ -486,7 +490,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = worldline::PaymentsRequest::try_from(req)?;
+ let connector_router_data = worldline::WorldlineRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = worldline::PaymentsRequest::try_from(&connector_router_data)?;
let worldline_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<worldline::PaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index d02ab60c8b9..f11c2398080 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -13,6 +13,7 @@ use crate::{
api::{self, enums as api_enums},
storage::enums,
transformers::ForeignFrom,
+ PaymentsAuthorizeData, PaymentsResponseData,
},
};
@@ -183,38 +184,91 @@ pub struct PaymentsRequest {
pub shipping: Option<Shipping>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest {
+#[derive(Debug, Serialize)]
+pub struct WorldlineRouterData<T> {
+ amount: i64,
+ router_data: T,
+}
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for WorldlineRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (_currency_unit, _currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
+impl
+ TryFrom<
+ &WorldlineRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ > for PaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let payment_data = match item.request.payment_method_data {
- api::PaymentMethodData::Card(ref card) => {
+
+ fn try_from(
+ item: &WorldlineRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let payment_data = match &item.router_data.request.payment_method_data {
+ api::PaymentMethodData::Card(card) => {
WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request(
- &item.request,
+ &item.router_data.request,
card,
)?))
}
- api::PaymentMethodData::BankRedirect(ref bank_redirect) => {
+ api::PaymentMethodData::BankRedirect(bank_redirect) => {
WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
- make_bank_redirect_request(&item.request, bank_redirect)?,
+ make_bank_redirect_request(&item.router_data.request, bank_redirect)?,
))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment methods".to_string(),
- ))?,
+ _ => {
+ return Err(
+ errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
+ )
+ }
};
- let customer = build_customer_info(&item.address, &item.request.email)?;
+
+ let customer =
+ build_customer_info(&item.router_data.address, &item.router_data.request.email)?;
let order = Order {
amount_of_money: AmountOfMoney {
- amount: item.request.amount,
- currency_code: item.request.currency.to_string().to_uppercase(),
+ amount: item.amount,
+ currency_code: item.router_data.request.currency.to_string().to_uppercase(),
},
customer,
references: References {
- merchant_reference: item.connector_request_reference_id.clone(),
+ merchant_reference: item.router_data.connector_request_reference_id.clone(),
},
};
let shipping = item
+ .router_data
.address
.shipping
.as_ref()
@@ -227,6 +281,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest {
})
}
}
+
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Gateway {
Amex = 2,
@@ -276,7 +331,7 @@ impl TryFrom<&api_models::enums::BankNames> for WorldlineBic {
}
fn make_card_request(
- req: &types::PaymentsAuthorizeData,
+ req: &PaymentsAuthorizeData,
ccard: &payments::Card,
) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let expiry_year = ccard.card_exp_year.peek().clone();
@@ -303,7 +358,7 @@ fn make_card_request(
}
fn make_bank_redirect_request(
- req: &types::PaymentsAuthorizeData,
+ req: &PaymentsAuthorizeData,
bank_redirect: &payments::BankRedirectData,
) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let return_url = req.router_return_url.clone();
@@ -497,12 +552,12 @@ pub struct Payment {
pub capture_method: enums::CaptureMethod,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, Payment, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::foreign_from((
@@ -541,12 +596,12 @@ pub struct RedirectData {
pub redirect_url: Url,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
| 2023-10-12T18:04:53Z |
## Description
This pull request implements the get_currency_unit from the ConnectorCommon trait for the Worldline connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Worldline it accepts currency as Minor units.
## Links to the files with corresponding changes.
1. crates/router/src/connector/worldline.rs
2. crates/router/src/connector/worldline/transformers.rs
## Motivation and Context
Closes #2249 | 1afae7e69a81afeff3a7ff55f2b2d5b063afb7c1 | [
"crates/router/src/connector/worldline.rs",
"crates/router/src/connector/worldline/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2226 | Bug: [FEATURE]: [Forte] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs
index 7cc3f9f9a4e..6184b130bb6 100644
--- a/crates/router/src/connector/forte.rs
+++ b/crates/router/src/connector/forte.rs
@@ -82,6 +82,10 @@ impl ConnectorCommon for Forte {
"forte"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -226,7 +230,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = forte::FortePaymentsRequest::try_from(req)?;
+ let connector_router_data = forte::ForteRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = forte::FortePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 83bcb2c551b..96955df244e 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -7,7 +7,10 @@ use crate::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData,
},
core::errors,
- types::{self, api, storage::enums, transformers::ForeignFrom},
+ types::{
+ self, api, storage::enums, transformers::ForeignFrom, PaymentsAuthorizeData,
+ PaymentsResponseData,
+ },
};
#[derive(Debug, Serialize)]
@@ -62,39 +65,80 @@ impl TryFrom<utils::CardIssuer> for ForteCardType {
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
+#[derive(Debug, Serialize)]
+pub struct ForteRouterData<T> {
+ amount: f64,
+ router_data: T,
+}
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for ForteRouterData<T>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- if item.request.currency != enums::Currency::USD {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Forte"),
- ))?
- }
- match item.request.payment_method_data {
- api_models::payments::PaymentMethodData::Card(ref ccard) => {
- let action = match item.request.is_auto_capture()? {
+ fn try_from(
+ (currency_unit, currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: utils::get_amount_as_f64(currency_unit, amount, currency)?,
+ router_data: item,
+ })
+ }
+}
+
+impl
+ TryFrom<
+ &ForteRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ > for FortePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &ForteRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match &item.router_data.request.payment_method_data {
+ api::PaymentMethodData::Card(card) => {
+ let action = match item.router_data.request.is_auto_capture()? {
true => ForteAction::Sale,
false => ForteAction::Authorize,
};
- let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?;
- let address = item.get_billing_address()?;
+ let card_type = ForteCardType::try_from(card.get_card_issuer()?)?;
+ let address = item.router_data.get_billing_address()?;
let card = Card {
card_type,
- name_on_card: ccard
+ name_on_card: card
.card_holder_name
.clone()
.unwrap_or(Secret::new("".to_string())),
- account_number: ccard.card_number.clone(),
- expire_month: ccard.card_exp_month.clone(),
- expire_year: ccard.card_exp_year.clone(),
- card_verification_value: ccard.card_cvc.clone(),
+ account_number: card.card_number.clone(),
+ expire_month: card.card_exp_month.clone(),
+ expire_year: card.card_exp_year.clone(),
+ card_verification_value: card.card_cvc.clone(),
};
let billing_address = BillingAddress {
first_name: address.get_first_name()?.to_owned(),
last_name: address.get_last_name()?.to_owned(),
};
- let authorization_amount =
- utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?;
+ let authorization_amount = item.amount.to_owned();
Ok(Self {
action,
authorization_amount,
@@ -255,13 +299,12 @@ pub struct ForteMeta {
pub auth_id: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item.response.response.response_code;
let action = item.response.action;
@@ -300,18 +343,12 @@ pub struct FortePaymentsSyncResponse {
pub response: ResponseStatus,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, FortePaymentsSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- FortePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: types::ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
@@ -441,13 +478,12 @@ pub struct ForteCancelResponse {
pub response: CancelResponseStatus,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<types::ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>>
+ for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>,
+ item: types::ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
| 2023-10-11T18:34:00Z |
## Description
<!-- Describe your changes in detail -->
This pull request implements the get_currency_unit from the Connector trait for the Forte connector. This function allows connectors to declare their accepted currency unit as either `Base` or `Minor`. For Forte it accepts currency as `Base` units.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->#2226
# | 2d4f6b3fa004a3f03beaa604e2dbfe95fcbe22a6 |
We need to create a payment using Forte and test the currency unit from connector response and connector dashboard.
| [
"crates/router/src/connector/forte.rs",
"crates/router/src/connector/forte/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2321 | Bug: [FEATURE]: [Worldpay] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index aabe27fc4eb..61d04a8e9f1 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -167,10 +167,14 @@ impl
debt_repayment: None,
},
merchant: Merchant {
- entity: item.router_data.attempt_id.clone().replace('_', "-"),
+ entity: item
+ .router_data
+ .connector_request_reference_id
+ .clone()
+ .replace('_', "-"),
..Default::default()
},
- transaction_reference: item.router_data.attempt_id.clone(),
+ transaction_reference: item.router_data.connector_request_reference_id.clone(),
channel: None,
customer: None,
})
| 2023-10-11T18:13:27Z |
## Description
<!-- Describe your changes in detail -->
As mentioned in the issue #2321 , I had to work on the attempt_id and payment_id in the Router data , it should have been replaced with the new introduced connector_request_reference_id.
I think I have did it.
please have a look and merge if it's done @VedantKhairnar @srujanchikke | cd9030506c6843c0331bc93d67590d12e280ecca | [
"crates/router/src/connector/worldpay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2205 | Bug: [FEATURE]: [ACI] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 7d30c80c49c..f6c1daffe4d 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -682,12 +682,12 @@ impl<F, T>
}
},
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
}),
..item.data
})
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index c34008d527a..7afcef2cd31 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -449,7 +449,7 @@ where
headers.extend(
external_latency
.map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())])
- .unwrap_or(vec![]),
+ .unwrap_or_default(),
);
}
let output = Ok(match payment_request {
| 2023-10-11T17:54:29Z |
## Description
The connector_response_reference_id parameter has been set for the ACIs Payment Solutions for uniform reference and transaction tracking.
## File Changes
This PR modifies the Aci Transformers file.
Location- router/src/connector/aci/transformers.rs
## Motivation and Context
The PR was raised so that it fixes #2205.
## How did you test it
- I ran the following command, and all the errors were addressed properly, and the build was successful.
`cargo clippy --all-features`
<img width="1065" alt="Screenshot 2023-10-13 at 12 53 06 PM" src="https://github.com/juspay/hyperswitch/assets/65838772/dc50a454-4b25-42da-b7b7-73c3df65cccb">
- The code changes were formatted with the following command to fix styling issues.
`cargo +nightly fmt` | 3807601ee1c140310abf7a7e6ee4b83d44de9558 | [
"crates/router/src/connector/aci/transformers.rs",
"crates/router/src/core/payments/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2203 | Bug: [FEATURE]: [ACI] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 30ed9f5d8db..7d30c80c49c 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -203,7 +203,9 @@ impl
bank_account_iban: None,
billing_country: Some(country.to_owned()),
merchant_customer_id: Some(Secret::new(item.get_customer_id()?)),
- merchant_transaction_id: Some(Secret::new(item.payment_id.clone())),
+ merchant_transaction_id: Some(Secret::new(
+ item.connector_request_reference_id.clone(),
+ )),
customer_email: None,
}))
}
| 2023-10-11T14:39:49Z |
## Description
<!-- Describe your changes in detail -->
Replaced payment_id with connector_request_reference_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).
-->
Fixes #2203
# | 550377a6c3943d9fec4ca6a8be5a5f3aafe109ab | [
"crates/router/src/connector/aci/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2283 | Bug: [REFACTOR]: [PowerTranz] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 4032f8019b0..5bbfe094352 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -1,6 +1,7 @@
use api_models::payments::Card;
use common_utils::pii::Email;
use diesel_models::enums::RefundStatus;
+use error_stack::IntoReport;
use masking::Secret;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -101,9 +102,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(card) => Ok(Source::from(&card)),
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- )),
+ api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "powertranz",
+ })
+ .into_report(),
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
| 2023-10-11T13:10:38Z |
## 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).
-->
# | 31431e41357d4d3d12668fa0d678cce0b3d86611 | [
"crates/router/src/connector/powertranz/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2350 | Bug: [FEATURE]: [Tsys] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index 5aa4574c91e..d8516c8293b 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -192,12 +192,14 @@ fn get_error_response(
fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsResponseData {
types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(connector_response.transaction_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ connector_response.transaction_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(connector_response.transaction_id),
}
}
@@ -215,7 +217,12 @@ fn get_payments_sync_response(
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ connector_response
+ .transaction_details
+ .transaction_id
+ .clone(),
+ ),
}
}
| 2023-10-11T12:40:42Z |
## Description
The `connector_response_reference_id` parameter has been set for the Tsys Payment Solutions for uniform reference and transaction tracking.
### File Changes
- [x] This PR modifies the Tsys Transformers file.
**Location- router/src/connector/tsys/transformers.rs**
## Motivation and Context
This PR was raised so that it Fixes #2350 !
# | 62638c4230bfd149c43c2805cbad0ce9be5386b3 | - **I ran the following command, and all the errors were addressed properly, and the build was successful.**
```bash
cargo clippy --all-features
```

- The code changes were formatted with the following command to fix styling issues.
```bash
cargo +nightly fmt
```
| [
"crates/router/src/connector/tsys/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2337 | Bug: [FEATURE]: [Nexi Nets] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 5949e48ae18..7b2a41cfb0b 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -364,7 +364,7 @@ impl<F, T>
mandate_reference,
connector_metadata: Some(connector_metadata),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id),
}),
..item.data
})
@@ -425,7 +425,7 @@ impl<F, T>
let transaction_id = Some(item.response.transaction_id.clone());
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id,
- order_id: Some(item.response.order.order_id),
+ order_id: Some(item.response.order.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.into_report()
@@ -447,7 +447,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: Some(connector_metadata),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order.order_id),
}),
..item.data
})
| 2023-10-10T14:22:43Z |
## Description
The `connector_response_reference_id` parameter has been set for the Nexi Nets Payment Solutions for uniform reference and transaction tracking.
### File Changes
- [x] This PR modifies the Nexi Nets Transformers file.
**Location- router/src/connector/nexinets/transformers.rs**
## Motivation and Context
This PR was raised so that it Fixes #2337
# | 3854d58270937ac4d2e5901eeb215bc19fffc838 | - **I ran the following command, and all the errors were addressed properly, and the build was successful.**
```bash
cargo clippy --all-features
```

- The code changes were formatted with the following command to fix styling issues.
```bash
cargo +nightly fmt
```
| [
"crates/router/src/connector/nexinets/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2526 | Bug: [REFACTOR] delete requires cvv config when merchant account is deleted
### Feature Description
Add support for removing the requires cvv config from configs table when merchant account is deleted.
### Possible Implementation
When merchant account delete request is sent, delete an entry in configs with key = '{merchant_id}_requires_cvv'
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index ec229bd8a56..226d77d598e 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -491,6 +491,25 @@ pub async fn merchant_account_delete(
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted;
}
+
+ match db
+ .delete_config_by_key(format!("{}_requires_cvv", merchant_id).as_str())
+ .await
+ {
+ Ok(_) => Ok::<_, errors::ApiErrorResponse>(()),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ crate::logger::error!("requires_cvv config not found in db: {err:?}");
+ Ok(())
+ } else {
+ Err(err
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while deleting requires_cvv config"))?
+ }
+ }
+ }
+ .ok();
+
let response = api::MerchantAccountDeleteResponse {
merchant_id,
deleted: is_deleted,
| 2023-10-10T08:03:09Z |
## Description
<!-- Describe your changes in detail -->
This PR includes changes for removing the requires cvv config from configs table when merchant account is deleted.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | cf0db35923d39caca9bf267b7d87a3f215884b66 |

| [
"crates/router/src/core/admin.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2333 | Bug: [FEATURE]: [Iatapay] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 39dfd61b9a3..9d4ecdff197 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -212,10 +212,14 @@ impl<F, T>
item: types::ResponseRouterData<F, IatapayPaymentsResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let id = match item.response.iata_payment_id {
+ let id = match item.response.iata_payment_id.clone() {
Some(s) => types::ResponseId::ConnectorTransactionId(s),
None => types::ResponseId::NoResponseId,
};
+ let connector_response_reference_id = item
+ .response
+ .merchant_payment_id
+ .or(item.response.iata_payment_id);
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: item.response.checkout_methods.map_or(
@@ -225,7 +229,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: connector_response_reference_id.clone(),
}),
|checkout_methods| {
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -238,7 +242,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: connector_response_reference_id.clone(),
})
},
),
| 2023-10-10T07:58:03Z |
## Description
<!-- Describe your changes in detail -->
- Adressess issue #2333 : Implement `connector_response_reference_id ` as reference to connector for Iatapay
- Modified the file `hyperswitch/crates/router/src/connector/iatapay/transformers.rs`
- Rebased with changes from [https://github.com/juspay/hyperswitch/commit/67cf33d0894f337839bb35b2a87d3807085e6672](url)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | d9fb5d4a52f44809ab4a1576a99e97b4c8b8c41b | [
"crates/router/src/connector/iatapay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2300 | Bug: [FEATURE]: [GlobalPayments] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 7a35a5f578f..78a83e70026 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -39,7 +39,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest {
account_name,
amount: Some(item.request.amount.to_string()),
currency: item.request.currency.to_string(),
- reference: item.attempt_id.to_string(),
+ reference: item.connector_request_reference_id.to_string(),
country: item.get_billing_country()?,
capture_mode: Some(requests::CaptureMode::from(item.request.capture_method)),
payment_method: requests::PaymentMethod {
| 2023-10-10T05:28:11Z |
## 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).
-->
# | cf0db35923d39caca9bf267b7d87a3f215884b66 | [
"crates/router/src/connector/globalpay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2293 | Bug: [FEATURE]: [Bambora] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index d34dda73eb6..bfcd9846292 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -48,6 +48,7 @@ pub struct BamboraBrowserInfo {
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct BamboraPaymentsRequest {
+ order_number: String,
amount: i64,
payment_method: PaymentMethod,
customer_ip: Option<std::net::IpAddr>,
@@ -126,6 +127,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
};
let browser_info = item.request.get_browser_info()?;
Ok(Self {
+ order_number: item.connector_request_reference_id.clone(),
amount: item.request.amount,
payment_method: PaymentMethod::Card,
card: bambora_card,
| 2023-10-10T02:00:08Z | Addresses #2293
## Description
<!-- Describe your changes in detail -->
This PR updates the use of `RequestData.request.connector_transaction_id` to `RequestData.connector_request_reference_id` for Bambora.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This addresses issue #2293 by setting `connector_request_reference_id` on Bambora make payment responses.
# | 9e450b81ca8bc4b1ddbbe2c1d732dbc58c61934e |
I ensured compilation was successful and existing tests ran successfully after changes were applied.
| [
"crates/router/src/connector/bambora/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2291 | Bug: [FEATURE]: [Airwallex] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index ecdddfb3672..fc90743ab08 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -48,7 +48,7 @@ impl TryFrom<&types::PaymentsInitRouterData> for AirwallexIntentRequest {
request_id: Uuid::new_v4().to_string(),
amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?,
currency: item.request.currency,
- merchant_order_id: item.payment_id.clone(),
+ merchant_order_id: item.connector_request_reference_id.clone(),
})
}
}
| 2023-10-09T23:09:19Z |
## 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).
-->
# | c34f1bf36ffb3a3533dd51ac87e7f66ab0dcce79 | [
"crates/router/src/connector/airwallex/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2307 | Bug: [FEATURE]: [Nexi Nets] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 7b2a41cfb0b..897d8f639d3 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -27,6 +27,7 @@ pub struct NexinetsPaymentsRequest {
payment: Option<NexinetsPaymentDetails>,
#[serde(rename = "async")]
nexinets_async: NexinetsAsyncDetails,
+ merchant_order_id: Option<String>,
}
#[derive(Debug, Serialize, Default)]
@@ -172,6 +173,11 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
failure_url: return_url,
};
let (payment, product) = get_payment_details_and_product(item)?;
+ let merchant_order_id = match item.payment_method {
+ // Merchant order id is sent only in case of card payment
+ enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()),
+ _ => None,
+ };
Ok(Self {
initial_amount: item.request.amount,
currency: item.request.currency,
@@ -179,6 +185,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
product,
payment,
nexinets_async,
+ merchant_order_id,
})
}
}
| 2023-10-09T20:55:20Z |
## Description
For all payment methods, Hyperswitch should transmit a reference to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
In this PR, such reference is obtained by calling `connector_request_reference_id()` in `RouterData`. The result is then passed as the "merchantOrderId" parameter to the NexiNets API, as per the [official documentation](https://developer.nexigroup.com/payengine/en-EU/api/payengine-api-v1/#orders-post-body-merchantorderid).
## Motivation and Context
Fixes #2307
# | 8029a895b2c27a1ac14a19aea23bbc06cc364809 | [
"crates/router/src/connector/nexinets/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2201 | Bug: [REFACTOR]: [ACI] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index fe621bccd05..7fb3ba7c411 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -123,9 +123,32 @@ impl TryFrom<&api_models::payments::WalletData> for PaymentDetails {
account_id: None,
}))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- ))?,
+ api_models::payments::WalletData::AliPayHkRedirect(_)
+ | api_models::payments::WalletData::MomoRedirect(_)
+ | api_models::payments::WalletData::KakaoPayRedirect(_)
+ | api_models::payments::WalletData::GoPayRedirect(_)
+ | api_models::payments::WalletData::GcashRedirect(_)
+ | api_models::payments::WalletData::ApplePay(_)
+ | api_models::payments::WalletData::ApplePayThirdPartySdk(_)
+ | api_models::payments::WalletData::DanaRedirect { .. }
+ | api_models::payments::WalletData::GooglePay(_)
+ | api_models::payments::WalletData::GooglePayThirdPartySdk(_)
+ | api_models::payments::WalletData::MobilePayRedirect(_)
+ | api_models::payments::WalletData::PaypalRedirect(_)
+ | api_models::payments::WalletData::PaypalSdk(_)
+ | api_models::payments::WalletData::SamsungPay(_)
+ | api_models::payments::WalletData::TwintRedirect { .. }
+ | api_models::payments::WalletData::VippsRedirect { .. }
+ | api_models::payments::WalletData::TouchNGoRedirect(_)
+ | api_models::payments::WalletData::WeChatPayRedirect(_)
+ | api_models::payments::WalletData::WeChatPayQr(_)
+ | api_models::payments::WalletData::CashappQr(_)
+ | api_models::payments::WalletData::SwishQr(_)
+ | api_models::payments::WalletData::AliPayQr(_)
+ | api_models::payments::WalletData::ApplePayRedirect(_)
+ | api_models::payments::WalletData::GooglePayRedirect(_) => Err(
+ errors::ConnectorError::NotImplemented("Payment method".to_string()),
+ )?,
};
Ok(payment_data)
}
@@ -262,9 +285,18 @@ impl
customer_email: None,
}))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment method".to_string(),
- ))?,
+ api_models::payments::BankRedirectData::Bizum { .. }
+ | api_models::payments::BankRedirectData::Blik { .. }
+ | api_models::payments::BankRedirectData::BancontactCard { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingThailand { .. }
+ | api_models::payments::BankRedirectData::OpenBankingUk { .. } => Err(
+ errors::ConnectorError::NotImplemented("Payment method".to_string()),
+ )?,
};
Ok(payment_data)
}
| 2023-10-09T13:50:33Z |
## Description
<!-- Describe your changes in detail -->
Instead of _ case, handled each and every case explicitly.
Fixes #2201
## Motivation and Context
# | d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b | Test a Payment Method which is not implemented for Aci connector
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 Aci
| [
"crates/router/src/connector/aci/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2296 | Bug: [FEATURE]: [Cybersource] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 3558f752841..5a3060f99eb 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -21,6 +21,7 @@ pub struct CybersourcePaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
+ client_reference_information: ClientReferenceInformation,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -150,10 +151,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest
capture_options: None,
};
+ let client_reference_information = ClientReferenceInformation {
+ code: Some(item.connector_request_reference_id.clone()),
+ };
+
Ok(Self {
processing_information,
payment_information,
order_information,
+ client_reference_information,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
@@ -179,6 +185,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for CybersourcePaymentsRequest {
},
..Default::default()
},
+ client_reference_information: ClientReferenceInformation {
+ code: Some(value.connector_request_reference_id.clone()),
+ },
..Default::default()
})
}
@@ -195,6 +204,9 @@ impl TryFrom<&types::RefundExecuteRouterData> for CybersourcePaymentsRequest {
},
..Default::default()
},
+ client_reference_information: ClientReferenceInformation {
+ code: Some(value.connector_request_reference_id.clone()),
+ },
..Default::default()
})
}
@@ -278,7 +290,7 @@ pub struct CybersourcePaymentsResponse {
client_reference_information: Option<ClientReferenceInformation>,
}
-#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)]
+#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
| 2023-10-09T13:40:40Z | Add reference with value of connector_request_reference_id in Cybersource transformers.
Fixes #2296
## 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).
-->
# | 550377a6c3943d9fec4ca6a8be5a5f3aafe109ab | [
"crates/router/src/connector/cybersource/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2504 | Bug: [REFACTOR] Limiting `Tracing` to only Payments API
## Description
We are tracing all the APIs, which isn't effective due to the variance of the traffic. This change will include the tracing layer to a specific scope instead of the entire application | diff --git a/config/config.example.toml b/config/config.example.toml
index e980ea4fffd..b69519b6ac4 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -28,6 +28,7 @@ port = 5432 # DB Port
dbname = "hyperswitch_db" # Name of Database
pool_size = 5 # Number of connections to keep open
connection_timeout = 10 # Timeout for database connection in seconds
+queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client
# Replica SQL data store credentials
[replica_database]
@@ -38,6 +39,7 @@ port = 5432 # DB Port
dbname = "hyperswitch_db" # Name of Database
pool_size = 5 # Number of connections to keep open
connection_timeout = 10 # Timeout for database connection in seconds
+queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client
# Redis credentials
[redis]
@@ -93,6 +95,7 @@ sampling_rate = 0.1 # decimal rate between 0.0
otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics and traces to, can include port number
otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces
use_xray_generator = false # Set this to true for AWS X-ray compatible traces
+route_to_trace = [ "*/confirm" ]
# This section provides some secret values.
[secrets]
@@ -422,4 +425,4 @@ supported_connectors = "braintree"
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" #Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate
apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" #Private key generate by Elliptic-curve prime256v1 curve
apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" #Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate
-apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key generate by RSA:2048 algorithm
\ No newline at end of file
+apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key generate by RSA:2048 algorithm
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index ec06a6d7078..3bb1c31d180 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -29,6 +29,7 @@ impl Default for super::settings::Database {
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
+ queue_strategy: Default::default(),
}
}
}
diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs
index 0491fb61fc6..317ad0608b4 100644
--- a/crates/router/src/configs/kms.rs
+++ b/crates/router/src/configs/kms.rs
@@ -61,6 +61,7 @@ impl KmsDecrypt for settings::Database {
password: self.password.decrypt_inner(kms_client).await?.into(),
pool_size: self.pool_size,
connection_timeout: self.connection_timeout,
+ queue_strategy: self.queue_strategy.into(),
})
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index fd4a398fd56..70d05b79f96 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -464,6 +464,24 @@ pub struct Database {
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
+ pub queue_strategy: QueueStrategy,
+}
+
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(rename_all = "PascalCase")]
+pub enum QueueStrategy {
+ #[default]
+ Fifo,
+ Lifo,
+}
+
+impl From<QueueStrategy> for bb8::QueueStrategy {
+ fn from(value: QueueStrategy) -> Self {
+ match value {
+ QueueStrategy::Fifo => Self::Fifo,
+ QueueStrategy::Lifo => Self::Lifo,
+ }
+ }
}
#[cfg(not(feature = "kms"))]
@@ -477,6 +495,7 @@ impl Into<storage_impl::config::Database> for Database {
dbname: self.dbname,
pool_size: self.pool_size,
connection_timeout: self.connection_timeout,
+ queue_strategy: self.queue_strategy.into(),
}
}
}
@@ -704,9 +723,11 @@ impl Settings {
.try_parsing(true)
.separator("__")
.list_separator(",")
+ .with_list_parse_key("log.telemetry.route_to_trace")
.with_list_parse_key("redis.cluster_urls")
.with_list_parse_key("connectors.supported.wallets")
.with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),
+
)
.build()?;
diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs
index 269759ed44f..664c0d508f5 100644
--- a/crates/router_env/src/logger/config.rs
+++ b/crates/router_env/src/logger/config.rs
@@ -101,6 +101,8 @@ pub struct LogTelemetry {
pub otel_exporter_otlp_timeout: Option<u64>,
/// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY)
pub use_xray_generator: bool,
+ /// Route Based Tracing
+ pub route_to_trace: Option<Vec<String>>,
}
/// Telemetry / tracing.
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index 78cbe9f342f..992de3e747e 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -12,6 +12,7 @@ use opentelemetry::{
trace::BatchConfig,
Resource,
},
+ trace::{TraceContextExt, TraceState},
KeyValue,
};
use opentelemetry_otlp::{TonicExporterBuilder, WithExportConfig};
@@ -132,6 +133,92 @@ fn get_opentelemetry_exporter(config: &config::LogTelemetry) -> TonicExporterBui
exporter_builder
}
+#[derive(Debug, Clone)]
+enum TraceUrlAssert {
+ Match(String),
+ EndsWith(String),
+}
+
+impl TraceUrlAssert {
+ fn compare_url(&self, url: &str) -> bool {
+ match self {
+ Self::Match(value) => url == value,
+ Self::EndsWith(end) => url.ends_with(end),
+ }
+ }
+}
+
+impl From<String> for TraceUrlAssert {
+ fn from(value: String) -> Self {
+ match value {
+ url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()),
+ url => Self::Match(url),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+struct TraceAssertion {
+ clauses: Option<Vec<TraceUrlAssert>>,
+ /// default behaviour for tracing if no condition is provided
+ default: bool,
+}
+
+impl TraceAssertion {
+ ///
+ /// Should the provided url be traced
+ ///
+ fn should_trace_url(&self, url: &str) -> bool {
+ match &self.clauses {
+ Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)),
+ None => self.default,
+ }
+ }
+}
+
+///
+/// Conditional Sampler for providing control on url based tracing
+///
+#[derive(Clone, Debug)]
+struct ConditionalSampler<T: trace::ShouldSample + Clone + 'static>(TraceAssertion, T);
+
+impl<T: trace::ShouldSample + Clone + 'static> trace::ShouldSample for ConditionalSampler<T> {
+ fn should_sample(
+ &self,
+ parent_context: Option<&opentelemetry::Context>,
+ trace_id: opentelemetry::trace::TraceId,
+ name: &str,
+ span_kind: &opentelemetry::trace::SpanKind,
+ attributes: &opentelemetry::trace::OrderMap<opentelemetry::Key, opentelemetry::Value>,
+ links: &[opentelemetry::trace::Link],
+ instrumentation_library: &opentelemetry::InstrumentationLibrary,
+ ) -> opentelemetry::trace::SamplingResult {
+ match attributes
+ .get(&opentelemetry::Key::new("http.route"))
+ .map_or(self.0.default, |inner| {
+ self.0.should_trace_url(&inner.as_str())
+ }) {
+ true => self.1.should_sample(
+ parent_context,
+ trace_id,
+ name,
+ span_kind,
+ attributes,
+ links,
+ instrumentation_library,
+ ),
+ false => opentelemetry::trace::SamplingResult {
+ decision: opentelemetry::trace::SamplingDecision::Drop,
+ attributes: Vec::new(),
+ trace_state: match parent_context {
+ Some(ctx) => ctx.span().span_context().trace_state().clone(),
+ None => TraceState::default(),
+ },
+ },
+ }
+ }
+}
+
fn setup_tracing_pipeline(
config: &config::LogTelemetry,
service_name: &str,
@@ -140,9 +227,16 @@ fn setup_tracing_pipeline(
global::set_text_map_propagator(TraceContextPropagator::new());
let mut trace_config = trace::config()
- .with_sampler(trace::Sampler::TraceIdRatioBased(
- config.sampling_rate.unwrap_or(1.0),
- ))
+ .with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler(
+ TraceAssertion {
+ clauses: config
+ .route_to_trace
+ .clone()
+ .map(|inner| inner.into_iter().map(Into::into).collect()),
+ default: false,
+ },
+ trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)),
+ ))))
.with_resource(Resource::new(vec![KeyValue::new(
"service.name",
service_name.to_owned(),
diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs
index ad543b1942a..ceed3da81b3 100644
--- a/crates/storage_impl/src/config.rs
+++ b/crates/storage_impl/src/config.rs
@@ -9,4 +9,5 @@ pub struct Database {
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
+ pub queue_strategy: bb8::QueueStrategy,
}
diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs
index f9a7450b1cd..a09f1b75256 100644
--- a/crates/storage_impl/src/database/store.rs
+++ b/crates/storage_impl/src/database/store.rs
@@ -88,6 +88,7 @@ pub async fn diesel_make_pg_pool(
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let mut pool = bb8::Pool::builder()
.max_size(database.pool_size)
+ .queue_strategy(database.queue_strategy)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
if test_transaction {
| 2023-10-09T12:09:44Z |
## Description
This change introduces a new middleware for tracing requests with the specified url. Providing a filtration mechanism.
This change also includes changing the bb8 queue strategy from FIFO to LIFO.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 14cf0e735a31a823a1909a2886a3fedb4a9ea3e1 | [
"config/config.example.toml",
"crates/router/src/configs/defaults.rs",
"crates/router/src/configs/kms.rs",
"crates/router/src/configs/settings.rs",
"crates/router_env/src/logger/config.rs",
"crates/router_env/src/logger/setup.rs",
"crates/storage_impl/src/config.rs",
"crates/storage_impl/src/database/... | ||
juspay/hyperswitch | juspay__hyperswitch-2510 | Bug: [REFACTOR] remove ansi escape characters from logs when format is set to json
### Feature Description
Fix log formatting by removing the ansi escape characters from logs when the log format is set to json
### Possible Implementation
This will help in making the logs much cleaner as opposed to having ansi escape characters in json format. Set color mode of Report to None
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/Cargo.lock b/Cargo.lock
index 9e026101d1a..abecaf6ae24 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4179,6 +4179,7 @@ version = "0.1.0"
dependencies = [
"cargo_metadata 0.15.4",
"config",
+ "error-stack",
"gethostname",
"once_cell",
"opentelemetry",
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index c72220f52d2..1181685d723 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -10,6 +10,7 @@ license.workspace = true
[dependencies]
cargo_metadata = "0.15.4"
config = { version = "0.13.3", features = ["toml"] }
+error-stack = "0.3.1"
gethostname = "0.4.3"
once_cell = "1.18.0"
opentelemetry = { version = "0.19.0", features = ["rt-tokio-current-thread", "metrics"] }
diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs
index 313e64d0e9c..78cbe9f342f 100644
--- a/crates/router_env/src/logger/setup.rs
+++ b/crates/router_env/src/logger/setup.rs
@@ -101,6 +101,7 @@ pub fn setup(
subscriber.with(logging_layer).init();
}
config::LogFormat::Json => {
+ error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
let logging_layer =
FormattingLayer::new(service_name, console_writer).with_filter(console_filter);
subscriber.with(logging_layer).init();
| 2023-10-09T11:46:27Z |
## Description
<!-- Describe your changes in detail -->
This PR includes changes for removing the ansi escape characters from logs when the logs format is set to json
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This will help in making the logs much cleaner as opposed to having ansi escape characters in json format
# | e02838eb5d3da97ef573926ded4a318ed24b6f1c |
Current log -

Log due to current PR changes -

| [
"Cargo.lock",
"crates/router_env/Cargo.toml",
"crates/router_env/src/logger/setup.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2305 | Bug: [FEATURE]: [Multisafepay] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs
index 1629f2ab36d..120ea23d7ca 100644
--- a/crates/router/src/connector/multisafepay.rs
+++ b/crates/router/src/connector/multisafepay.rs
@@ -165,7 +165,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key
.expose();
- let ord_id = req.payment_id.clone();
+ let ord_id = req.connector_request_reference_id.clone();
Ok(format!("{url}v1/json/orders/{ord_id}?api_key={api_key}"))
}
@@ -341,7 +341,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key
.expose();
- let ord_id = req.payment_id.clone();
+ let ord_id = req.connector_request_reference_id.clone();
Ok(format!(
"{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}"
))
@@ -428,7 +428,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.change_context(errors::ConnectorError::FailedToObtainAuthType)?
.api_key
.expose();
- let ord_id = req.payment_id.clone();
+ let ord_id = req.connector_request_reference_id.clone();
Ok(format!(
"{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}"
))
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index dfc7bad277d..a8366fadf81 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -380,7 +380,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques
Ok(Self {
payment_type,
gateway,
- order_id: item.payment_id.to_string(),
+ order_id: item.connector_request_reference_id.to_string(),
currency: item.request.currency.to_string(),
amount: item.request.amount,
description,
| 2023-10-09T07:12:04Z |
## Description
- Addressing Issue [#2305](https://github.com/juspay/hyperswitch/issues/2305): Use connector_request_reference_id as reference to the connector
- Modified two files in `hyperswitch/crates/router/src/connector/`
- `multisafepay.rs`
- `multisafepay/transformers.rs`
- Rebase with changes from commit [12b5341](https://github.com/juspay/hyperswitch/commit/12b534197276ccc4aa9575e6b518bcc50b597bee)
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | e02838eb5d3da97ef573926ded4a318ed24b6f1c | [
"crates/router/src/connector/multisafepay.rs",
"crates/router/src/connector/multisafepay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2320 | Bug: [FEATURE]: [Worldline] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index f1267c09766..d02ab60c8b9 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -40,11 +40,18 @@ pub struct AmountOfMoney {
pub currency_code: String,
}
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct References {
+ pub merchant_reference: String,
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Order {
pub amount_of_money: AmountOfMoney,
pub customer: Customer,
+ pub references: References,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -202,6 +209,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest {
currency_code: item.request.currency.to_string().to_uppercase(),
},
customer,
+ references: References {
+ merchant_reference: item.connector_request_reference_id.clone(),
+ },
};
let shipping = item
| 2023-10-08T15:33:20Z |
## Description
Replace `payment_id` with `connector_request_reference_id` in worldline.
Closes #2320
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 53d760460305e16f03d86f699acb035151dfdfad | [
"crates/router/src/connector/worldline/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2323 | Bug: [FEATURE]: [Authorizedotnet] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index a2faeddb50f..1b7480f78e4 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -540,7 +540,9 @@ impl<F, T>
mandate_reference: None,
connector_metadata: metadata,
network_txn_id: transaction_response.network_trans_id.clone(),
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ transaction_response.transaction_id.clone(),
+ ),
}),
},
..item.data
@@ -604,7 +606,9 @@ impl<F, T>
mandate_reference: None,
connector_metadata: metadata,
network_txn_id: transaction_response.network_trans_id.clone(),
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ transaction_response.transaction_id.clone(),
+ ),
}),
},
..item.data
@@ -887,13 +891,13 @@ impl<F, Req>
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
- transaction.transaction_id,
+ transaction.transaction_id.clone(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(transaction.transaction_id.clone()),
}),
status: payment_status,
..item.data
| 2023-10-08T15:12:53Z |
## Description
<!-- Describe your changes in detail -->
Implement `connector_response_reference_id` as reference for Authorizedotnet
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Resolves #2323
# | 3f1e7c2152a839a6fe69f60b906277ca831e7611 |
Manually
| [
"crates/router/src/connector/authorizedotnet/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2303 | Bug: [FEATURE]: [Klarna] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index b31d56d51b9..31e356d4765 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -45,6 +45,7 @@ pub struct KlarnaPaymentsRequest {
order_amount: i64,
purchase_country: String,
purchase_currency: enums::Currency,
+ merchant_reference1: String,
}
#[derive(Default, Debug, Deserialize)]
@@ -140,6 +141,7 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP
total_amount: i64::from(data.quantity) * (data.amount),
})
.collect(),
+ merchant_reference1: item.router_data.connector_request_reference_id.clone(),
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "product_name"
| 2023-10-08T05:56:23Z |
## Description
<!-- Describe your changes in detail -->
Included a `merchant_reference1` field in `KlarnaPaymentsRequest` and map it to `connector_request_reference_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).
-->
# | b5feab61d950921c75267ad88e944e7e2c4af3ca | [
"crates/router/src/connector/klarna/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2309 | Bug: [FEATURE]: [Nuvei] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index cf7d480e0c1..2fd1a9c272f 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -384,7 +384,7 @@ impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRe
let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
let merchant_id = connector_meta.merchant_id;
let merchant_site_id = connector_meta.merchant_site_id;
- let client_request_id = item.attempt_id.clone();
+ let client_request_id = item.connector_request_reference_id.clone();
let time_stamp = date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now());
let merchant_secret = connector_meta.merchant_secret;
Ok(Self {
@@ -737,7 +737,7 @@ impl<F>
amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?,
currency: item.request.currency,
connector_auth_type: item.connector_auth_type.clone(),
- client_request_id: item.attempt_id.clone(),
+ client_request_id: item.connector_request_reference_id.clone(),
session_token: data.1,
capture_method: item.request.capture_method,
..Default::default()
@@ -914,7 +914,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay
amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?,
currency: item.request.currency,
connector_auth_type: item.connector_auth_type.clone(),
- client_request_id: item.attempt_id.clone(),
+ client_request_id: item.connector_request_reference_id.clone(),
session_token: data.1,
capture_method: item.request.capture_method,
..Default::default()
@@ -1018,7 +1018,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Self::try_from(NuveiPaymentRequestData {
- client_request_id: item.attempt_id.clone(),
+ client_request_id: item.connector_request_reference_id.clone(),
connector_auth_type: item.connector_auth_type.clone(),
amount: utils::to_currency_base_unit(
item.request.amount_to_capture,
@@ -1034,7 +1034,7 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundExecuteRouterData) -> Result<Self, Self::Error> {
Self::try_from(NuveiPaymentRequestData {
- client_request_id: item.attempt_id.clone(),
+ client_request_id: item.connector_request_reference_id.clone(),
connector_auth_type: item.connector_auth_type.clone(),
amount: utils::to_currency_base_unit(
item.request.refund_amount,
@@ -1061,7 +1061,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Self::try_from(NuveiPaymentRequestData {
- client_request_id: item.attempt_id.clone(),
+ client_request_id: item.connector_request_reference_id.clone(),
connector_auth_type: item.connector_auth_type.clone(),
amount: utils::to_currency_base_unit(
item.request.get_amount()?,
| 2023-10-08T01:05:10Z |
## Description
<!-- Describe your changes in detail -->
`connector_request_reference_id` is being passed as "attempt_id" or "payment_id" to improve consistency in transmitting payment information to the Nuvei payment gateway.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 3f1e7c2152a839a6fe69f60b906277ca831e7611 | [
"crates/router/src/connector/nuvei/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2347 | Bug: [FEATURE]: [Shift4] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 23c91e48d8c..0dd3b858349 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -717,6 +717,7 @@ impl<T, F>
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
+ let connector_id = types::ResponseId::ConnectorTransactionId(item.response.id.clone());
Ok(Self {
status: enums::AttemptStatus::foreign_from((
item.response.captured,
@@ -727,7 +728,7 @@ impl<T, F>
item.response.status,
)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: connector_id,
redirection_data: item
.response
.flow
@@ -737,7 +738,7 @@ impl<T, F>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
}),
..item.data
})
| 2023-10-08T00:13:23Z |
## Description
<!-- Describe your changes in detail -->
fixes #2316
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 31431e41357d4d3d12668fa0d678cce0b3d86611 | [
"crates/router/src/connector/shift4/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2316 | Bug: [FEATURE]: [Shift4] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 23c91e48d8c..0dd3b858349 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -717,6 +717,7 @@ impl<T, F>
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
+ let connector_id = types::ResponseId::ConnectorTransactionId(item.response.id.clone());
Ok(Self {
status: enums::AttemptStatus::foreign_from((
item.response.captured,
@@ -727,7 +728,7 @@ impl<T, F>
item.response.status,
)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: connector_id,
redirection_data: item
.response
.flow
@@ -737,7 +738,7 @@ impl<T, F>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.id),
}),
..item.data
})
| 2023-10-08T00:13:23Z |
## Description
<!-- Describe your changes in detail -->
fixes #2316
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 31431e41357d4d3d12668fa0d678cce0b3d86611 | [
"crates/router/src/connector/shift4/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2329 | Bug: [FEATURE]: [Fiserv] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index 6c6c346dccc..c9c2f0c4087 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -315,7 +315,9 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ gateway_resp.transaction_processing_details.order_id,
+ ),
}),
..item.data
})
@@ -350,7 +352,13 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ gateway_resp
+ .gateway_response
+ .transaction_processing_details
+ .order_id
+ .clone(),
+ ),
}),
..item.data
})
| 2023-10-07T15:44:04Z | Update connector_response_reference_id to use gateway_resp.transaction_processing_details.order_id in fiserv transformers.
Fixes #2329
## 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).
-->
# | 3f1e7c2152a839a6fe69f60b906277ca831e7611 | [
"crates/router/src/connector/fiserv/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2290 | Bug: [REFACTOR]: [Worldpay] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 61d04a8e9f1..d31f4d65e78 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -217,7 +217,13 @@ impl From<EventType> for enums::AttemptStatus {
EventType::CaptureFailed => Self::CaptureFailed,
EventType::Refused => Self::Failure,
EventType::Charged | EventType::SentForSettlement => Self::Charged,
- _ => Self::Pending,
+ EventType::Cancelled
+ | EventType::SentForRefund
+ | EventType::RefundFailed
+ | EventType::Refunded
+ | EventType::Error
+ | EventType::Expired
+ | EventType::Unknown => Self::Pending,
}
}
}
@@ -227,7 +233,16 @@ impl From<EventType> for enums::RefundStatus {
match value {
EventType::Refunded => Self::Success,
EventType::RefundFailed => Self::Failure,
- _ => Self::Pending,
+ EventType::Authorized
+ | EventType::Cancelled
+ | EventType::Charged
+ | EventType::SentForRefund
+ | EventType::Refused
+ | EventType::Error
+ | EventType::SentForSettlement
+ | EventType::Expired
+ | EventType::CaptureFailed
+ | EventType::Unknown => Self::Pending,
}
}
}
| 2023-10-07T11:57:43Z |
## Description
Instead of relying on a default match case `_` I have added conditions for each type in match statements.
Changes are made at https://github.com/juspay/hyperswitch/blob/main/crates/router/src/connector/worldpay/transformers.rs
## Motivation and Context
Closes #2290 | adad77f0433bb7691f4313a27e021849cd5a6c1d | [
"crates/router/src/connector/worldpay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2287 | Bug: [REFACTOR]: [Trustpay] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/Cargo.lock b/Cargo.lock
index cca3b6f58d9..9e026101d1a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -393,6 +393,7 @@ dependencies = [
"serde",
"serde_json",
"strum 0.24.1",
+ "thiserror",
"time 0.3.22",
"url",
"utoipa",
@@ -471,18 +472,6 @@ dependencies = [
"serde_json",
]
-[[package]]
-name = "async-bb8-diesel"
-version = "0.1.0"
-source = "git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5#9a71d142726dbc33f41c1fd935ddaa79841c7be5"
-dependencies = [
- "async-trait",
- "bb8",
- "diesel",
- "thiserror",
- "tokio",
-]
-
[[package]]
name = "async-bb8-diesel"
version = "0.1.0"
@@ -735,39 +724,6 @@ dependencies = [
"tracing",
]
-[[package]]
-name = "aws-sdk-s3"
-version = "0.25.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "392b9811ca489747ac84349790e49deaa1f16631949e7dd4156000251c260eae"
-dependencies = [
- "aws-credential-types",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-sigv4",
- "aws-smithy-async",
- "aws-smithy-checksums",
- "aws-smithy-client",
- "aws-smithy-eventstream",
- "aws-smithy-http",
- "aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-smithy-xml",
- "aws-types",
- "bytes",
- "http",
- "http-body",
- "once_cell",
- "percent-encoding",
- "regex",
- "tokio-stream",
- "tower",
- "tracing",
- "url",
-]
-
[[package]]
name = "aws-sdk-s3"
version = "0.28.0"
@@ -1204,7 +1160,16 @@ dependencies = [
"cc",
"cfg-if",
"constant_time_eq",
- "digest",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
+dependencies = [
+ "generic-array",
]
[[package]]
@@ -1853,9 +1818,9 @@ dependencies = [
name = "diesel_models"
version = "0.1.0"
dependencies = [
- "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)",
+ "async-bb8-diesel",
"aws-config",
- "aws-sdk-s3 0.28.0",
+ "aws-sdk-s3",
"common_enums",
"common_utils",
"diesel",
@@ -1882,13 +1847,22 @@ dependencies = [
"syn 2.0.29",
]
+[[package]]
+name = "digest"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
- "block-buffer",
+ "block-buffer 0.10.4",
"crypto-common",
"subtle",
]
@@ -1940,7 +1914,7 @@ checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257"
name = "drainer"
version = "0.1.0"
dependencies = [
- "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)",
+ "async-bb8-diesel",
"bb8",
"clap",
"common_utils",
@@ -1988,20 +1962,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"
dependencies = [
"atty",
- "humantime 1.3.0",
- "log",
- "regex",
- "termcolor",
-]
-
-[[package]]
-name = "env_logger"
-version = "0.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0"
-dependencies = [
- "humantime 2.1.0",
- "is-terminal",
+ "humantime",
"log",
"regex",
"termcolor",
@@ -2192,7 +2153,7 @@ dependencies = [
"rand 0.8.5",
"redis-protocol",
"semver",
- "sha-1",
+ "sha-1 0.10.1",
"tokio",
"tokio-stream",
"tokio-util",
@@ -2522,7 +2483,7 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -2589,12 +2550,6 @@ dependencies = [
"quick-error",
]
-[[package]]
-name = "humantime"
-version = "2.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
-
[[package]]
name = "hyper"
version = "0.14.27"
@@ -2779,18 +2734,6 @@ version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f"
-[[package]]
-name = "is-terminal"
-version = "0.4.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f"
-dependencies = [
- "hermit-abi 0.3.1",
- "io-lifetimes",
- "rustix",
- "windows-sys 0.48.0",
-]
-
[[package]]
name = "itertools"
version = "0.10.5"
@@ -3070,7 +3013,7 @@ version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca"
dependencies = [
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -3321,6 +3264,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d11de466f4a3006fe8a5e7ec84e93b79c70cb992ae0aa0eb631ad2df8abfe2"
+[[package]]
+name = "opaque-debug"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
+
[[package]]
name = "openssl"
version = "0.10.55"
@@ -3680,7 +3629,7 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d"
dependencies = [
- "env_logger 0.7.1",
+ "env_logger",
"log",
]
@@ -4134,11 +4083,11 @@ dependencies = [
"actix-rt",
"actix-web",
"api_models",
- "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)",
+ "async-bb8-diesel",
"async-trait",
"awc",
"aws-config",
- "aws-sdk-s3 0.28.0",
+ "aws-sdk-s3",
"base64 0.21.2",
"bb8",
"blake3",
@@ -4151,6 +4100,7 @@ dependencies = [
"derive_deref",
"diesel",
"diesel_models",
+ "digest 0.9.0",
"dyn-clone",
"encoding_rs",
"error-stack",
@@ -4189,6 +4139,7 @@ dependencies = [
"serde_urlencoded",
"serde_with",
"serial_test",
+ "sha-1 0.9.8",
"signal-hook",
"signal-hook-tokio",
"storage_impl",
@@ -4428,36 +4379,19 @@ dependencies = [
name = "scheduler"
version = "0.1.0"
dependencies = [
- "actix-multipart",
- "actix-rt",
- "actix-web",
- "api_models",
- "async-bb8-diesel 0.1.0 (git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5)",
"async-trait",
- "aws-config",
- "aws-sdk-s3 0.25.1",
- "cards",
- "clap",
"common_utils",
- "diesel",
"diesel_models",
- "dyn-clone",
- "env_logger 0.10.0",
"error-stack",
"external_services",
- "frunk",
- "frunk_core",
"futures",
- "infer 0.13.0",
"masking",
"once_cell",
"rand 0.8.5",
"redis_interface",
- "router_derive",
"router_env",
"serde",
"serde_json",
- "signal-hook",
"signal-hook-tokio",
"storage_impl",
"strum 0.24.1",
@@ -4678,6 +4612,19 @@ dependencies = [
"syn 2.0.29",
]
+[[package]]
+name = "sha-1"
+version = "0.9.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6"
+dependencies = [
+ "block-buffer 0.9.0",
+ "cfg-if",
+ "cpufeatures",
+ "digest 0.9.0",
+ "opaque-debug",
+]
+
[[package]]
name = "sha-1"
version = "0.10.1"
@@ -4686,7 +4633,7 @@ checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c"
dependencies = [
"cfg-if",
"cpufeatures",
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -4697,7 +4644,7 @@ checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
dependencies = [
"cfg-if",
"cpufeatures",
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -4708,7 +4655,7 @@ checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
dependencies = [
"cfg-if",
"cpufeatures",
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -4824,7 +4771,7 @@ version = "0.1.0"
dependencies = [
"actix-web",
"api_models",
- "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)",
+ "async-bb8-diesel",
"async-trait",
"bb8",
"bytes",
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index e9ef7f4c288..5ca4bd1ac3d 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -238,7 +238,23 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
api_models::payments::BankRedirectData::Blik { .. } => Ok(Self::Blik),
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api_models::payments::BankRedirectData::BancontactCard { .. }
+ | api_models::payments::BankRedirectData::Bizum {}
+ | api_models::payments::BankRedirectData::Interac { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
+ | api_models::payments::BankRedirectData::OpenBankingUk { .. }
+ | api_models::payments::BankRedirectData::Przelewy24 { .. }
+ | api_models::payments::BankRedirectData::Trustly { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("trustpay"),
+ )
+ .into())
+ }
}
}
}
@@ -419,7 +435,20 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
auth,
)
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::Wallet(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("trustpay"),
+ )
+ .into()),
}
}
}
| 2023-10-06T16:14:34Z |
## Description
<!-- Describe your changes in detail -->
Handling the unhandled variants for trustpay
Issue #2287
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | ba2efac4fa2af22f81b0841350a334bc36e91022 | [
"Cargo.lock",
"crates/router/src/connector/trustpay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2327 | Bug: [FEATURE]: [Cybersource] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 106ce2e3c29..3558f752841 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -275,6 +275,13 @@ pub struct CybersourcePaymentsResponse {
id: String,
status: CybersourcePaymentStatus,
error_information: Option<CybersourceErrorInformation>,
+ client_reference_information: Option<ClientReferenceInformation>,
+}
+
+#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientReferenceInformation {
+ code: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)]
@@ -313,12 +320,18 @@ impl<F, T>
status_code: item.http_code,
}),
_ => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .client_reference_information
+ .map(|cref| cref.code)
+ .unwrap_or(Some(item.response.id)),
}),
},
..item.data
@@ -331,6 +344,7 @@ impl<F, T>
pub struct CybersourceTransactionResponse {
id: String,
application_information: ApplicationInformation,
+ client_reference_information: Option<ClientReferenceInformation>,
}
#[derive(Debug, Deserialize)]
@@ -378,12 +392,16 @@ impl<F, T>
item.response.application_information.status.into(),
),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .client_reference_information
+ .map(|cref| cref.code)
+ .unwrap_or(Some(item.response.id)),
}),
..item.data
})
| 2023-10-05T19:02:15Z |
## Description
Use connector_response_reference_id as reference to merchant for Cybersource
Fixes #2327
## Motivation and Context
fixes #2327
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 503823408b782968fb59f6ff5d7df417b9aa7dbe | [
"crates/router/src/connector/cybersource/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2326 | Bug: [FEATURE]: [Coinbase] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index acc08e36e49..6cc097bc9d8 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -136,7 +136,7 @@ impl<F, T>
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id);
+ let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -145,7 +145,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.data.id.clone()),
}),
|context| {
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
@@ -155,7 +155,7 @@ impl<F, T>
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
}),
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.data.id),
})
},
);
| 2023-10-05T17:50:31Z |
## Description
<!-- Describe your changes in detail -->
Relevant documentation [here](https://docs.cloud.coinbase.com/commerce/docs/webhooks-events). I'm not 100% sure what `code` is in the documentation but they haven't provided more clarity, the only other identifier for the transaction is id, so I've used that.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Fixes #2326
# | bb2ba0815330578295de8036ea1a5e6d66a36277 | [
"crates/router/src/connector/coinbase/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2308 | Bug: [FEATURE]: [Noon] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 6c3084a75e4..3e584e204ae 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -264,7 +264,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
currency,
channel: NoonChannels::Web,
category,
- reference: item.payment_id.clone(),
+ reference: item.connector_request_reference_id.clone(),
name,
};
let payment_action = if item.request.is_auto_capture()? {
| 2023-10-05T17:35:30Z |
## Description
<!-- Describe your changes in detail -->
Closes #2308
Use `connector_request_reference_id` instead of `payment_id` as Order reference
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 414996592b3016bfa9f3399319c6e02ccd333c68 | [
"crates/router/src/connector/noon/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2276 | Bug: [REFACTOR]: [NMI] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index a57ac4271d0..3f64ff9eaca 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -112,14 +112,51 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod {
api_models::payments::WalletData::ApplePay(ref applepay_data) => {
Ok(Self::from(applepay_data))
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment Method".to_string(),
- ))
- .into_report(),
+ api_models::payments::WalletData::AliPayQr(_)
+ | api_models::payments::WalletData::AliPayRedirect(_)
+ | api_models::payments::WalletData::AliPayHkRedirect(_)
+ | api_models::payments::WalletData::MomoRedirect(_)
+ | api_models::payments::WalletData::KakaoPayRedirect(_)
+ | api_models::payments::WalletData::GoPayRedirect(_)
+ | api_models::payments::WalletData::GcashRedirect(_)
+ | api_models::payments::WalletData::ApplePayRedirect(_)
+ | api_models::payments::WalletData::ApplePayThirdPartySdk(_)
+ | api_models::payments::WalletData::DanaRedirect {}
+ | api_models::payments::WalletData::GooglePayRedirect(_)
+ | api_models::payments::WalletData::GooglePayThirdPartySdk(_)
+ | api_models::payments::WalletData::MbWayRedirect(_)
+ | api_models::payments::WalletData::MobilePayRedirect(_)
+ | api_models::payments::WalletData::PaypalRedirect(_)
+ | api_models::payments::WalletData::PaypalSdk(_)
+ | api_models::payments::WalletData::SamsungPay(_)
+ | api_models::payments::WalletData::TwintRedirect {}
+ | api_models::payments::WalletData::VippsRedirect {}
+ | api_models::payments::WalletData::TouchNGoRedirect(_)
+ | api_models::payments::WalletData::WeChatPayRedirect(_)
+ | api_models::payments::WalletData::WeChatPayQr(_)
+ | api_models::payments::WalletData::CashappQr(_)
+ | api_models::payments::WalletData::SwishQr(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "nmi",
+ })
+ .into_report()
+ }
},
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment Method".to_string(),
- ))
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "nmi",
+ })
.into_report(),
}
}
| 2023-10-05T15:12:18Z |
## Description
<!-- Describe your changes in detail -->
Adds the error handles for all unhandled variants
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Wanted to contribute to open source
# | 414996592b3016bfa9f3399319c6e02ccd333c68 | [
"crates/router/src/connector/nmi/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2330 | Bug: [FEATURE]: [Forte] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index dcc8b97788d..bc7c55c4f87 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -259,7 +259,7 @@ impl<F, T>
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(transaction_id.to_string()),
}),
..item.data
})
@@ -306,7 +306,7 @@ impl<F, T>
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(transaction_id.to_string()),
}),
..item.data
})
@@ -362,19 +362,18 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
fn try_from(
item: types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
) -> Result<Self, Self::Error> {
+ let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transaction_id,
- ),
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.transaction_id.to_string()),
}),
amount_captured: None,
..item.data
@@ -441,7 +440,7 @@ impl<F, T>
auth_id: item.response.authorization_code,
})),
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(transaction_id.to_string()),
}),
..item.data
})
| 2023-10-05T07:22:01Z |
## Description
<!-- Describe your changes in detail -->
Addreses issue #2330
Updated `connector_response_reference_id` to use `transaction_id` from Forte response.
Forte 'POST' Payment Docs -> https://restdocs.forte.net/#c35427927-d955-4087-88d3-f99413ed91c2
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | bb2ba0815330578295de8036ea1a5e6d66a36277 |
This code was tested manually, I was able to verify the updated `connector_response_reference_id` in the response to the POST request to create a payment.
<img width="1382" alt="forte_response" src="https://github.com/juspay/hyperswitch/assets/29712119/ffd4859c-e23d-48bb-800d-7acb25b0ebcc">
| [
"crates/router/src/connector/forte/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2344 | Bug: [FEATURE]: [PayU] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs
index c43e59ac76c..9a2e14215c7 100644
--- a/crates/router/src/connector/payu/transformers.rs
+++ b/crates/router/src/connector/payu/transformers.rs
@@ -194,12 +194,17 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .ext_order_id
+ .or(Some(item.response.order_id)),
}),
amount_captured: None,
..item.data
@@ -326,12 +331,17 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .ext_order_id
+ .or(Some(item.response.order_id)),
}),
amount_captured: None,
..item.data
@@ -461,7 +471,10 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: order
+ .ext_order_id
+ .clone()
+ .or(Some(order.order_id.clone())),
}),
amount_captured: Some(
order
| 2023-10-04T16:32:38Z |
## Description
Fixes #2344
## Motivation and Context
Fixes #2344
# | b5cc7483f99dcd995b9022d21c94f2f9710ea7fe | [
"crates/router/src/connector/payu/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2336 | Bug: [FEATURE]: [Multisafepay] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 2fa8a4c9030..dfc7bad277d 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -530,7 +530,9 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.data.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.data.order_id.clone(),
+ ),
redirection_data,
mandate_reference: item
.response
@@ -543,7 +545,7 @@ impl<F, T>
}),
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.data.order_id.clone()),
}),
..item.data
})
| 2023-10-04T16:17:19Z |
## Description
Updated the `connector_response_reference_id` value from the response.
closes #2336
## Motivation and Context
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as payment_id, attempt_id, and connector_transaction_id for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
# | 65ca5f12da54715e5db785d122e2ec9714147c68 | [
"crates/router/src/connector/multisafepay/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2328 | Bug: [FEATURE]: [Dlocal] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index e6db1503e59..8558836372e 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -250,6 +250,7 @@ pub struct DlocalPaymentsResponse {
status: DlocalPaymentStatus,
id: String,
three_dsecure: Option<ThreeDSecureResData>,
+ order_id: String,
}
impl<F, T>
@@ -269,12 +270,12 @@ impl<F, T>
});
let response = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
@@ -288,6 +289,7 @@ impl<F, T>
pub struct DlocalPaymentsSyncResponse {
status: DlocalPaymentStatus,
id: String,
+ order_id: String,
}
impl<F, T>
@@ -307,12 +309,14 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
}),
..item.data
})
@@ -323,6 +327,7 @@ impl<F, T>
pub struct DlocalPaymentsCaptureResponse {
status: DlocalPaymentStatus,
id: String,
+ order_id: String,
}
impl<F, T>
@@ -342,12 +347,14 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
}),
..item.data
})
@@ -356,7 +363,7 @@ impl<F, T>
pub struct DlocalPaymentsCancelResponse {
status: DlocalPaymentStatus,
- id: String,
+ order_id: String,
}
impl<F, T>
@@ -376,12 +383,14 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
}),
..item.data
})
| 2023-10-04T11:16:52Z |
## Description
<!-- Describe your changes in detail -->
I have populated the 'id' which is provided as a payment-specific ID in their response to then be populated as 'connector_reference_id'. As per the docs they don't require a payment reference ID in their payment requests. So populated the existing id.

## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
If it fixes an open issue, please link to the issue here.
It fixes an open issue . Closes #2328
# | d177b4d94f08fb8ef44b5c07ec1bdc771baa016d | [
"crates/router/src/connector/dlocal/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2339 | Bug: [FEATURE]: [Noon] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index d7dc832b445..6c3084a75e4 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -356,6 +356,7 @@ pub struct NoonPaymentsOrderResponse {
id: u64,
error_code: u64,
error_message: Option<String>,
+ reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -410,14 +411,20 @@ impl<F, T>
reason: Some(error_message),
status_code: item.http_code,
}),
- _ => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(order.id.to_string()),
- redirection_data,
- mandate_reference,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- }),
+ _ => {
+ let connector_response_reference_id =
+ order.reference.or(Some(order.id.to_string()));
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ order.id.to_string(),
+ ),
+ redirection_data,
+ mandate_reference,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id,
+ })
+ }
},
..item.data
})
@@ -660,6 +667,7 @@ impl From<NoonWebhookObject> for NoonPaymentsResponse {
//For successful payments Noon Always populates error_code as 0.
error_code: 0,
error_message: None,
+ reference: None,
},
checkout_data: None,
subscription: None,
| 2023-10-04T10:01:42Z |
## Description
I have added `reference` that's sent to noon payments order to the `TransactionResponse` in `transformer.rs` of noon that's present in the `connector` directory.
https://github.com/juspay/hyperswitch/blob/main/crates/router/src/connector/noon/transformers.rs
## Motivation and Context
Closes #2339 | ab2cde799371a66eb045cf8b20431b3b108dac44 | [
"crates/router/src/connector/noon/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2250 | Bug: [FEATURE]: [Worldpay] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 0c69cd981bb..60a5fc83045 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -56,6 +56,10 @@ impl ConnectorCommon for Worldpay {
"worldpay"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/vnd.worldpay.payments-v6+json"
}
@@ -428,7 +432,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_request = WorldpayPaymentsRequest::try_from(req)?;
+ let connector_router_data = worldpay::WorldpayRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_request = WorldpayPaymentsRequest::try_from(&connector_router_data)?;
let worldpay_payment_request = types::RequestBody::log_and_get_request_body(
&connector_request,
ext_traits::Encode::<WorldpayPaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 3d467f4198f..aabe27fc4eb 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -3,15 +3,44 @@ use common_utils::errors::CustomResult;
use diesel_models::enums;
use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
+use serde::Serialize;
use super::{requests::*, response::*};
use crate::{
connector::utils,
consts,
core::errors,
- types::{self, api},
+ types::{self, api, PaymentsAuthorizeData, PaymentsResponseData},
};
+#[derive(Debug, Serialize)]
+pub struct WorldpayRouterData<T> {
+ amount: i64,
+ router_data: T,
+}
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for WorldpayRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (_currency_unit, _currency, amount, item): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
fn fetch_payment_instrument(
payment_method: api::PaymentMethodData,
) -> CustomResult<PaymentInstrument, errors::ConnectorError> {
@@ -100,29 +129,48 @@ fn fetch_payment_instrument(
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for WorldpayPaymentsRequest {
+impl
+ TryFrom<
+ &WorldpayRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ > for WorldpayPaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+
+ fn try_from(
+ item: &WorldpayRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ >,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
instruction: Instruction {
value: PaymentValue {
- amount: item.request.amount,
- currency: item.request.currency.to_string(),
+ amount: item.amount,
+ currency: item.router_data.request.currency.to_string(),
},
narrative: InstructionNarrative {
- line1: item.merchant_id.clone().replace('_', "-"),
+ line1: item.router_data.merchant_id.clone().replace('_', "-"),
..Default::default()
},
payment_instrument: fetch_payment_instrument(
- item.request.payment_method_data.clone(),
+ item.router_data.request.payment_method_data.clone(),
)?,
debt_repayment: None,
},
merchant: Merchant {
- entity: item.attempt_id.clone().replace('_', "-"),
+ entity: item.router_data.attempt_id.clone().replace('_', "-"),
..Default::default()
},
- transaction_reference: item.attempt_id.clone(),
+ transaction_reference: item.router_data.attempt_id.clone(),
channel: None,
customer: None,
})
diff --git a/package.json b/package.json
index 0766efdcc17..45d2be3153b 100644
--- a/package.json
+++ b/package.json
@@ -6,4 +6,4 @@
"devDependencies": {
"newman": "git+ssh://git@github.com:knutties/newman.git#7106e194c15d49d066fa09d9a2f18b2238f3dba8"
}
-}
+}
\ No newline at end of file
| 2023-10-03T16:27:58Z |
## Description
<!-- Describe your changes in detail -->
This pull request implements the get_currency_unit from the ConnectorCommon trait for the Worldpay connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Worldpay it accepts currency as Minor units.
### Links to the files with corresponding changes.
1. crates\router\src\connector\worldpay.rs
2. crates\router\src\connector\worldpay\transformers.rs
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #2250.
# | b5b3625efdd70c619e9fc206721c4bedf8af30a4 | I tried setting up and testing using VS code and codesandbox but was not able to do it.
So kindly review the changes and do let me know if any further issues.
| [
"crates/router/src/connector/worldpay.rs",
"crates/router/src/connector/worldpay/transformers.rs",
"package.json"
] | |
juspay/hyperswitch | juspay__hyperswitch-2349 | Bug: [FEATURE]: [Square] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index ff33914c4fd..01ed507bf34 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -327,6 +327,7 @@ pub struct SquarePaymentsResponseDetails {
status: SquarePaymentStatus,
id: String,
amount_money: SquarePaymentsAmountData,
+ reference_id: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct SquarePaymentsResponse {
@@ -355,7 +356,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item.response.payment.reference_id,
}),
amount_captured,
..item.data
| 2023-10-03T14:40:02Z |
## Description
Populated reference ID from the response
## Motivation and Context
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as payment_id, attempt_id, and connector_transaction_id for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
# | 0aa6b30d2c9056e9a21a88bdc064daa7e8659bd6 | [
"crates/router/src/connector/square/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2441 | Bug: [REFACTOR] add support for passing context generic to api calls
### Feature Description
Add support for including a new generic, context, which will be passed during api call (server_wrap) to call the related implementation depending on context
### Possible Implementation
To have multiple implementation to a particular object and calling the respective implementation during runtime depending on the context passed
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index e44ce0a1fd3..1076dfe410f 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -6,7 +6,7 @@ use router_env::{instrument, tracing, Flow};
use crate::{
compatibility::{stripe::errors, wrap},
- core::{api_locking::GetLockingInput, payments},
+ core::{api_locking::GetLockingInput, payment_methods::Oss, payments},
routes,
services::{api, authentication as auth},
types::api::{self as api_types},
@@ -50,7 +50,7 @@ pub async fn payment_intents_create(
&req,
create_payment_req,
|state, auth, req| {
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -109,7 +109,7 @@ pub async fn payment_intents_retrieve(
&req,
payload,
|state, auth, payload| {
- payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -172,7 +172,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -236,7 +236,7 @@ pub async fn payment_intents_update(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -302,7 +302,7 @@ pub async fn payment_intents_confirm(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -358,7 +358,7 @@ pub async fn payment_intents_capture(
&req,
payload,
|state, auth, payload| {
- payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -418,7 +418,7 @@ pub async fn payment_intents_cancel(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _, Oss>(
state,
auth.merchant_account,
auth.key_store,
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index b9da2f8e3ee..311498e1af5 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -9,7 +9,7 @@ use crate::{
stripe::{errors, payment_intents::types as stripe_payment_types},
wrap,
},
- core::{api_locking, payments},
+ core::{api_locking, payment_methods::Oss, payments},
routes,
services::{api, authentication as auth},
types::api as api_types,
@@ -54,7 +54,14 @@ pub async fn setup_intents_create(
&req,
create_payment_req,
|state, auth, req| {
- payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<
+ api_types::SetupMandate,
+ api_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state,
auth.merchant_account,
auth.key_store,
@@ -113,7 +120,7 @@ pub async fn setup_intents_retrieve(
&req,
payload,
|state, auth, payload| {
- payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -178,7 +185,14 @@ pub async fn setup_intents_update(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<
+ api_types::SetupMandate,
+ api_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state,
auth.merchant_account,
auth.key_store,
@@ -244,7 +258,14 @@ pub async fn setup_intents_confirm(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<
+ api_types::SetupMandate,
+ api_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state,
auth.merchant_account,
auth.key_store,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index f1d641adbe5..850daeba75f 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1,3 +1,99 @@
pub mod cards;
pub mod transformers;
pub mod vault;
+
+pub use api_models::{
+ enums::{Connector, PayoutConnectors},
+ payouts as payout_types,
+};
+pub use common_utils::request::RequestBody;
+use data_models::payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent};
+use diesel_models::enums;
+
+use crate::{
+ core::{errors::RouterResult, payments::helpers},
+ routes::AppState,
+ types::api::{self, payments},
+};
+
+pub struct Oss;
+
+#[async_trait::async_trait]
+pub trait PaymentMethodRetrieve {
+ async fn retrieve_payment_method(
+ pm_data: &Option<payments::PaymentMethodData>,
+ state: &AppState,
+ payment_intent: &PaymentIntent,
+ payment_attempt: &PaymentAttempt,
+ ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)>;
+}
+
+#[async_trait::async_trait]
+impl PaymentMethodRetrieve for Oss {
+ async fn retrieve_payment_method(
+ pm_data: &Option<payments::PaymentMethodData>,
+ state: &AppState,
+ payment_intent: &PaymentIntent,
+ payment_attempt: &PaymentAttempt,
+ ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)> {
+ match pm_data {
+ pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::Card,
+ pm,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ pm @ Some(api::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
+ pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
+ pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::BankTransfer,
+ pm,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::Wallet,
+ pm,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::BankRedirect,
+ pm,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
+ _ => Ok((None, None)),
+ }
+ }
+}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1b6d93596f1..cc84a13616d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -18,6 +18,8 @@ use futures::future::join_all;
use helpers::ApplePayData;
use masking::Secret;
use router_env::{instrument, tracing};
+#[cfg(feature = "olap")]
+use router_types::transformers::ForeignFrom;
use scheduler::{db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as pt_utils};
use time;
@@ -31,12 +33,11 @@ use self::{
operations::{payment_complete_authorize, BoxedOperation, Operation},
};
use super::errors::StorageErrorExt;
-#[cfg(feature = "olap")]
-use crate::types::transformers::ForeignFrom;
use crate::{
configs::settings::PaymentMethodTypeTokenFilter,
core::{
errors::{self, CustomResult, RouterResponse, RouterResult},
+ payment_methods::PaymentMethodRetrieve,
utils,
},
db::StorageInterface,
@@ -56,7 +57,7 @@ use crate::{
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
-pub async fn payments_operation_core<F, Req, Op, FData>(
+pub async fn payments_operation_core<F, Req, Op, FData, Ctx>(
state: &AppState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -69,7 +70,7 @@ pub async fn payments_operation_core<F, Req, Op, FData>(
where
F: Send + Clone + Sync,
Req: Authenticate,
- Op: Operation<F, Req> + Send + Sync,
+ Op: Operation<F, Req, Ctx> + Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
@@ -80,10 +81,11 @@ where
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, FData>,
+ PaymentResponse: Operation<F, FData, Ctx>,
FData: Send + Sync,
+ Ctx: PaymentMethodRetrieve,
{
- let operation: BoxedOperation<'_, F, Req> = Box::new(operation);
+ let operation: BoxedOperation<'_, F, Req, Ctx> = Box::new(operation);
tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str());
let (operation, validate_result) = operation
@@ -239,7 +241,7 @@ where
}
#[allow(clippy::too_many_arguments)]
-pub async fn payments_core<F, Res, Req, Op, FData>(
+pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
state: AppState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -252,31 +254,33 @@ pub async fn payments_core<F, Res, Req, Op, FData>(
where
F: Send + Clone + Sync,
FData: Send + Sync,
- Op: Operation<F, Req> + Send + Sync + Clone,
+ Op: Operation<F, Req, Ctx> + Send + Sync + Clone,
Req: Debug + Authenticate,
Res: transformers::ToResponse<Req, PaymentData<F>, Op>,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+ Ctx: PaymentMethodRetrieve,
// To construct connector flow specific api
dyn router_types::api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, FData>,
+ PaymentResponse: Operation<F, FData, Ctx>,
{
- let (payment_data, req, customer, connector_http_status_code) = payments_operation_core(
- &state,
- merchant_account,
- key_store,
- operation.clone(),
- req,
- call_connector_action,
- auth_flow,
- header_payload,
- )
- .await?;
+ let (payment_data, req, customer, connector_http_status_code) =
+ payments_operation_core::<_, _, _, _, Ctx>(
+ &state,
+ merchant_account,
+ key_store,
+ operation.clone(),
+ req,
+ call_connector_action,
+ auth_flow,
+ header_payload,
+ )
+ .await?;
Res::generate_response(
Some(req),
@@ -306,7 +310,7 @@ pub struct PaymentsRedirectResponseData {
}
#[async_trait::async_trait]
-pub trait PaymentRedirectFlow: Sync {
+pub trait PaymentRedirectFlow<Ctx: PaymentMethodRetrieve>: Sync {
async fn call_payment_flow(
&self,
state: &AppState,
@@ -402,7 +406,7 @@ pub trait PaymentRedirectFlow: Sync {
pub struct PaymentRedirectCompleteAuthorize;
#[async_trait::async_trait]
-impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
+impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCompleteAuthorize {
async fn call_payment_flow(
&self,
state: &AppState,
@@ -422,7 +426,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
}),
..Default::default()
};
- payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _>(
+ payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _, Ctx>(
state.clone(),
merchant_account,
merchant_key_store,
@@ -492,7 +496,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
pub struct PaymentRedirectSync;
#[async_trait::async_trait]
-impl PaymentRedirectFlow for PaymentRedirectSync {
+impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectSync {
async fn call_payment_flow(
&self,
state: &AppState,
@@ -517,7 +521,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync {
expand_attempts: None,
expand_captures: None,
};
- payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
+ payments_core::<api::PSync, api::PaymentsResponse, _, _, _, Ctx>(
state.clone(),
merchant_account,
merchant_key_store,
@@ -552,12 +556,12 @@ impl PaymentRedirectFlow for PaymentRedirectSync {
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
-pub async fn call_connector_service<F, RouterDReq, ApiRequest>(
+pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector: api::ConnectorData,
- operation: &BoxedOperation<'_, F, ApiRequest>,
+ operation: &BoxedOperation<'_, F, ApiRequest, Ctx>,
payment_data: &mut PaymentData<F>,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
@@ -573,6 +577,7 @@ where
PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>:
Feature<F, RouterDReq> + Send,
+ Ctx: PaymentMethodRetrieve,
// To construct connector flow specific api
dyn api::Connector:
@@ -767,7 +772,7 @@ where
router_data_res
}
-pub async fn call_multiple_connectors_service<F, Op, Req>(
+pub async fn call_multiple_connectors_service<F, Op, Req, Ctx>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
@@ -787,9 +792,10 @@ where
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
+ Ctx: PaymentMethodRetrieve,
// To perform router related operation for PaymentResponse
- PaymentResponse: Operation<F, Req>,
+ PaymentResponse: Operation<F, Req, Ctx>,
{
let call_connectors_start_time = Instant::now();
let mut join_handlers = Vec::with_capacity(connectors.len());
@@ -969,12 +975,12 @@ where
}
}
-async fn complete_preprocessing_steps_if_required<F, Req, Q>(
+async fn complete_preprocessing_steps_if_required<F, Req, Q, Ctx>(
state: &AppState,
connector: &api::ConnectorData,
payment_data: &PaymentData<F>,
mut router_data: router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
- operation: &BoxedOperation<'_, F, Q>,
+ operation: &BoxedOperation<'_, F, Q, Ctx>,
should_continue_payment: bool,
) -> RouterResult<(
router_types::RouterData<F, Req, router_types::PaymentsResponseData>,
@@ -1256,15 +1262,16 @@ pub enum TokenizationAction {
}
#[allow(clippy::too_many_arguments)]
-pub async fn get_connector_tokenization_action_when_confirm_true<F, Req>(
+pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, Ctx>(
state: &AppState,
- operation: &BoxedOperation<'_, F, Req>,
+ operation: &BoxedOperation<'_, F, Req, Ctx>,
payment_data: &mut PaymentData<F>,
validate_result: &operations::ValidateResult<'_>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<(PaymentData<F>, TokenizationAction)>
where
F: Send + Clone,
+ Ctx: PaymentMethodRetrieve,
{
let connector = payment_data.payment_attempt.connector.to_owned();
@@ -1364,14 +1371,15 @@ where
Ok(payment_data_and_tokenization_action)
}
-pub async fn tokenize_in_router_when_confirm_false<F, Req>(
+pub async fn tokenize_in_router_when_confirm_false<F, Req, Ctx>(
state: &AppState,
- operation: &BoxedOperation<'_, F, Req>,
+ operation: &BoxedOperation<'_, F, Req, Ctx>,
payment_data: &mut PaymentData<F>,
validate_result: &operations::ValidateResult<'_>,
) -> RouterResult<PaymentData<F>>
where
F: Send + Clone,
+ Ctx: PaymentMethodRetrieve,
{
// On confirm is false and only router related
let payment_data = if !is_operation_confirm(operation) {
@@ -1454,15 +1462,16 @@ pub struct CustomerDetails {
pub phone_country_code: Option<String>,
}
-pub fn if_not_create_change_operation<'a, Op, F>(
+pub fn if_not_create_change_operation<'a, Op, F, Ctx>(
status: storage_enums::IntentStatus,
confirm: Option<bool>,
current: &'a Op,
-) -> BoxedOperation<'_, F, api::PaymentsRequest>
+) -> BoxedOperation<'_, F, api::PaymentsRequest, Ctx>
where
F: Send + Clone,
- Op: Operation<F, api::PaymentsRequest> + Send + Sync,
- &'a Op: Operation<F, api::PaymentsRequest>,
+ Op: Operation<F, api::PaymentsRequest, Ctx> + Send + Sync,
+ &'a Op: Operation<F, api::PaymentsRequest, Ctx>,
+ Ctx: PaymentMethodRetrieve,
{
if confirm.unwrap_or(false) {
Box::new(PaymentConfirm)
@@ -1476,15 +1485,16 @@ where
}
}
-pub fn is_confirm<'a, F: Clone + Send, R, Op>(
+pub fn is_confirm<'a, F: Clone + Send, R, Op, Ctx>(
operation: &'a Op,
confirm: Option<bool>,
-) -> BoxedOperation<'_, F, R>
+) -> BoxedOperation<'_, F, R, Ctx>
where
- PaymentConfirm: Operation<F, R>,
- &'a PaymentConfirm: Operation<F, R>,
- Op: Operation<F, R> + Send + Sync,
- &'a Op: Operation<F, R>,
+ PaymentConfirm: Operation<F, R, Ctx>,
+ &'a PaymentConfirm: Operation<F, R, Ctx>,
+ Op: Operation<F, R, Ctx> + Send + Sync,
+ &'a Op: Operation<F, R, Ctx>,
+ Ctx: PaymentMethodRetrieve,
{
if confirm.unwrap_or(false) {
Box::new(&PaymentConfirm)
@@ -1777,8 +1787,8 @@ where
Ok(())
}
-pub async fn get_connector_choice<F, Req>(
- operation: &BoxedOperation<'_, F, Req>,
+pub async fn get_connector_choice<F, Req, Ctx>(
+ operation: &BoxedOperation<'_, F, Req, Ctx>,
state: &AppState,
req: &Req,
merchant_account: &domain::MerchantAccount,
@@ -1787,6 +1797,7 @@ pub async fn get_connector_choice<F, Req>(
) -> RouterResult<Option<api::ConnectorCallType>>
where
F: Send + Clone,
+ Ctx: PaymentMethodRetrieve,
{
let connector_choice = operation
.to_domain()?
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index d9c1d719c73..44c9b516dc5 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -36,7 +36,7 @@ use crate::{
consts::{self, BASE64_ENGINE},
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payment_methods::{cards, vault},
+ payment_methods::{cards, vault, PaymentMethodRetrieve},
payments,
},
db::StorageInterface,
@@ -936,10 +936,11 @@ where
}
}
-pub fn response_operation<'a, F, R>() -> BoxedOperation<'a, F, R>
+pub fn response_operation<'a, F, R, Ctx>() -> BoxedOperation<'a, F, R, Ctx>
where
F: Send + Clone,
- PaymentResponse: Operation<F, R>,
+ Ctx: PaymentMethodRetrieve,
+ PaymentResponse: Operation<F, R, Ctx>,
{
Box::new(PaymentResponse)
}
@@ -1149,14 +1150,14 @@ pub async fn get_connector_default(
}
#[instrument(skip_all)]
-pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
- operation: BoxedOperation<'a, F, R>,
+pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>(
+ operation: BoxedOperation<'a, F, R, Ctx>,
db: &dyn StorageInterface,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
-) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError> {
+) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
.change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?;
@@ -1302,12 +1303,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
))
}
-pub async fn make_pm_data<'a, F: Clone, R>(
- operation: BoxedOperation<'a, F, R>,
+pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
+ operation: BoxedOperation<'a, F, R, Ctx>,
state: &'a AppState,
payment_data: &mut PaymentData<F>,
-) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)> {
- let request = &payment_data.payment_method_data;
+) -> RouterResult<(
+ BoxedOperation<'a, F, R, Ctx>,
+ Option<api::PaymentMethodData>,
+)> {
+ let request = &payment_data.payment_method_data.clone();
let token = payment_data.token.clone();
let hyperswitch_token = match payment_data.mandate_id {
@@ -1418,89 +1422,19 @@ pub async fn make_pm_data<'a, F: Clone, R>(
None => None,
})
}
- (pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)), _) => {
- if should_store_payment_method_data_in_vault(
- &state.conf.temp_locker_disable_config,
- payment_data.payment_attempt.connector.clone(),
- enums::PaymentMethod::Card,
- ) {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
- enums::PaymentMethod::Card,
- )
- .await?;
- payment_data.token = Some(parent_payment_method_token);
- }
- Ok(pm_opt.to_owned())
- }
- (pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::Upi(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::Voucher(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::Reward), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::CardRedirect(_)), _) => Ok(pm.to_owned()),
- (pm @ Some(api::PaymentMethodData::GiftCard(_)), _) => Ok(pm.to_owned()),
- (pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)), _) => {
- if should_store_payment_method_data_in_vault(
- &state.conf.temp_locker_disable_config,
- payment_data.payment_attempt.connector.clone(),
- enums::PaymentMethod::BankTransfer,
- ) {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
- enums::PaymentMethod::BankTransfer,
- )
- .await?;
-
- payment_data.token = Some(parent_payment_method_token);
- }
+ (Some(_), _) => {
+ let payment_method_data = Ctx::retrieve_payment_method(
+ request,
+ state,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ )
+ .await?;
- Ok(pm_opt.to_owned())
- }
- (pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)), _) => {
- if should_store_payment_method_data_in_vault(
- &state.conf.temp_locker_disable_config,
- payment_data.payment_attempt.connector.clone(),
- enums::PaymentMethod::Wallet,
- ) {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
- enums::PaymentMethod::Wallet,
- )
- .await?;
+ payment_data.token = payment_method_data.1;
- payment_data.token = Some(parent_payment_method_token);
- }
- Ok(pm_opt.to_owned())
- }
- (pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)), _) => {
- if should_store_payment_method_data_in_vault(
- &state.conf.temp_locker_disable_config,
- payment_data.payment_attempt.connector.clone(),
- enums::PaymentMethod::BankRedirect,
- ) {
- let parent_payment_method_token = store_in_vault_and_generate_ppmt(
- state,
- pm,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
- enums::PaymentMethod::BankRedirect,
- )
- .await?;
- payment_data.token = Some(parent_payment_method_token);
- }
- Ok(pm_opt.to_owned())
+ Ok(payment_method_data.0)
}
_ => Ok(None),
}?;
@@ -1538,6 +1472,32 @@ pub async fn store_in_vault_and_generate_ppmt(
Ok(parent_payment_method_token)
}
+pub async fn store_payment_method_data_in_vault(
+ state: &AppState,
+ payment_attempt: &PaymentAttempt,
+ payment_intent: &PaymentIntent,
+ payment_method: enums::PaymentMethod,
+ payment_method_data: &api::PaymentMethodData,
+) -> RouterResult<Option<String>> {
+ if should_store_payment_method_data_in_vault(
+ &state.conf.temp_locker_disable_config,
+ payment_attempt.connector.clone(),
+ payment_method,
+ ) {
+ let parent_payment_method_token = store_in_vault_and_generate_ppmt(
+ state,
+ payment_method_data,
+ payment_intent,
+ payment_attempt,
+ payment_method,
+ )
+ .await?;
+
+ return Ok(Some(parent_payment_method_token));
+ }
+
+ Ok(None)
+}
pub fn should_store_payment_method_data_in_vault(
temp_locker_disable_config: &TempLockerDisableConfig,
option_connector: Option<String>,
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index b0c7a5ae126..d198cd562a7 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -27,7 +27,10 @@ pub use self::{
};
use super::{helpers, CustomerDetails, PaymentData};
use crate::{
- core::errors::{self, CustomResult, RouterResult},
+ core::{
+ errors::{self, CustomResult, RouterResult},
+ payment_methods::PaymentMethodRetrieve,
+ },
db::StorageInterface,
routes::AppState,
services,
@@ -38,26 +41,26 @@ use crate::{
},
};
-pub type BoxedOperation<'a, F, T> = Box<dyn Operation<F, T> + Send + Sync + 'a>;
+pub type BoxedOperation<'a, F, T, Ctx> = Box<dyn Operation<F, T, Ctx> + Send + Sync + 'a>;
-pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T> + Send + Sync)> {
+pub trait Operation<F: Clone, T, Ctx: PaymentMethodRetrieve>: Send + std::fmt::Debug {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T, Ctx> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("validate request interface not found for {self:?}"))
}
fn to_get_tracker(
&self,
- ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T> + Send + Sync)> {
+ ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, T>> {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Ctx>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(
&self,
- ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T> + Send + Sync)> {
+ ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("update tracker interface not found for {self:?}"))
}
@@ -80,16 +83,16 @@ pub struct ValidateResult<'a> {
}
#[allow(clippy::type_complexity)]
-pub trait ValidateRequest<F, R> {
+pub trait ValidateRequest<F, R, Ctx: PaymentMethodRetrieve> {
fn validate_request<'a, 'b>(
&'b self,
request: &R,
merchant_account: &'a domain::MerchantAccount,
- ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult<'a>)>;
+ ) -> RouterResult<(BoxedOperation<'b, F, R, Ctx>, ValidateResult<'a>)>;
}
#[async_trait]
-pub trait GetTracker<F, D, R>: Send {
+pub trait GetTracker<F, D, R, Ctx: PaymentMethodRetrieve>: Send {
#[allow(clippy::too_many_arguments)]
async fn get_trackers<'a>(
&'a self,
@@ -100,11 +103,11 @@ pub trait GetTracker<F, D, R>: Send {
merchant_account: &domain::MerchantAccount,
mechant_key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
- ) -> RouterResult<(BoxedOperation<'a, F, R>, D, Option<CustomerDetails>)>;
+ ) -> RouterResult<(BoxedOperation<'a, F, R, Ctx>, D, Option<CustomerDetails>)>;
}
#[async_trait]
-pub trait Domain<F: Clone, R>: Send + Sync {
+pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync {
/// This will fetch customer details, (this operation is flow specific)
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -112,7 +115,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError>;
+ ) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn make_pm_data<'a>(
@@ -120,7 +123,10 @@ pub trait Domain<F: Clone, R>: Send + Sync {
state: &'a AppState,
payment_data: &mut PaymentData<F>,
storage_scheme: enums::MerchantStorageScheme,
- ) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)>;
+ ) -> RouterResult<(
+ BoxedOperation<'a, F, R, Ctx>,
+ Option<api::PaymentMethodData>,
+ )>;
async fn add_task_to_process_tracker<'a>(
&'a self,
@@ -144,7 +150,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
#[async_trait]
#[allow(clippy::too_many_arguments)]
-pub trait UpdateTracker<F, D, Req>: Send {
+pub trait UpdateTracker<F, D, Req, Ctx: PaymentMethodRetrieve>: Send {
async fn update_trackers<'b>(
&'b self,
db: &dyn StorageInterface,
@@ -155,7 +161,7 @@ pub trait UpdateTracker<F, D, Req>: Send {
mechant_key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, Req>, D)>
+ ) -> RouterResult<(BoxedOperation<'b, F, Req, Ctx>, D)>
where
F: 'b + Send;
}
@@ -175,10 +181,13 @@ pub trait PostUpdateTracker<F, D, R>: Send {
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest>>
- Domain<F, api::PaymentsRetrieveRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Ctx>,
+ > Domain<F, api::PaymentsRetrieveRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -189,7 +198,7 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -225,7 +234,7 @@ where
payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
helpers::make_pm_data(Box::new(self), state, payment_data).await
@@ -233,10 +242,13 @@ where
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest>>
- Domain<F, api::PaymentsCaptureRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Ctx>,
+ > Domain<F, api::PaymentsCaptureRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -247,7 +259,7 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
+ BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -271,7 +283,7 @@ where
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
+ BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
Ok((Box::new(self), None))
@@ -290,10 +302,13 @@ where
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest>>
- Domain<F, api::PaymentsCancelRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Ctx>,
+ > Domain<F, api::PaymentsCancelRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -304,7 +319,7 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsCancelRequest>,
+ BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -329,7 +344,7 @@ where
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCancelRequest>,
+ BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
Ok((Box::new(self), None))
@@ -348,10 +363,13 @@ where
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest>>
- Domain<F, api::PaymentsRejectRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Ctx>,
+ > Domain<F, api::PaymentsRejectRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -362,7 +380,7 @@ where
_merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRejectRequest>,
+ BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -377,7 +395,7 @@ where
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRejectRequest>,
+ BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
Ok((Box::new(self), None))
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 871e906ee9d..d7b3d743b95 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -31,7 +32,9 @@ use crate::{
pub struct PaymentApprove;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentApprove {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -43,7 +46,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -262,7 +265,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for PaymentApprove
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -272,7 +277,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -295,7 +300,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove {
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
let (op, payment_method_data) =
@@ -334,7 +339,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentApprove {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -346,7 +353,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -366,14 +376,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentApprove {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
+ for PaymentApprove
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest>,
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
let given_payment_id = match &request.payment_id {
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index f2964a4e48c..72006946c20 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -29,7 +30,9 @@ use crate::{
pub struct PaymentCancel;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -41,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCancelRequest>,
+ BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -176,7 +179,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -189,7 +194,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCancelRequest>,
+ BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>,
PaymentData<F>,
)>
where
@@ -231,14 +236,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for PaymentCancel {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ ValidateRequest<F, api::PaymentsCancelRequest, Ctx> for PaymentCancel
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCancelRequest>,
+ BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index c3b915f9d34..bd64ebac632 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, types::MultipleCaptureData},
},
db::StorageInterface,
@@ -29,8 +30,8 @@ use crate::{
pub struct PaymentCapture;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
- for PaymentCapture
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentCapture
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -43,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
+ BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>,
payments::PaymentData<F>,
Option<payments::CustomerDetails>,
)> {
@@ -236,7 +237,8 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx>
for PaymentCapture
{
#[instrument(skip_all)]
@@ -251,7 +253,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
payments::PaymentData<F>,
)>
where
@@ -274,14 +276,16 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for PaymentCapture {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentCapture
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
+ BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 1ee7bec135f..db2c9e27c9b 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -30,7 +31,9 @@ use crate::{
pub struct CompleteAuthorize;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -257,7 +260,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for CompleteAuthorize
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -267,7 +272,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -290,7 +295,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
let (op, payment_method_data) =
@@ -329,7 +334,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -341,7 +348,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -349,14 +359,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAuthorize {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
+ for CompleteAuthorize
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest>,
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
let given_payment_id = match &request.payment_id {
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 2d35ef61ff6..761264e4798 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -12,6 +12,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -30,7 +31,9 @@ use crate::{
#[operation(ops = "all", flow = "authorize")]
pub struct PaymentConfirm;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -364,7 +367,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for PaymentConfirm
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -374,7 +379,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -397,7 +402,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
let (op, payment_method_data) =
@@ -436,7 +441,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -448,7 +455,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -597,14 +607,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfirm {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
+ for PaymentConfirm
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest>,
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 17d8d5f6c3d..479b0e2ccee 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -14,6 +14,7 @@ use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils::{self as core_utils},
},
@@ -39,7 +40,9 @@ pub struct PaymentCreate;
/// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments
/// This will create all the entities required for a new payment from the request
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -51,7 +54,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
merchant_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -231,7 +234,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.await
.transpose()?;
- let operation = payments::if_not_create_change_operation::<_, F>(
+ let operation = payments::if_not_create_change_operation::<_, F, Ctx>(
payment_intent.status,
request.confirm,
self,
@@ -299,7 +302,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for PaymentCreate
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -309,7 +314,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -332,7 +337,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
helpers::make_pm_data(Box::new(self), state, payment_data).await
@@ -362,7 +367,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -374,7 +381,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -444,14 +454,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
+ for PaymentCreate
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest>,
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs
index 2f260ee3e0a..0ff49279f3c 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -12,6 +12,7 @@ use crate::{
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, Operation, PaymentData},
utils as core_utils,
},
@@ -31,14 +32,16 @@ use crate::{
#[operation(ops = "all", flow = "verify")]
pub struct PaymentMethodValidate;
-impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodValidate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::VerifyRequest, Ctx>
+ for PaymentMethodValidate
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::VerifyRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::VerifyRequest>,
+ BoxedOperation<'b, F, api::VerifyRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
@@ -63,7 +66,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa
}
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentMethodValidate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::VerifyRequest, Ctx> for PaymentMethodValidate
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -75,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
_mechant_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::VerifyRequest>,
+ BoxedOperation<'a, F, api::VerifyRequest, Ctx>,
PaymentData<F>,
Option<payments::CustomerDetails>,
)> {
@@ -204,7 +209,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentMethodValidate {
+impl<F: Clone, Ctx: PaymentMethodRetrieve> UpdateTracker<F, PaymentData<F>, api::VerifyRequest, Ctx>
+ for PaymentMethodValidate
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -216,7 +223,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM
_mechant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::VerifyRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::VerifyRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -245,11 +255,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM
}
#[async_trait]
-impl<F, Op> Domain<F, api::VerifyRequest> for Op
+impl<F, Op, Ctx: PaymentMethodRetrieve> Domain<F, api::VerifyRequest, Ctx> for Op
where
F: Clone + Send,
- Op: Send + Sync + Operation<F, api::VerifyRequest>,
- for<'a> &'a Op: Operation<F, api::VerifyRequest>,
+ Op: Send + Sync + Operation<F, api::VerifyRequest, Ctx>,
+ for<'a> &'a Op: Operation<F, api::VerifyRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -260,7 +270,7 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::VerifyRequest>,
+ BoxedOperation<'a, F, api::VerifyRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -283,7 +293,7 @@ where
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::VerifyRequest>,
+ BoxedOperation<'a, F, api::VerifyRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
helpers::make_pm_data(Box::new(self), state, payment_data).await
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index fe52d1b89d5..c9a24b8fb84 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -28,7 +29,9 @@ use crate::{
pub struct PaymentReject;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for PaymentReject {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -40,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for P
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, PaymentsRejectRequest>,
+ BoxedOperation<'a, F, PaymentsRejectRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -162,7 +165,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for P
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for PaymentReject {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -174,7 +179,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for Payme
_mechant_key_store: &domain::MerchantKeyStore,
_should_decline_transaction: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, PaymentsRejectRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -220,14 +228,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for Payme
}
}
-impl<F: Send + Clone> ValidateRequest<F, PaymentsRejectRequest> for PaymentReject {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsRejectRequest, Ctx>
+ for PaymentReject
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsRejectRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, PaymentsRejectRequest>,
+ BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
Ok((
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index d3cb4f818f0..712515b2e87 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -11,6 +11,7 @@ use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
mandate,
+ payment_methods::PaymentMethodRetrieve,
payments::{types::MultipleCaptureData, PaymentData},
utils as core_utils,
},
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 938441962b2..261275296f1 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, PaymentData},
},
db::StorageInterface,
@@ -29,8 +30,8 @@ use crate::{
pub struct PaymentSession;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
- for PaymentSession
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -43,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsSessionRequest>,
+ BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>,
PaymentData<F>,
Option<payments::CustomerDetails>,
)> {
@@ -198,7 +199,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -211,7 +214,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
PaymentData<F>,
)>
where
@@ -234,14 +237,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for PaymentSession {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ ValidateRequest<F, api::PaymentsSessionRequest, Ctx> for PaymentSession
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsSessionRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
//paymentid is already generated and should be sent in the request
@@ -261,10 +266,13 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest>>
- Domain<F, api::PaymentsSessionRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Ctx>,
+ > Domain<F, api::PaymentsSessionRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -275,7 +283,7 @@ where
key_store: &domain::MerchantKeyStore,
) -> errors::CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsSessionRequest>,
+ BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -298,7 +306,7 @@ where
_payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsSessionRequest>,
+ BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
//No payment method data for this operation
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 2d34d409979..07015810039 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
@@ -28,7 +29,9 @@ use crate::{
pub struct PaymentStart;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -40,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
mechant_key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsStartRequest>,
+ BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -171,7 +174,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -184,7 +189,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsStartRequest>,
+ BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>,
PaymentData<F>,
)>
where
@@ -194,14 +199,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentStart {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsStartRequest, Ctx>
+ for PaymentStart
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsStartRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsStartRequest>,
+ BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = Some(&request.merchant_id[..]);
@@ -227,10 +234,13 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
}
#[async_trait]
-impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsStartRequest>>
- Domain<F, api::PaymentsStartRequest> for Op
+impl<
+ F: Clone + Send,
+ Ctx: PaymentMethodRetrieve,
+ Op: Send + Sync + Operation<F, api::PaymentsStartRequest, Ctx>,
+ > Domain<F, api::PaymentsStartRequest, Ctx> for Op
where
- for<'a> &'a Op: Operation<F, api::PaymentsStartRequest>,
+ for<'a> &'a Op: Operation<F, api::PaymentsStartRequest, Ctx>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
@@ -241,7 +251,7 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsStartRequest>,
+ BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -264,7 +274,7 @@ where
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsStartRequest>,
+ BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
if payment_data
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 80830efd13d..6e0ef2f4bac 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -11,7 +11,11 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payments::{helpers, operations, types, CustomerDetails, PaymentAddress, PaymentData},
+ payment_methods::PaymentMethodRetrieve,
+ payments::{
+ helpers, operations, types as payment_types, CustomerDetails, PaymentAddress,
+ PaymentData,
+ },
},
db::StorageInterface,
routes::AppState,
@@ -27,31 +31,39 @@ use crate::{
#[operation(ops = "all", flow = "sync")]
pub struct PaymentStatus;
-impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for PaymentStatus {
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx>
+ for PaymentStatus
+{
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> {
Ok(self)
}
fn to_update_tracker(
&self,
- ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
- {
+ ) -> RouterResult<
+ &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync),
+ > {
Ok(self)
}
}
-impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for &PaymentStatus {
- fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx>
+ for &PaymentStatus
+{
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> {
Ok(*self)
}
fn to_update_tracker(
&self,
- ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
- {
+ ) -> RouterResult<
+ &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync),
+ > {
Ok(*self)
}
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for PaymentStatus
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -61,7 +73,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -84,7 +96,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
helpers::make_pm_data(Box::new(self), state, payment_data).await
@@ -114,7 +126,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentStatus
+{
async fn update_trackers<'b>(
&'b self,
_db: &dyn StorageInterface,
@@ -125,7 +139,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -134,7 +151,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
+{
async fn update_trackers<'b>(
&'b self,
_db: &dyn StorageInterface,
@@ -146,7 +165,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>,
PaymentData<F>,
)>
where
@@ -157,8 +176,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo
}
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest>
- for PaymentStatus
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
@@ -171,7 +190,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -191,7 +210,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
- Op: Operation<F, api::PaymentsRetrieveRequest> + 'a + Send + Sync,
+ Ctx: PaymentMethodRetrieve,
+ Op: Operation<F, api::PaymentsRetrieveRequest, Ctx> + 'a + Send + Sync,
>(
payment_id: &api::PaymentIdType,
merchant_account: &domain::MerchantAccount,
@@ -201,7 +221,7 @@ async fn get_tracker_for_sync<
operation: Op,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -282,7 +302,7 @@ async fn get_tracker_for_sync<
.attach_printable_lazy(|| {
format!("Error while retrieving capture list for, merchant_id: {}, payment_id: {payment_id_str}", merchant_account.merchant_id)
})?;
- Some(types::MultipleCaptureData::new_for_sync(
+ Some(payment_types::MultipleCaptureData::new_for_sync(
captures,
request.expand_captures,
)?)
@@ -388,13 +408,15 @@ async fn get_tracker_for_sync<
))
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for PaymentStatus {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ ValidateRequest<F, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus
+{
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRetrieveRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
+ BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 04f36d51c2c..9e0ef76d3e7 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
@@ -30,7 +31,9 @@ use crate::{
pub struct PaymentUpdate;
#[async_trait]
-impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
+ GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate
+{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
@@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
@@ -268,7 +271,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
})
.await
.transpose()?;
- let next_operation: BoxedOperation<'a, F, api::PaymentsRequest> =
+ let next_operation: BoxedOperation<'a, F, api::PaymentsRequest, Ctx> =
if request.confirm.unwrap_or(false) {
Box::new(operations::PaymentConfirm)
} else {
@@ -350,7 +353,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
}
#[async_trait]
-impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
+impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx>
+ for PaymentUpdate
+{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
@@ -360,7 +365,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<
(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<domain::Customer>,
),
errors::StorageError,
@@ -383,7 +388,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<(
- BoxedOperation<'a, F, api::PaymentsRequest>,
+ BoxedOperation<'a, F, api::PaymentsRequest, Ctx>,
Option<api::PaymentMethodData>,
)> {
helpers::make_pm_data(Box::new(self), state, payment_data).await
@@ -413,7 +418,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate {
}
#[async_trait]
-impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
+impl<F: Clone, Ctx: PaymentMethodRetrieve>
+ UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate
+{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
@@ -425,7 +432,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: api::HeaderPayload,
- ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
+ ) -> RouterResult<(
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
+ PaymentData<F>,
+ )>
where
F: 'b + Send,
{
@@ -556,14 +566,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
}
-impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate {
+impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx>
+ for PaymentUpdate
+{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
- BoxedOperation<'b, F, api::PaymentsRequest>,
+ BoxedOperation<'b, F, api::PaymentsRequest, Ctx>,
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index b647c8a97d7..530d445b50d 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -20,6 +20,7 @@ use crate::{
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse},
+ payment_methods::PaymentMethodRetrieve,
payments, refunds,
},
db::StorageInterface,
@@ -39,7 +40,10 @@ use crate::{
const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5;
const MERCHANT_ID: &str = "merchant_id";
-pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>(
+pub async fn payments_incoming_webhook_flow<
+ W: types::OutgoingWebhookType,
+ Ctx: PaymentMethodRetrieve,
+>(
state: AppState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -74,27 +78,28 @@ pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>(
.perform_locking_action(&state, merchant_account.merchant_id.to_string())
.await?;
- let response = payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
- state.clone(),
- merchant_account.clone(),
- key_store,
- payments::operations::PaymentStatus,
- api::PaymentsRetrieveRequest {
- resource_id: id,
- merchant_id: Some(merchant_account.merchant_id.clone()),
- force_sync: true,
- connector: None,
- param: None,
- merchant_connector_details: None,
- client_secret: None,
- expand_attempts: None,
- expand_captures: None,
- },
- services::AuthFlow::Merchant,
- consume_or_trigger_flow,
- HeaderPayload::default(),
- )
- .await;
+ let response =
+ payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _, Ctx>(
+ state.clone(),
+ merchant_account.clone(),
+ key_store,
+ payments::operations::PaymentStatus,
+ api::PaymentsRetrieveRequest {
+ resource_id: id,
+ merchant_id: Some(merchant_account.merchant_id.clone()),
+ force_sync: true,
+ connector: None,
+ param: None,
+ merchant_connector_details: None,
+ client_secret: None,
+ expand_attempts: None,
+ expand_captures: None,
+ },
+ services::AuthFlow::Merchant,
+ consume_or_trigger_flow,
+ HeaderPayload::default(),
+ )
+ .await;
lock_action
.free_lock_action(&state, merchant_account.merchant_id.to_owned())
@@ -531,7 +536,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>(
}
}
-async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType>(
+async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>(
state: AppState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
@@ -553,7 +558,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType>(
payment_token: payment_attempt.payment_token,
..Default::default()
};
- payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Ctx>(
state.clone(),
merchant_account.to_owned(),
key_store,
@@ -824,7 +829,7 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>(
Ok(())
}
-pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>(
+pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>(
state: AppState,
req: &actix_web::HttpRequest,
merchant_account: domain::MerchantAccount,
@@ -832,7 +837,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>(
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
) -> RouterResponse<serde_json::Value> {
- let (application_response, _webhooks_response_tracker) = webhooks_core::<W>(
+ let (application_response, _webhooks_response_tracker) = webhooks_core::<W, Ctx>(
state,
req,
merchant_account,
@@ -846,7 +851,8 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>(
}
#[instrument(skip_all)]
-pub async fn webhooks_core<W: types::OutgoingWebhookType>(
+
+pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>(
state: AppState,
req: &actix_web::HttpRequest,
merchant_account: domain::MerchantAccount,
@@ -1044,7 +1050,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(
};
match flow_type {
- api::WebhookFlow::Payment => payments_incoming_webhook_flow::<W>(
+ api::WebhookFlow::Payment => payments_incoming_webhook_flow::<W, Ctx>(
state.clone(),
merchant_account,
key_store,
@@ -1078,7 +1084,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(
.await
.attach_printable("Incoming webhook flow for disputes failed")?,
- api::WebhookFlow::BankTransfer => bank_transfer_webhook_flow::<W>(
+ api::WebhookFlow::BankTransfer => bank_transfer_webhook_flow::<W, Ctx>(
state.clone(),
merchant_account,
key_store,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 9d7cf220a3a..b760aa83aaa 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -10,6 +10,7 @@ use crate::{
self as app,
core::{
errors::http_not_implemented,
+ payment_methods::{Oss, PaymentMethodRetrieve},
payments::{self, PaymentRedirectFlow},
},
openapi::examples::{
@@ -106,7 +107,7 @@ pub async fn payments_create(
&req,
payload,
|state, auth, req| {
- authorize_verify_select(
+ authorize_verify_select::<_, Oss>(
payments::PaymentCreate,
state,
auth.merchant_account,
@@ -160,8 +161,15 @@ pub async fn payments_start(
state,
&req,
payload,
- |state,auth, req| {
- payments::payments_core::<api_types::Authorize, payment_types::PaymentsResponse, _, _, _>(
+ |state, auth, req| {
+ payments::payments_core::<
+ api_types::Authorize,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state,
auth.merchant_account,
auth.key_store,
@@ -227,7 +235,7 @@ pub async fn payments_retrieve(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -288,7 +296,7 @@ pub async fn payments_retrieve_with_gateway_creds(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -354,7 +362,7 @@ pub async fn payments_update(
&req,
payload,
|state, auth, req| {
- authorize_verify_select(
+ authorize_verify_select::<_, Oss>(
payments::PaymentUpdate,
state,
auth.merchant_account,
@@ -430,7 +438,7 @@ pub async fn payments_confirm(
&req,
payload,
|state, auth, req| {
- authorize_verify_select(
+ authorize_verify_select::<_, Oss>(
payments::PaymentConfirm,
state,
auth.merchant_account,
@@ -485,7 +493,14 @@ pub async fn payments_capture(
&req,
payload,
|state, auth, payload| {
- payments::payments_core::<api_types::Capture, payment_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<
+ api_types::Capture,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
state,
auth.merchant_account,
auth.key_store,
@@ -539,6 +554,7 @@ pub async fn payments_connector_session(
_,
_,
_,
+ Oss,
>(
state,
auth.merchant_account,
@@ -600,7 +616,8 @@ pub async fn payments_redirect_response(
&req,
payload,
|state, auth, req| {
- payments::PaymentRedirectSync {}.handle_payments_redirect_response(
+ <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ &payments::PaymentRedirectSync {},
state,
auth.merchant_account,
auth.key_store,
@@ -657,7 +674,8 @@ pub async fn payments_redirect_response_with_creds_identifier(
&req,
payload,
|state, auth, req| {
- payments::PaymentRedirectSync {}.handle_payments_redirect_response(
+ <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ &payments::PaymentRedirectSync {},
state,
auth.merchant_account,
auth.key_store,
@@ -696,7 +714,9 @@ pub async fn payments_complete_authorize(
&req,
payload,
|state, auth, req| {
- payments::PaymentRedirectCompleteAuthorize {}.handle_payments_redirect_response(
+
+ <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response(
+ &payments::PaymentRedirectCompleteAuthorize {},
state,
auth.merchant_account,
auth.key_store,
@@ -745,7 +765,7 @@ pub async fn payments_cancel(
&req,
payload,
|state, auth, req| {
- payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _,Oss>(
state,
auth.merchant_account,
auth.key_store,
@@ -846,7 +866,7 @@ pub async fn get_filters_for_payments(
)
.await
}
-async fn authorize_verify_select<Op>(
+async fn authorize_verify_select<Op, Ctx>(
operation: Op,
state: app::AppState,
merchant_account: domain::MerchantAccount,
@@ -856,13 +876,18 @@ async fn authorize_verify_select<Op>(
auth_flow: api::AuthFlow,
) -> app::core::errors::RouterResponse<api_models::payments::PaymentsResponse>
where
+ Ctx: PaymentMethodRetrieve,
Op: Sync
+ Clone
+ std::fmt::Debug
- + payments::operations::Operation<api_types::Authorize, api_models::payments::PaymentsRequest>
+ payments::operations::Operation<
+ api_types::Authorize,
+ api_models::payments::PaymentsRequest,
+ Ctx,
+ > + payments::operations::Operation<
api_types::SetupMandate,
api_models::payments::PaymentsRequest,
+ Ctx,
>,
{
// TODO: Change for making it possible for the flow to be inferred internally or through validation layer
@@ -874,23 +899,26 @@ where
match req.payment_type.unwrap_or_default() {
api_models::enums::PaymentType::Normal
| api_models::enums::PaymentType::RecurringMandate
- | api_models::enums::PaymentType::NewMandate => payments::payments_core::<
- api_types::Authorize,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- >(
- state,
- merchant_account,
- key_store,
- operation,
- req,
- auth_flow,
- payments::CallConnectorAction::Trigger,
- header_payload,
- )
- .await,
+ | api_models::enums::PaymentType::NewMandate => {
+ payments::payments_core::<
+ api_types::Authorize,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ Ctx,
+ >(
+ state,
+ merchant_account,
+ key_store,
+ operation,
+ req,
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ header_payload,
+ )
+ .await
+ }
api_models::enums::PaymentType::SetupMandate => {
payments::payments_core::<
api_types::SetupMandate,
@@ -898,6 +926,7 @@ where
_,
_,
_,
+ Ctx,
>(
state,
merchant_account,
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index 0bbc6add436..f9fee54d16f 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -5,6 +5,7 @@ use super::app::AppState;
use crate::{
core::{
api_locking,
+ payment_methods::Oss,
webhooks::{self, types},
},
services::{api, authentication as auth},
@@ -26,7 +27,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
&req,
body,
|state, auth, body| {
- webhooks::webhooks_wrapper::<W>(
+ webhooks::webhooks_wrapper::<W, Oss>(
state.to_owned(),
&req,
auth.merchant_account,
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 744cce31327..4dbf97081a6 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -8,7 +8,10 @@ use scheduler::{
};
use crate::{
- core::payments::{self as payment_flows, operations},
+ core::{
+ payment_methods::Oss,
+ payments::{self as payment_flows, operations},
+ },
db::StorageInterface,
errors,
routes::AppState,
@@ -55,7 +58,7 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow {
.await?;
let (payment_data, _, _, _) =
- payment_flows::payments_operation_core::<api::PSync, _, _, _>(
+ payment_flows::payments_operation_core::<api::PSync, _, _, _, Oss>(
state,
merchant_account.clone(),
key_store,
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 1bff639d346..551960ac138 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -4,7 +4,7 @@ mod utils;
use router::{
configs,
- core::payments,
+ core::{payment_methods::Oss, payments},
db::StorageImpl,
routes, services,
types::{
@@ -361,7 +361,7 @@ async fn payments_create_core() {
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response =
- payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Oss>(
state,
merchant_account,
key_store,
@@ -531,7 +531,7 @@ async fn payments_create_core_adyen_no_redirect() {
vec![],
));
let actual_response =
- payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>(
+ payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Oss>(
state,
merchant_account,
key_store,
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 91b2a454eea..96ed131dc6f 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -3,7 +3,7 @@
mod utils;
use router::{
- core::payments,
+ core::{payment_methods::Oss, payments},
db::StorageImpl,
types::api::{self, enums as api_enums},
*,
@@ -120,19 +120,25 @@ async fn payments_create_core() {
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
- let actual_response =
- router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>(
- state,
- merchant_account,
- key_store,
- payments::PaymentCreate,
- req,
- services::AuthFlow::Merchant,
- payments::CallConnectorAction::Trigger,
- api::HeaderPayload::default(),
- )
- .await
- .unwrap();
+ let actual_response = router::core::payments::payments_core::<
+ api::Authorize,
+ api::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
+ state,
+ merchant_account,
+ key_store,
+ payments::PaymentCreate,
+ req,
+ services::AuthFlow::Merchant,
+ payments::CallConnectorAction::Trigger,
+ api::HeaderPayload::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(expected_response, actual_response);
}
@@ -292,18 +298,24 @@ async fn payments_create_core_adyen_no_redirect() {
},
vec![],
));
- let actual_response =
- router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>(
- state,
- merchant_account,
- key_store,
- payments::PaymentCreate,
- req,
- services::AuthFlow::Merchant,
- payments::CallConnectorAction::Trigger,
- api::HeaderPayload::default(),
- )
- .await
- .unwrap();
+ let actual_response = router::core::payments::payments_core::<
+ api::Authorize,
+ api::PaymentsResponse,
+ _,
+ _,
+ _,
+ Oss,
+ >(
+ state,
+ merchant_account,
+ key_store,
+ payments::PaymentCreate,
+ req,
+ services::AuthFlow::Merchant,
+ payments::CallConnectorAction::Trigger,
+ api::HeaderPayload::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(expected_response, actual_response);
}
diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs
index cf71370a293..fb0ef35ef58 100644
--- a/crates/router_derive/src/macros/operation.rs
+++ b/crates/router_derive/src/macros/operation.rs
@@ -61,7 +61,7 @@ impl Derives {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
- impl<F:Send+Clone> Operation<F,#req_type> for #struct_name {
+ impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for #struct_name {
#(#fns)*
}
}
@@ -75,7 +75,7 @@ impl Derives {
let req_type = Conversion::get_req_type(self);
quote! {
#[automatically_derived]
- impl<F:Send+Clone> Operation<F,#req_type> for &#struct_name {
+ impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for &#struct_name {
#(#ref_fns)*
}
}
@@ -138,22 +138,22 @@ impl Conversion {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> {
Ok(self)
}
},
Self::GetTracker => quote! {
- fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
+ fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
Ok(self)
}
},
Self::Domain => quote! {
- fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type>> {
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type,Ctx>> {
Ok(self)
}
},
Self::UpdateTracker => quote! {
- fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
+ fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
Ok(self)
}
},
@@ -186,22 +186,22 @@ impl Conversion {
let req_type = Self::get_req_type(ident);
match self {
Self::ValidateRequest => quote! {
- fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> {
+ fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> {
Ok(*self)
}
},
Self::GetTracker => quote! {
- fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
+ fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
Ok(*self)
}
},
Self::Domain => quote! {
- fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type>)> {
+ fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type,Ctx>)> {
Ok(*self)
}
},
Self::UpdateTracker => quote! {
- fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> {
+ fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> {
Ok(*self)
}
},
| 2023-10-03T13:46:00Z |
## Description
<!-- Describe your changes in detail -->
This PR includes changes for adding a new generic, context, which will be passed during api call (server_wrap) to call the related implementation depending on context
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | f364a069b90dd63a28cf25457b2cd4fda0829a8b | [
"crates/router/src/compatibility/stripe/payment_intents.rs",
"crates/router/src/compatibility/stripe/setup_intents.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payments.rs",
"crates/router/src/core/payments/helpers.rs",
"crates/router/src/core/payments/operations.rs",
"crate... | ||
juspay/hyperswitch | juspay__hyperswitch-2432 | Bug: [REFACTOR] add `requires_cvv` config while creating merchant account
### Feature Description
Insert requires_cvv config during merchant account creation itself. while getting that config during list_customer_payment_method, if not found in db, we insert it into db.
### Possible Implementation
in order to reduce db call in during listing payment methods, we insert config for requires_cvv during merchant creation itself
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index dabe22da626..c7009bf4cc9 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -219,6 +219,17 @@ pub async fn create_merchant_account(
.insert_merchant(merchant_account, &key_store)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
+
+ db.insert_config(diesel_models::configs::ConfigNew {
+ key: format!("{}_requires_cvv", merchant_account.merchant_id),
+ config: "true".to_string(),
+ })
+ .await
+ .map_err(|err| {
+ crate::logger::error!("Error while setting requires_cvv config: {err:?}");
+ })
+ .ok();
+
Ok(service_api::ApplicationResponse::Json(
merchant_account
.try_into()
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c22b7323095..20a3e130eb2 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1831,7 +1831,7 @@ pub async fn list_customer_payment_method(
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch merchant_id config for requires_cvv")?;
+ .attach_printable("Failed to fetch requires_cvv config")?;
let requires_cvv = is_requires_cvv.config != "false";
| 2023-10-03T13:39:33Z |
## Description
<!-- Describe your changes in detail -->
This PR includes changes for inserting requires_cvv config during merchant account creation itself. while getting that config during `list_customer_payment_method`, if not found in db, we insert it into db.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | d177b4d94f08fb8ef44b5c07ec1bdc771baa016d |

| [
"crates/router/src/core/admin.rs",
"crates/router/src/core/payment_methods/cards.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2341 | Bug: [FEATURE]: [Opayo] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index e6c3d90fa4f..d828232dbc1 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -86,6 +86,7 @@ impl From<OpayoPaymentStatus> for enums::AttemptStatus {
pub struct OpayoPaymentsResponse {
status: OpayoPaymentStatus,
id: String,
+ transaction_id: String,
}
impl<F, T>
@@ -99,12 +100,14 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.transaction_id),
}),
..item.data
})
| 2023-10-02T18:54:39Z |
## Description
<!-- Describe your changes in detail -->
opayo uses [transaction_Id ](https://developer-eu.elavon.com/docs/opayo/spec/api-reference#operation/createTransaction)
filled the connector_response_reference_id
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Fixes #2341
# | 688557ef95826622fe87a4de1dfbc09446496686 | [
"crates/router/src/connector/opayo/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2342 | Bug: [FEATURE]: [OpenNode] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index 70a50e1b922..aa3fae3a516 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -78,6 +78,7 @@ pub struct OpennodePaymentsResponseData {
id: String,
hosted_checkout_url: String,
status: OpennodePaymentStatus,
+ order_id: Option<String>,
}
//TODO: Fill the struct with respective fields
@@ -114,7 +115,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item.response.data.order_id,
})
} else {
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse {
@@ -125,7 +126,7 @@ impl<F, T>
"Please check the transaction in opennode dashboard and resolve manually"
.to_string(),
}),
- connector_response_reference_id: None,
+ connector_response_reference_id: item.response.data.order_id,
})
};
Ok(Self {
| 2023-10-02T13:56:34Z |
## 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).
-->
Closes #2342.
# | f720aecf1fb676cec71e636b877a46f9791d713a | [
"crates/router/src/connector/opennode/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2348 | Bug: [FEATURE]: [Stax] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 42c7c02a363..4ee28be1937 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -23,6 +23,7 @@ pub struct StaxPaymentsRequest {
is_refundable: bool,
pre_auth: bool,
meta: StaxPaymentsRequestMetaData,
+ idempotency_id: Option<String>,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
@@ -51,6 +52,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
+ idempotency_id: Some(item.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(
@@ -69,6 +71,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
+ idempotency_id: Some(item.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(_)
@@ -282,6 +285,7 @@ pub struct StaxPaymentsResponse {
child_captures: Vec<StaxChildCapture>,
#[serde(rename = "type")]
payment_response_type: StaxPaymentResponseTypes,
+ idempotency_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
@@ -323,12 +327,14 @@ impl<F, T>
Ok(Self {
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ item.response.idempotency_id.unwrap_or(item.response.id),
+ ),
}),
..item.data
})
| 2023-10-02T10:52:24Z |
## Description
<!-- Describe your changes in detail -->
This pull request fixes #2348 issue in STAX and uses connector_response_reference_id as reference to 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).
-->
Fixes #2348 and fixes #2317.
# | 36805411772da00719a716d05c650f10ca990d49 | [
"crates/router/src/connector/stax/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2317 | Bug: [FEATURE]: [Stax] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 42c7c02a363..4ee28be1937 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -23,6 +23,7 @@ pub struct StaxPaymentsRequest {
is_refundable: bool,
pre_auth: bool,
meta: StaxPaymentsRequestMetaData,
+ idempotency_id: Option<String>,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
@@ -51,6 +52,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
+ idempotency_id: Some(item.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(
@@ -69,6 +71,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest {
Err(errors::ConnectorError::InvalidWalletToken)?
}
}),
+ idempotency_id: Some(item.connector_request_reference_id.clone()),
})
}
api::PaymentMethodData::BankDebit(_)
@@ -282,6 +285,7 @@ pub struct StaxPaymentsResponse {
child_captures: Vec<StaxChildCapture>,
#[serde(rename = "type")]
payment_response_type: StaxPaymentResponseTypes,
+ idempotency_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
@@ -323,12 +327,14 @@ impl<F, T>
Ok(Self {
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ item.response.idempotency_id.unwrap_or(item.response.id),
+ ),
}),
..item.data
})
| 2023-10-02T10:52:24Z |
## Description
<!-- Describe your changes in detail -->
This pull request fixes #2348 issue in STAX and uses connector_response_reference_id as reference to 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).
-->
Fixes #2348 and fixes #2317.
# | 36805411772da00719a716d05c650f10ca990d49 | [
"crates/router/src/connector/stax/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2230 | Bug: [FEATURE]: [Klarna] Currency Unit Conversion
### :memo: Feature Description
- Each currency can be described in terms of base or minor units.
- For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit.
- In Hyperswitch, the amount value is expected to be always provided in minor units.
- For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent)
- Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them.
- We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector.
### :hammer: Possible Implementation
- ConnectorCommon trait have been implemented for the connector.
- This trait contains `get_currency_unit` method. This method needs to be implemented.
- It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 1814f9de809..2611c062ebe 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -32,6 +32,10 @@ impl ConnectorCommon for Klarna {
"klarna"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -406,7 +410,13 @@ impl
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let connector_req = klarna::KlarnaPaymentsRequest::try_from(req)?;
+ let connector_router_data = klarna::KlarnaRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = klarna::KlarnaPaymentsRequest::try_from(&connector_router_data)?;
let klarna_req = types::RequestBody::log_and_get_request_body(
&connector_req,
utils::Encode::<klarna::KlarnaPaymentsRequest>::encode_to_string_of_json,
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 3607818353a..b31d56d51b9 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -8,6 +8,37 @@ use crate::{
types::{self, storage::enums},
};
+#[derive(Debug, Serialize)]
+pub struct KlarnaRouterData<T> {
+ amount: i64,
+ router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for KlarnaRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize)]
pub struct KlarnaPaymentsRequest {
order_lines: Vec<OrderLines>,
@@ -88,10 +119,13 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>>
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for KlarnaPaymentsRequest {
+impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let request = &item.request;
+
+ fn try_from(
+ item: &KlarnaRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let request = &item.router_data.request;
match request.order_details.clone() {
Some(order_details) => Ok(Self {
purchase_country: "US".to_string(),
| 2023-10-02T10:10:41Z |
## Description
This pull request implements the `get_currency_unit` from the `ConnectorCommon` trait for the Klarna connector. This function allows connectors to declare their accepted currency unit as either `Base` or `Minor`. For Klarna it accepts currency as `Minor` units.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Fixes #2230
# | 89cb63be3328010d26b5f6322449fc50e80593e4 | `cargo check`, `cargo clippy`, and `cargo test` all pass without any new errors.
| [
"crates/router/src/connector/klarna.rs",
"crates/router/src/connector/klarna/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-2345 | Bug: [FEATURE]: [PowerTranz] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 4703a81f30f..4032f8019b0 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -123,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
.to_string(),
three_d_secure,
source,
- order_identifier: item.payment_id.clone(),
+ order_identifier: item.connector_request_reference_id.clone(),
// billing_address,
// shipping_address,
extended_data,
@@ -239,6 +239,7 @@ pub struct PowertranzBaseResponse {
iso_response_code: String,
redirect_data: Option<String>,
response_message: String,
+ order_identifier: String,
}
impl ForeignFrom<(u8, bool, bool)> for enums::AttemptStatus {
@@ -297,7 +298,7 @@ impl<F, T>
let connector_transaction_id = item
.response
.original_trxn_identifier
- .unwrap_or(item.response.transaction_identifier);
+ .unwrap_or(item.response.transaction_identifier.clone());
let redirection_data =
item.response
.redirect_data
@@ -311,7 +312,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_identifier),
}),
Err,
);
| 2023-10-02T08:23:45Z |
## 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).
-->
Fixes #2345
# | 89cb63be3328010d26b5f6322449fc50e80593e4 | [
"crates/router/src/connector/powertranz/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2314 | Bug: [FEATURE]: [PowerTranz] Use `connector_request_reference_id` as reference to the connector
### :memo: Feature Description
- We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard.
- Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`.
- This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system.
### :hammer: Possible Implementation
- To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData.
- This id should replace them as a reference id to the connector for payment request.
- One might need to have exposure to api docs of the connector for which it is being implemented.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052
:bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 4703a81f30f..4032f8019b0 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -123,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
.to_string(),
three_d_secure,
source,
- order_identifier: item.payment_id.clone(),
+ order_identifier: item.connector_request_reference_id.clone(),
// billing_address,
// shipping_address,
extended_data,
@@ -239,6 +239,7 @@ pub struct PowertranzBaseResponse {
iso_response_code: String,
redirect_data: Option<String>,
response_message: String,
+ order_identifier: String,
}
impl ForeignFrom<(u8, bool, bool)> for enums::AttemptStatus {
@@ -297,7 +298,7 @@ impl<F, T>
let connector_transaction_id = item
.response
.original_trxn_identifier
- .unwrap_or(item.response.transaction_identifier);
+ .unwrap_or(item.response.transaction_identifier.clone());
let redirection_data =
item.response
.redirect_data
@@ -311,7 +312,7 @@ impl<F, T>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_identifier),
}),
Err,
);
| 2023-10-02T08:23:45Z |
## 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).
-->
Fixes #2345
# | 89cb63be3328010d26b5f6322449fc50e80593e4 | [
"crates/router/src/connector/powertranz/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-2343 | Bug: [FEATURE]: [Payeezy] Use `connector_response_reference_id` as reference to merchant
### :memo: Feature Description
- Reference id are used to map transactions in the connector’s dashboard.
- Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction.
- However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment.
### :hammer: Possible Implementation
- When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData.
- For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction.
- One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id.
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index d6c22ba67c3..98e8ea12c00 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -67,6 +67,7 @@ pub struct PayeezyPaymentsRequest {
pub currency_code: String,
pub credit_card: PayeezyPaymentMethod,
pub stored_credentials: Option<StoredCredentials>,
+ pub reference: String,
}
#[derive(Serialize, Debug)]
@@ -118,6 +119,7 @@ fn get_card_specific_payment_data(
currency_code,
credit_card,
stored_credentials,
+ reference: item.connector_request_reference_id.clone(),
})
}
fn get_transaction_type_and_stored_creds(
@@ -252,6 +254,7 @@ pub struct PayeezyPaymentsResponse {
pub gateway_resp_code: String,
pub gateway_message: String,
pub stored_credentials: Option<PaymentsStoredCredentials>,
+ pub reference: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -354,13 +357,17 @@ impl<F, T>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.transaction_id,
+ item.response.transaction_id.clone(),
),
redirection_data: None,
mandate_reference,
connector_metadata: metadata,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(
+ item.response
+ .reference
+ .unwrap_or(item.response.transaction_id),
+ ),
}),
..item.data
})
| 2023-10-01T19:11:46Z |
## Description
<!-- Describe your changes in detail -->
Add `connector_response_reference_id` support for Payeezy
- Used `transaction_id` as the reference id, while implementing this!
Resolves #2343 and resolves #2312.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
# | 89cb63be3328010d26b5f6322449fc50e80593e4 | Need help testing!
| [
"crates/router/src/connector/payeezy/transformers.rs"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.