Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(core): Add record attempt operation for revenue recovery webhooks (#7236)

chikke srujan24aa00341f90
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 76d71e8308..f9540fd08f 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -707,7 +707,7 @@ pub struct PaymentAmountDetailsResponse {
}
#[cfg(feature = "v2")]
-#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentAttemptAmountDetails {
/// The total amount of the order including tax, surcharge and shipping cost
@@ -5416,7 +5416,7 @@ pub struct PaymentsRetrieveRequest {
/// Error details for the payment
#[cfg(feature = "v2")]
-#[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema)]
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)]
pub struct ErrorDetails {
/// The error code
pub code: String,
@@ -8387,3 +8387,84 @@ pub struct BillingConnectorPaymentDetails {
/// Billing Connector's Customer Id
pub connector_customer_id: String,
}
+
+// Serialize is required because the api event requires Serialize to be implemented
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[cfg(feature = "v2")]
+pub struct PaymentsAttemptRecordRequest {
+ /// The amount details for the payment attempt.
+ pub amount_details: PaymentAttemptAmountDetails,
+
+ #[schema(value_type = AttemptStatus, example = "charged")]
+ pub status: enums::AttemptStatus,
+
+ /// The billing details of the payment attempt. This address will be used for invoicing.
+ pub billing: Option<Address>,
+
+ /// The shipping address for the payment attempt.
+ pub shipping: Option<Address>,
+
+ /// Error details provided by the billing processor.
+ pub error: Option<RecordAttemptErrorDetails>,
+
+ /// A description for the payment attempt.
+ #[schema(example = "It's my first payment request", value_type = Option<String>)]
+ pub description: Option<common_utils::types::Description>,
+
+ /// A unique identifier for a payment provided by the connector.
+ pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
+
+ /// The payment method type used for payment attempt.
+ #[schema(value_type = PaymentMethod, example = "bank_transfer")]
+ pub payment_method_type: api_enums::PaymentMethod,
+
+ /// The name of the payment connector through which the payment attempt was made.
+ #[schema(value_type = Option<Connector>, example = "stripe")]
+ pub connector: Option<common_enums::connector_enums::Connector>,
+
+ /// Billing connector id to update the invoices.
+ #[schema(value_type = String, example = "mca_1234567890")]
+ pub billing_connector_id: id_type::MerchantConnectorAccountId,
+
+ /// Billing connector id to update the invoices.
+ #[schema(value_type = String, example = "mca_1234567890")]
+ pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
+
+ /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided
+ #[schema(value_type = PaymentMethodType, example = "apple_pay")]
+ pub payment_method_subtype: api_enums::PaymentMethodType,
+
+ /// The payment instrument data to be used for the payment attempt.
+ pub payment_method_data: Option<PaymentMethodDataRequest>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
+ #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// Additional data that might be required by hyperswitch based on the requested features by the merchants.
+ pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
+
+ /// The time at which payment attempt was created.
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub transaction_created_at: Option<PrimitiveDateTime>,
+
+ /// payment method token at payment processor end.
+ #[schema(value_type = String, example = "1234567890")]
+ pub processor_payment_method_token: String,
+
+ /// customer id at payment connector for which mandate is attached.
+ #[schema(value_type = String, example = "cust_12345")]
+ pub connector_customer_id: String,
+}
+
+/// Error details for the payment
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+pub struct RecordAttemptErrorDetails {
+ /// error code sent by billing connector.
+ pub code: String,
+ /// error message sent by billing connector.
+ pub message: String,
+}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 09121f7f00..7409b72265 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -311,6 +311,7 @@ pub struct PaymentAttemptNew {
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
+ pub connector_payment_id: Option<ConnectorTransactionId>,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub id: id_type::GlobalAttemptId,
pub connector_token_details: Option<ConnectorTokenDetails>,
diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
index 80b9b8cc20..f5b16695c1 100644
--- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
@@ -285,7 +285,7 @@ pub struct ChargebeeTransactionData {
status: ChargebeeTranasactionStatus,
error_code: Option<String>,
error_text: Option<String>,
- gateway_account_id: Option<String>,
+ gateway_account_id: String,
currency_code: enums::Currency,
amount: MinorUnit,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
@@ -373,9 +373,14 @@ impl ChargebeeInvoiceBody {
}
}
+pub struct ChargebeeMandateDetails {
+ pub customer_id: String,
+ pub mandate_id: String,
+}
+
impl ChargebeeCustomer {
// the logic to find connector customer id & mandate id is different for different gateways, reference : https://apidocs.chargebee.com/docs/api/customers?prod_cat_ver=2#customer_payment_method_reference_id .
- pub fn find_connector_ids(&self) -> Result<(String, String), errors::ConnectorError> {
+ pub fn find_connector_ids(&self) -> Result<ChargebeeMandateDetails, errors::ConnectorError> {
match self.payment_method.gateway {
ChargebeeGateway::Stripe | ChargebeeGateway::Braintree => {
let mut parts = self.payment_method.reference_id.split('/');
@@ -387,7 +392,10 @@ impl ChargebeeCustomer {
.last()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
- Ok((customer_id, mandate_id))
+ Ok(ChargebeeMandateDetails {
+ customer_id,
+ mandate_id,
+ })
}
}
}
@@ -409,13 +417,15 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD
.map(common_utils::types::ConnectorTransactionId::TxnId);
let error_code = item.content.transaction.error_code.clone();
let error_message = item.content.transaction.error_text.clone();
- let (connector_customer_id, processor_payment_method_token) = match &item.content.customer {
- Some(customer) => {
- let (customer_id, mandate_id) = customer.find_connector_ids()?;
- (Some(customer_id), Some(mandate_id))
- }
- None => (None, None),
- };
+ let connector_mandate_details = item
+ .content
+ .customer
+ .as_ref()
+ .map(|customer| customer.find_connector_ids())
+ .transpose()?
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_mandate_details",
+ })?;
let connector_account_reference_id = item.content.transaction.gateway_account_id.clone();
let transaction_created_at = item.content.transaction.date;
let status = enums::AttemptStatus::from(item.content.transaction.status);
@@ -433,8 +443,8 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD
connector_transaction_id,
error_code,
error_message,
- processor_payment_method_token,
- connector_customer_id,
+ processor_payment_method_token: connector_mandate_details.mandate_id,
+ connector_customer_id: connector_mandate_details.customer_id,
connector_account_reference_id,
transaction_created_at,
status,
@@ -452,7 +462,7 @@ impl From<ChargebeeTranasactionStatus> for enums::AttemptStatus {
ChargebeeTranasactionStatus::Success => Self::Charged,
ChargebeeTranasactionStatus::Failure
| ChargebeeTranasactionStatus::Timeout
- | ChargebeeTranasactionStatus::LateFailure => Self::Pending,
+ | ChargebeeTranasactionStatus::LateFailure => Self::Failure,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index e7a7b8feea..f2dddf39b0 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -569,3 +569,33 @@ impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
}
}
}
+#[cfg(feature = "v2")]
+impl From<&api_models::payments::PaymentAttemptAmountDetails>
+ for payments::payment_attempt::AttemptAmountDetailsSetter
+{
+ fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self {
+ Self {
+ net_amount: amount.net_amount,
+ amount_to_capture: amount.amount_to_capture,
+ surcharge_amount: amount.surcharge_amount,
+ tax_on_surcharge: amount.tax_on_surcharge,
+ amount_capturable: amount.amount_capturable,
+ shipping_cost: amount.shipping_cost,
+ order_tax_amount: amount.order_tax_amount,
+ }
+ }
+}
+#[cfg(feature = "v2")]
+impl From<&api_models::payments::RecordAttemptErrorDetails>
+ for payments::payment_attempt::ErrorDetails
+{
+ fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self {
+ Self {
+ code: error.code.clone(),
+ message: error.message.clone(),
+ reason: Some(error.message.clone()),
+ unified_code: None,
+ unified_message: None,
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 1e602c0282..464009a84a 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -159,6 +159,21 @@ impl MerchantConnectorAccount {
pub fn get_connector_name_as_string(&self) -> String {
self.connector_name.clone().to_string()
}
+
+ pub fn get_payment_merchant_connector_account_id_using_account_reference_id(
+ &self,
+ account_reference_id: String,
+ ) -> Option<id_type::MerchantConnectorAccountId> {
+ self.feature_metadata.as_ref().and_then(|metadata| {
+ metadata.revenue_recovery.as_ref().and_then(|recovery| {
+ recovery
+ .mca_reference
+ .billing_to_recovery
+ .get(&account_reference_id)
+ .cloned()
+ })
+ })
+ }
}
#[cfg(feature = "v2")]
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index d0a4551d01..36cc1c5f80 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -4,7 +4,7 @@ use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::payments::SessionToken;
#[cfg(feature = "v2")]
-use common_utils::ext_traits::ValueExt;
+use common_utils::ext_traits::{OptionExt, ValueExt};
use common_utils::{
self,
crypto::Encryptable,
@@ -594,6 +594,18 @@ impl PaymentIntent {
split_payments: None,
})
}
+
+ pub fn get_revenue_recovery_metadata(
+ &self,
+ ) -> Option<diesel_models::types::PaymentRevenueRecoveryMetadata> {
+ self.feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
+ }
+
+ pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> {
+ self.feature_metadata.clone()
+ }
}
#[cfg(feature = "v1")]
@@ -731,6 +743,78 @@ where
}
}
+#[cfg(feature = "v2")]
+#[derive(Clone)]
+pub struct PaymentAttemptRecordData<F>
+where
+ F: Clone,
+{
+ pub flow: PhantomData<F>,
+ pub payment_intent: PaymentIntent,
+ pub payment_attempt: PaymentAttempt,
+ pub revenue_recovery_data: RevenueRecoveryData,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Clone)]
+pub struct RevenueRecoveryData {
+ pub billing_connector_id: id_type::MerchantConnectorAccountId,
+ pub processor_payment_method_token: String,
+ pub connector_customer_id: String,
+}
+
+#[cfg(feature = "v2")]
+impl<F> PaymentAttemptRecordData<F>
+where
+ F: Clone,
+{
+ pub fn get_updated_feature_metadata(
+ &self,
+ ) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> {
+ let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata();
+
+ let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata();
+
+ let payment_revenue_recovery_metadata =
+ Some(diesel_models::types::PaymentRevenueRecoveryMetadata {
+ // Update retry count by one.
+ total_retry_count: revenue_recovery.map_or(1, |data| (data.total_retry_count + 1)),
+ // Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.
+ payment_connector_transmission:
+ common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
+ billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(),
+ active_attempt_payment_connector_id: self
+ .payment_attempt
+ .get_attempt_merchant_connector_account_id()?,
+ billing_connector_payment_details:
+ diesel_models::types::BillingConnectorPaymentDetails {
+ payment_processor_token: self
+ .revenue_recovery_data
+ .processor_payment_method_token
+ .clone(),
+ connector_customer_id: self
+ .revenue_recovery_data
+ .connector_customer_id
+ .clone(),
+ },
+ payment_method_type: self.payment_attempt.payment_method_type,
+ payment_method_subtype: self.payment_attempt.payment_method_subtype,
+ });
+ Ok(Some(FeatureMetadata {
+ redirect_response: payment_intent_feature_metadata
+ .as_ref()
+ .and_then(|data| data.redirect_response.clone()),
+ search_tags: payment_intent_feature_metadata
+ .as_ref()
+ .and_then(|data| data.search_tags.clone()),
+ apple_pay_recurring_details: payment_intent_feature_metadata
+ .as_ref()
+ .and_then(|data| data.apple_pay_recurring_details.clone()),
+ payment_revenue_recovery_metadata,
+ }))
+ }
+}
+
#[derive(Clone, serde::Serialize, Debug)]
pub enum VaultOperation {
ExistingVaultData(VaultData),
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 765798229a..7092605695 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -8,6 +8,7 @@ use common_utils::{
};
use common_utils::{
errors::{CustomResult, ValidationError},
+ ext_traits::OptionExt,
id_type, pii,
types::{
keymanager::{self, KeyManagerState},
@@ -660,6 +661,118 @@ impl PaymentAttempt {
card_discovery: None,
})
}
+
+ /// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
+ #[cfg(feature = "v2")]
+ pub async fn create_domain_model_using_record_request(
+ payment_intent: &super::PaymentIntent,
+ cell_id: id_type::CellId,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ request: &api_models::payments::PaymentsAttemptRecordRequest,
+ encrypted_data: DecryptedPaymentAttempt,
+ ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
+ let id = id_type::GlobalAttemptId::generate(&cell_id);
+
+ let amount_details = AttemptAmountDetailsSetter::from(&request.amount_details);
+
+ let now = common_utils::date_time::now();
+ // we consume transaction_created_at from webhook request, if it is not present we take store current time as transaction_created_at.
+ let transaction_created_at = request
+ .transaction_created_at
+ .unwrap_or(common_utils::date_time::now());
+
+ // This function is called in the record attempt flow, which tells us that this is a payment attempt created by an external system.
+ let feature_metadata = PaymentAttemptFeatureMetadata {
+ revenue_recovery: Some({
+ PaymentAttemptRevenueRecoveryData {
+ attempt_triggered_by: common_enums::TriggeredBy::External,
+ }
+ }),
+ };
+
+ let payment_method_billing_address = encrypted_data
+ .payment_method_billing_address
+ .as_ref()
+ .map(|data| {
+ data.clone()
+ .deserialize_inner_value(|value| value.parse_value("Address"))
+ })
+ .transpose()
+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to decode billing address")?;
+ let error = request.error.as_ref().map(ErrorDetails::from);
+ let connector_payment_id = request
+ .connector_transaction_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_id().clone());
+ let connector = request.connector.map(|connector| connector.to_string());
+
+ Ok(Self {
+ payment_id: payment_intent.id.clone(),
+ merchant_id: payment_intent.merchant_id.clone(),
+ amount_details: AttemptAmountDetails::from(amount_details),
+ status: request.status,
+ connector,
+ authentication_type: storage_enums::AuthenticationType::NoThreeDs,
+ created_at: transaction_created_at,
+ modified_at: now,
+ last_synced: None,
+ cancellation_reason: None,
+ browser_info: None,
+ payment_token: None,
+ connector_metadata: None,
+ payment_experience: None,
+ payment_method_data: None,
+ routing_result: None,
+ preprocessing_step_id: None,
+ multiple_capture_count: None,
+ connector_response_reference_id: None,
+ updated_by: storage_scheme.to_string(),
+ redirection_data: None,
+ encoded_data: None,
+ merchant_connector_id: request.payment_merchant_connector_id.clone(),
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ profile_id: payment_intent.profile_id.clone(),
+ organization_id: payment_intent.organization_id.clone(),
+ payment_method_type: request.payment_method_type,
+ payment_method_id: None,
+ connector_payment_id,
+ payment_method_subtype: request.payment_method_subtype,
+ authentication_applied: None,
+ external_reference_id: None,
+ payment_method_billing_address,
+ error,
+ feature_metadata: Some(feature_metadata),
+ id,
+ connector_token_details: Some(diesel_models::ConnectorTokenDetails {
+ connector_mandate_id: Some(request.processor_payment_method_token.clone()),
+ connector_token_request_reference_id: None,
+ }),
+ card_discovery: None,
+ charges: None,
+ })
+ }
+
+ pub fn get_attempt_merchant_connector_account_id(
+ &self,
+ ) -> CustomResult<
+ id_type::MerchantConnectorAccountId,
+ errors::api_error_response::ApiErrorResponse,
+ > {
+ let merchant_connector_id = self
+ .merchant_connector_id
+ .clone()
+ .get_required_value("merchant_connector_id")
+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Merchant connector id is None")?;
+ Ok(merchant_connector_id)
+ }
}
#[cfg(feature = "v1")]
@@ -2272,6 +2385,9 @@ impl behaviour::Conversion for PaymentAttempt {
amount_to_capture: amount_details.amount_to_capture,
payment_method_billing_address: payment_method_billing_address.map(Encryption::from),
payment_method_subtype,
+ connector_payment_id: connector_payment_id
+ .as_ref()
+ .map(|txn_id| ConnectorTransactionId::TxnId(txn_id.clone())),
payment_method_type_v2: payment_method_type,
id,
charges,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 628be8c1d8..380523bbeb 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -339,6 +339,12 @@ pub enum PaymentIntentUpdate {
amount_captured: Option<MinorUnit>,
updated_by: String,
},
+ RecordUpdate {
+ status: common_enums::IntentStatus,
+ feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>,
+ active_attempt_id: id_type::GlobalAttemptId,
+ updated_by: String,
+ },
/// UpdateIntent
UpdateIntent(Box<PaymentIntentUpdateFields>),
}
@@ -632,6 +638,47 @@ impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal {
updated_by,
}
}
+ PaymentIntentUpdate::RecordUpdate {
+ status,
+ feature_metadata,
+ active_attempt_id,
+ updated_by,
+ } => Self {
+ status: Some(status),
+ amount_captured: None,
+ active_attempt_id: Some(Some(active_attempt_id)),
+ modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: *feature_metadata,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
+ updated_by,
+ },
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
index 8467189d27..8adf5676f9 100644
--- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs
+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
@@ -1,46 +1,48 @@
-use api_models::webhooks;
+use api_models::{payments as api_payments, webhooks};
+use common_enums::enums as common_enums;
+use common_utils::{id_type, types as util_types};
use time::PrimitiveDateTime;
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
/// transaction amount against invoice, accepted in minor unit.
- pub amount: common_utils::types::MinorUnit,
+ pub amount: util_types::MinorUnit,
/// currency of the transaction
- pub currency: common_enums::enums::Currency,
+ pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
- pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
+ pub merchant_reference_id: id_type::PaymentReferenceId,
/// transaction id reference at payment connector
- pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
+ pub connector_transaction_id: Option<util_types::ConnectorTransactionId>,
/// error code sent by billing connector.
pub error_code: Option<String>,
/// error message sent by billing connector.
pub error_message: Option<String>,
/// mandate token at payment processor end.
- pub processor_payment_method_token: Option<String>,
+ pub processor_payment_method_token: String,
/// customer id at payment connector for which mandate is attached.
- pub connector_customer_id: Option<String>,
+ pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
- pub connector_account_reference_id: Option<String>,
+ pub connector_account_reference_id: String,
/// timestamp at which transaction has been created at billing connector
pub transaction_created_at: Option<PrimitiveDateTime>,
/// transaction status at billing connector equivalent to payment attempt status.
- pub status: common_enums::enums::AttemptStatus,
+ pub status: common_enums::AttemptStatus,
/// payment method of payment attempt.
- pub payment_method_type: common_enums::enums::PaymentMethod,
+ pub payment_method_type: common_enums::PaymentMethod,
/// payment method sub type of the payment attempt.
- pub payment_method_sub_type: common_enums::enums::PaymentMethodType,
+ pub payment_method_sub_type: common_enums::PaymentMethodType,
}
/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryInvoiceData {
/// invoice amount at billing connector
- pub amount: common_utils::types::MinorUnit,
+ pub amount: util_types::MinorUnit,
/// currency of the amount.
- pub currency: common_enums::enums::Currency,
+ pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
- pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
+ pub merchant_reference_id: id_type::PaymentReferenceId,
}
/// type of action that needs to taken after consuming recovery payload
@@ -61,15 +63,15 @@ pub enum RecoveryAction {
}
pub struct RecoveryPaymentIntent {
- pub payment_id: common_utils::id_type::GlobalPaymentId,
- pub status: common_enums::enums::IntentStatus,
- pub feature_metadata: Option<api_models::payments::FeatureMetadata>,
+ pub payment_id: id_type::GlobalPaymentId,
+ pub status: common_enums::IntentStatus,
+ pub feature_metadata: Option<api_payments::FeatureMetadata>,
}
pub struct RecoveryPaymentAttempt {
- pub attempt_id: common_utils::id_type::GlobalAttemptId,
+ pub attempt_id: id_type::GlobalAttemptId,
pub attempt_status: common_enums::AttemptStatus,
- pub feature_metadata: Option<api_models::payments::PaymentAttemptFeatureMetadata>,
+ pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>,
}
impl RecoveryPaymentAttempt {
@@ -138,9 +140,9 @@ impl RecoveryAction {
}
}
-impl From<&RevenueRecoveryInvoiceData> for api_models::payments::AmountDetails {
+impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
- let amount = api_models::payments::AmountDetailsSetter {
+ let amount = api_payments::AmountDetailsSetter {
order_amount: data.amount.into(),
currency: data.currency,
shipping_cost: None,
@@ -154,9 +156,9 @@ impl From<&RevenueRecoveryInvoiceData> for api_models::payments::AmountDetails {
}
}
-impl From<&RevenueRecoveryInvoiceData> for api_models::payments::PaymentsCreateIntentRequest {
+impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
- let amount_details = api_models::payments::AmountDetails::from(data);
+ let amount_details = api_payments::AmountDetails::from(data);
Self {
amount_details,
merchant_reference_id: Some(data.merchant_reference_id.clone()),
@@ -188,3 +190,29 @@ impl From<&RevenueRecoveryInvoiceData> for api_models::payments::PaymentsCreateI
}
}
}
+
+impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails {
+ fn from(data: &RevenueRecoveryAttemptData) -> Self {
+ Self {
+ net_amount: data.amount,
+ amount_to_capture: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ amount_capturable: data.amount,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
+}
+
+impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> {
+ fn from(data: &RevenueRecoveryAttemptData) -> Self {
+ data.error_code
+ .as_ref()
+ .zip(data.error_message.clone())
+ .map(|(code, message)| api_payments::RecordAttemptErrorDetails {
+ code: code.to_string(),
+ message: message.to_string(),
+ })
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
index bbe1a65de8..fbc797269d 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
@@ -67,3 +67,6 @@ pub struct PaymentUpdateIntent;
#[derive(Debug, Clone)]
pub struct PostSessionTokens;
+
+#[derive(Debug, Clone)]
+pub struct RecordAttempt;
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index f56fef1af5..b32fe76f5e 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -483,4 +483,6 @@ pub enum RevenueRecoveryError {
PaymentIntentCreateFailed,
#[error("Source verification failed for billing connector")]
WebhookAuthenticationFailed,
+ #[error("Payment merchant connector account not found using acccount reference id")]
+ PaymentMerchantConnectorAccountNotFound,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 03126ea771..d92d9b1fa0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1725,6 +1725,76 @@ where
)
}
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+pub async fn record_attempt_core(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_account: domain::MerchantAccount,
+ profile: domain::Profile,
+ key_store: domain::MerchantKeyStore,
+ req: api_models::payments::PaymentsAttemptRecordRequest,
+ payment_id: id_type::GlobalPaymentId,
+ header_payload: HeaderPayload,
+ platform_merchant_account: Option<domain::MerchantAccount>,
+) -> RouterResponse<api_models::payments::PaymentAttemptResponse> {
+ tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
+
+ let operation: &operations::payment_attempt_record::PaymentAttemptRecord =
+ &operations::payment_attempt_record::PaymentAttemptRecord;
+ let boxed_operation: BoxedOperation<
+ '_,
+ api::RecordAttempt,
+ api_models::payments::PaymentsAttemptRecordRequest,
+ domain_payments::PaymentAttemptRecordData<api::RecordAttempt>,
+ > = Box::new(operation);
+
+ let _validate_result = boxed_operation
+ .to_validate_request()?
+ .validate_request(&req, &merchant_account)?;
+
+ tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
+
+ let operations::GetTrackerResponse { payment_data } = boxed_operation
+ .to_get_tracker()?
+ .get_trackers(
+ &state,
+ &payment_id,
+ &req,
+ &merchant_account,
+ &profile,
+ &key_store,
+ &header_payload,
+ platform_merchant_account.as_ref(),
+ )
+ .await?;
+
+ let (_operation, payment_data) = boxed_operation
+ .to_update_tracker()?
+ .update_trackers(
+ &state,
+ req_state,
+ payment_data,
+ None,
+ merchant_account.storage_scheme,
+ None,
+ &key_store,
+ None,
+ header_payload.clone(),
+ )
+ .await?;
+
+ transformers::GenerateResponse::generate_response(
+ payment_data,
+ &state,
+ None,
+ None,
+ header_payload.x_hs_latency,
+ &merchant_account,
+ &profile,
+ )
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_intent_core<F, Res, Req, Op, D>(
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 47b020554c..294ec92e30 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -30,6 +30,8 @@ pub mod payments_incremental_authorization;
#[cfg(feature = "v1")]
pub mod tax_calculation;
+#[cfg(feature = "v2")]
+pub mod payment_attempt_record;
#[cfg(feature = "v2")]
pub mod payment_confirm_intent;
#[cfg(feature = "v2")]
diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rs
new file mode 100644
index 0000000000..8b81822a59
--- /dev/null
+++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs
@@ -0,0 +1,323 @@
+use std::marker::PhantomData;
+
+use api_models::{enums::FrmSuggestion, payments::PaymentsAttemptRecordRequest};
+use async_trait::async_trait;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::{AsyncExt, Encode, ValueExt},
+ types::keymanager::ToEncryptable,
+};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::payments::PaymentAttemptRecordData;
+use masking::PeekInterface;
+use router_env::{instrument, tracing};
+
+use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
+use crate::{
+ core::{
+ errors::{self, StorageErrorExt},
+ payments::{
+ self,
+ cards::create_encrypted_data,
+ helpers,
+ operations::{self, ValidateStatusForOperation},
+ },
+ },
+ db::{domain::types, errors::RouterResult},
+ routes::{app::ReqState, SessionState},
+ services,
+ types::{
+ api,
+ domain::{self, types as domain_types},
+ storage::{self, enums},
+ },
+ utils::{self, OptionExt},
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct PaymentAttemptRecord;
+
+type PaymentsAttemptRecordOperation<'b, F> =
+ BoxedOperation<'b, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>;
+
+impl<F: Send + Clone + Sync> Operation<F, PaymentsAttemptRecordRequest> for &PaymentAttemptRecord {
+ type Data = PaymentAttemptRecordData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<
+ &(dyn ValidateRequest<F, PaymentsAttemptRecordRequest, Self::Data> + Send + Sync),
+ > {
+ Ok(*self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+ fn to_domain(
+ &self,
+ ) -> RouterResult<&(dyn Domain<F, PaymentsAttemptRecordRequest, Self::Data>)> {
+ Ok(*self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+}
+
+impl ValidateStatusForOperation for PaymentAttemptRecord {
+ fn validate_status_for_operation(
+ &self,
+ intent_status: common_enums::IntentStatus,
+ ) -> Result<(), errors::ApiErrorResponse> {
+ // need to verify this?
+ match intent_status {
+ // Payment attempt can be recorded for failed payment as well in revenue recovery flow.
+ common_enums::IntentStatus::RequiresPaymentMethod
+ | common_enums::IntentStatus::Failed => Ok(()),
+ common_enums::IntentStatus::Succeeded
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::Processing
+ | common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::RequiresConfirmation
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable => {
+ Err(errors::ApiErrorResponse::PaymentUnexpectedState {
+ current_flow: format!("{self:?}"),
+ field_name: "status".to_string(),
+ current_value: intent_status.to_string(),
+ states: [
+ common_enums::IntentStatus::RequiresPaymentMethod,
+ common_enums::IntentStatus::Failed,
+ ]
+ .map(|enum_value| enum_value.to_string())
+ .join(", "),
+ })
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl<F: Send + Clone + Sync>
+ GetTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest>
+ for PaymentAttemptRecord
+{
+ #[instrument(skip_all)]
+ async fn get_trackers<'a>(
+ &'a self,
+ state: &'a SessionState,
+ payment_id: &common_utils::id_type::GlobalPaymentId,
+ request: &PaymentsAttemptRecordRequest,
+ merchant_account: &domain::MerchantAccount,
+ _profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ _platform_merchant_account: Option<&domain::MerchantAccount>,
+ ) -> RouterResult<operations::GetTrackerResponse<PaymentAttemptRecordData<F>>> {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let storage_scheme = merchant_account.storage_scheme;
+
+ let payment_intent = db
+ .find_payment_intent_by_id(key_manager_state, payment_id, key_store, storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ self.validate_status_for_operation(payment_intent.status)?;
+ let payment_method_billing_address = request
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| {
+ data.billing
+ .as_ref()
+ .map(|address| address.clone().encode_to_value())
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode payment_method_billing address")?
+ .map(masking::Secret::new);
+
+ let batch_encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
+ domain_types::CryptoOperation::BatchEncrypt(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
+ payment_method_billing_address,
+ },
+ ),
+ ),
+ common_utils::types::keymanager::Identifier::Merchant(merchant_account.get_id().to_owned()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details".to_string())?;
+
+ let encrypted_data =
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details")?;
+ let cell_id = state.conf.cell_information.id.clone();
+
+ let payment_attempt_domain_model =
+ hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::create_domain_model_using_record_request(
+ &payment_intent,
+ cell_id,
+ storage_scheme,
+ request,
+ encrypted_data,
+ )
+ .await?;
+
+ let payment_attempt = db
+ .insert_payment_attempt(
+ key_manager_state,
+ key_store,
+ payment_attempt_domain_model,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not insert payment attempt")?;
+ let revenue_recovery_data = hyperswitch_domain_models::payments::RevenueRecoveryData {
+ billing_connector_id: request.billing_connector_id.clone(),
+ processor_payment_method_token: request.processor_payment_method_token.clone(),
+ connector_customer_id: request.connector_customer_id.clone(),
+ };
+
+ let payment_data = PaymentAttemptRecordData {
+ flow: PhantomData,
+ payment_intent,
+ payment_attempt,
+ revenue_recovery_data,
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse { payment_data };
+
+ Ok(get_trackers_response)
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Sync> UpdateTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest>
+ for PaymentAttemptRecord
+{
+ #[instrument(skip_all)]
+ async fn update_trackers<'b>(
+ &'b self,
+ state: &'b SessionState,
+ _req_state: ReqState,
+ mut payment_data: PaymentAttemptRecordData<F>,
+ _customer: Option<domain::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
+ _updated_customer: Option<storage::CustomerUpdate>,
+ key_store: &domain::MerchantKeyStore,
+ _frm_suggestion: Option<FrmSuggestion>,
+ _header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<(
+ PaymentsAttemptRecordOperation<'b, F>,
+ PaymentAttemptRecordData<F>,
+ )>
+ where
+ F: 'b + Send,
+ {
+ let feature_metadata = payment_data.get_updated_feature_metadata()?;
+ let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::RecordUpdate
+ {
+ status: common_enums::IntentStatus::from(payment_data.payment_attempt.status),
+ feature_metadata: Box::new(feature_metadata),
+ active_attempt_id: payment_data.payment_attempt.id.clone(),
+ updated_by: storage_scheme.to_string(),
+ };
+ payment_data.payment_intent = state
+ .store
+ .update_payment_intent(
+ &state.into(),
+ payment_data.payment_intent,
+ payment_intent_update,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ Ok((Box::new(self), payment_data))
+ }
+}
+
+impl<F: Send + Clone> ValidateRequest<F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>
+ for PaymentAttemptRecord
+{
+ #[instrument(skip_all)]
+ fn validate_request<'a, 'b>(
+ &'b self,
+ _request: &PaymentsAttemptRecordRequest,
+ merchant_account: &'a domain::MerchantAccount,
+ ) -> RouterResult<operations::ValidateResult> {
+ Ok(operations::ValidateResult {
+ merchant_id: merchant_account.get_id().to_owned(),
+ storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
+ })
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Send + Sync> Domain<F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>
+ for PaymentAttemptRecord
+{
+ #[instrument(skip_all)]
+ async fn get_customer_details<'a>(
+ &'a self,
+ _state: &SessionState,
+ _payment_data: &mut PaymentAttemptRecordData<F>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<
+ (
+ BoxedOperation<'a, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>,
+ Option<domain::Customer>,
+ ),
+ errors::StorageError,
+ > {
+ Ok((Box::new(self), None))
+ }
+
+ #[instrument(skip_all)]
+ async fn make_pm_data<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_data: &mut PaymentAttemptRecordData<F>,
+ _storage_scheme: enums::MerchantStorageScheme,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _customer: &Option<domain::Customer>,
+ _business_profile: &domain::Profile,
+ _should_retry_with_pan: bool,
+ ) -> RouterResult<(
+ PaymentsAttemptRecordOperation<'a, F>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+ )> {
+ Ok((Box::new(self), None, None))
+ }
+
+ #[instrument(skip_all)]
+ async fn perform_routing<'a>(
+ &'a self,
+ _merchant_account: &domain::MerchantAccount,
+ _business_profile: &domain::Profile,
+ _state: &SessionState,
+ _payment_data: &mut PaymentAttemptRecordData<F>,
+ _mechant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
+ Ok(api::ConnectorCallType::Skip)
+ }
+}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 69a0ef35e7..9647a277b0 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1796,6 +1796,30 @@ where
}
}
+#[cfg(feature = "v2")]
+impl<F> GenerateResponse<api_models::payments::PaymentAttemptResponse>
+ for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F>
+where
+ F: Clone,
+{
+ fn generate_response(
+ self,
+ _state: &SessionState,
+ _connector_http_status_code: Option<u16>,
+ _external_latency: Option<u128>,
+ _is_latency_header_enabled: Option<bool>,
+ _merchant_account: &domain::MerchantAccount,
+ _profile: &domain::Profile,
+ ) -> RouterResponse<api_models::payments::PaymentAttemptResponse> {
+ let payment_attempt = self.payment_attempt;
+ let response = api_models::payments::PaymentAttemptResponse::foreign_from(&payment_attempt);
+ Ok(services::ApplicationResponse::JsonWithHeaders((
+ response,
+ vec![],
+ )))
+ }
+}
+
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse
where
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index f67eb5c15c..b187343ab7 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -364,6 +364,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
&request_details,
event_type,
req_state,
+ merchant_connector_account,
))
.await
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index b87311c0be..f27ee47d6a 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -1,4 +1,4 @@
-use api_models::webhooks;
+use api_models::{payments as api_payments, webhooks};
use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::revenue_recovery;
@@ -29,6 +29,7 @@ pub async fn recovery_incoming_webhook_flow(
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
+ billing_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
@@ -79,17 +80,43 @@ pub async fn recovery_incoming_webhook_flow(
)
.change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)?,
);
-
- invoice_transaction_details
- .get_payment_attempt(
+ // Find the payment merchant connector ID at the top level to avoid multiple DB calls.
+ let payment_merchant_connector_account = invoice_transaction_details
+ .find_payment_merchant_connector_account(
&state,
- &req_state,
- &merchant_account,
- &business_profile,
&key_store,
- payment_intent.payment_id.clone(),
+ &billing_connector_account,
)
- .await?
+ .await?;
+
+ Some(
+ invoice_transaction_details
+ .get_payment_attempt(
+ &state,
+ &req_state,
+ &merchant_account,
+ &business_profile,
+ &key_store,
+ payment_intent.payment_id.clone(),
+ )
+ .await
+ .transpose()
+ .async_unwrap_or_else(|| async {
+ invoice_transaction_details
+ .record_payment_attempt(
+ &state,
+ &req_state,
+ &merchant_account,
+ &business_profile,
+ &key_store,
+ payment_intent.payment_id.clone(),
+ &billing_connector_account.id,
+ payment_merchant_connector_account,
+ )
+ .await
+ })
+ .await?,
+ )
}
false => None,
};
@@ -189,13 +216,13 @@ impl RevenueRecoveryInvoice {
profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
- let payload = api_models::payments::PaymentsCreateIntentRequest::from(&self.0);
+ let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0);
let global_payment_id =
common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
let create_intent_response = Box::pin(payments::payments_intent_core::<
hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent,
- api_models::payments::PaymentsIntentResponse,
+ api_payments::PaymentsIntentResponse,
_,
_,
hyperswitch_domain_models::payments::PaymentIntentData<
@@ -242,7 +269,7 @@ impl RevenueRecoveryAttempt {
{
let attempt_response = Box::pin(payments::payments_core::<
hyperswitch_domain_models::router_flow_types::payments::PSync,
- api_models::payments::PaymentsResponse,
+ api_payments::PaymentsResponse,
_,
_,
_,
@@ -256,7 +283,7 @@ impl RevenueRecoveryAttempt {
profile.clone(),
key_store.clone(),
payments::operations::PaymentGet,
- api_models::payments::PaymentsRetrieveRequest {
+ api_payments::PaymentsRetrieveRequest {
force_sync: false,
expand_attempts: true,
param: None,
@@ -286,25 +313,122 @@ impl RevenueRecoveryAttempt {
});
Ok(payment_attempt)
}
- Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
router_env::logger::error!(?error);
- Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
- .attach_printable("failed to fetch payment intent recovery webhook flow")
+ Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
+ .attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
}?;
Ok(response)
}
+
+ #[allow(clippy::too_many_arguments)]
async fn record_payment_attempt(
&self,
- _state: &SessionState,
- _req_state: &ReqState,
- _merchant_account: &domain::MerchantAccount,
- _profile: &domain::Profile,
- _key_store: &domain::MerchantKeyStore,
- _payment_id: common_utils::id_type::GlobalPaymentId,
+ state: &SessionState,
+ req_state: &ReqState,
+ merchant_account: &domain::MerchantAccount,
+ profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ payment_id: common_utils::id_type::GlobalPaymentId,
+ billing_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId,
+ payment_connector_account: Option<domain::MerchantConnectorAccount>,
) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> {
- todo!()
+ let request_payload = self
+ .create_payment_record_request(billing_connector_account_id, payment_connector_account);
+ let attempt_response = Box::pin(payments::record_attempt_core(
+ state.clone(),
+ req_state.clone(),
+ merchant_account.clone(),
+ profile.clone(),
+ key_store.clone(),
+ request_payload,
+ payment_id.clone(),
+ hyperswitch_domain_models::payments::HeaderPayload::default(),
+ None,
+ ))
+ .await;
+
+ let response = match attempt_response {
+ Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
+ Ok(revenue_recovery::RecoveryPaymentAttempt {
+ attempt_id: attempt_response.id,
+ attempt_status: attempt_response.status,
+ feature_metadata: attempt_response.feature_metadata,
+ })
+ }
+ Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
+ .attach_printable("Unexpected response from record attempt core"),
+ error @ Err(_) => {
+ router_env::logger::error!(?error);
+ Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
+ .attach_printable("failed to record attempt in recovery webhook flow")
+ }
+ }?;
+ Ok(response)
+ }
+
+ pub fn create_payment_record_request(
+ &self,
+ billing_merchant_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId,
+ payment_merchant_connector_account: Option<domain::MerchantConnectorAccount>,
+ ) -> api_payments::PaymentsAttemptRecordRequest {
+ let amount_details = api_payments::PaymentAttemptAmountDetails::from(&self.0);
+ let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {
+ revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {
+ // Since we are recording the external paymenmt attempt, this is hardcoded to External
+ attempt_triggered_by: common_enums::TriggeredBy::External,
+ }),
+ };
+ let error = Option::<api_payments::RecordAttemptErrorDetails>::from(&self.0);
+ api_payments::PaymentsAttemptRecordRequest {
+ amount_details,
+ status: self.0.status,
+ billing: None,
+ shipping: None,
+ connector : payment_merchant_connector_account.as_ref().map(|account| account.connector_name),
+ payment_merchant_connector_id: payment_merchant_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone()),
+ error,
+ description: None,
+ connector_transaction_id: self.0.connector_transaction_id.clone(),
+ payment_method_type: self.0.payment_method_type,
+ billing_connector_id: billing_merchant_connector_account_id.clone(),
+ payment_method_subtype: self.0.payment_method_sub_type,
+ payment_method_data: None,
+ metadata: None,
+ feature_metadata: Some(feature_metadata),
+ transaction_created_at: self.0.transaction_created_at,
+ processor_payment_method_token: self.0.processor_payment_method_token.clone(),
+ connector_customer_id: self.0.connector_customer_id.clone(),
+ }
+ }
+
+ pub async fn find_payment_merchant_connector_account(
+ &self,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ billing_connector_account: &domain::MerchantConnectorAccount,
+ ) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {
+ let payment_merchant_connector_account_id = billing_connector_account
+ .get_payment_merchant_connector_account_id_using_account_reference_id(
+ self.0.connector_account_reference_id.clone(),
+ );
+ let db = &*state.store;
+ let key_manager_state = &(state).into();
+ let payment_merchant_connector_account = payment_merchant_connector_account_id
+ .as_ref()
+ .async_map(|mca_id| async move {
+ db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)
+ .await
+ })
+ .await
+ .transpose()
+ .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)
+ .attach_printable(
+ "failed to fetch payment merchant connector id using account reference id",
+ )?;
+ Ok(payment_merchant_connector_account)
}
}
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 2835acb472..9f509f3bcb 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -36,7 +36,7 @@ pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent,
PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, PostProcessing, PostSessionTokens,
- PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void,
+ PreProcessing, RecordAttempt, Reject, SdkSessionUpdate, Session, SetupMandate, Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,