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): update connector_mandate_details in payment_method (#4155)

Amisha Prabhatd8028cefd532
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ef153c23a7..488725f6ae 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -126,6 +126,9 @@ pub enum PaymentMethodUpdate {
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
+ ConnectorMandateDetailsUpdate {
+ connector_mandate_details: Option<serde_json::Value>,
+ },
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -135,6 +138,7 @@ pub struct PaymentMethodUpdateInternal {
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
status: Option<storage_enums::PaymentMethodStatus>,
+ connector_mandate_details: Option<serde_json::Value>,
}
impl PaymentMethodUpdateInternal {
@@ -153,6 +157,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data: None,
last_used_at: None,
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -161,18 +166,30 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data,
last_used_at: None,
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status,
+ connector_mandate_details: None,
+ },
+ PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ status: None,
+ connector_mandate_details,
},
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 59215da32f..64346a94a9 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -846,6 +846,20 @@ pub async fn update_payment_method(
Ok(())
}
+pub async fn update_payment_method_connector_mandate_details(
+ db: &dyn db::StorageInterface,
+ pm: payment_method::PaymentMethod,
+ connector_mandate_details: Option<serde_json::Value>,
+) -> errors::CustomResult<(), errors::VaultError> {
+ let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details,
+ };
+
+ db.update_payment_method(pm, pm_update)
+ .await
+ .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
+ Ok(())
+}
#[instrument(skip_all)]
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::AppState,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index e945e86a6f..6cb19a29a1 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -19,6 +19,7 @@ use crate::{
mandate,
payment_methods::PaymentMethodRetrieve,
payments::{
+ self,
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
@@ -878,6 +879,37 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.in_current_span(),
);
+ let flow_name = core_utils::get_flow_name::<F>()?;
+ if flow_name == "PSync" || flow_name == "CompleteAuthorize" {
+ let connector_mandate_id = match router_data.response.clone() {
+ Ok(resp) => match resp {
+ types::PaymentsResponseData::TransactionResponse {
+ ref mandate_reference,
+ ..
+ } => {
+ if let Some(mandate_ref) = mandate_reference {
+ mandate_ref.connector_mandate_id.clone()
+ } else {
+ None
+ }
+ }
+ _ => None,
+ },
+ Err(_) => None,
+ };
+ if let Some(ref payment_method) = payment_data.payment_method_info {
+ payments::tokenization::update_connector_mandate_details_in_payment_method(
+ payment_method.clone(),
+ payment_method.payment_method_type,
+ Some(payment_data.payment_attempt.amount),
+ payment_data.payment_attempt.currency,
+ payment_data.payment_attempt.merchant_connector_id.clone(),
+ connector_mandate_id,
+ )
+ .await?;
+ }
+ }
+
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 10e39b2d1b..3941fad5a4 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -89,19 +89,33 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
- let connector_mandate_details = if resp.request.get_setup_mandate_details().is_none()
+ let connector_mandate_id = match responses {
+ types::PaymentsResponseData::TransactionResponse {
+ ref mandate_reference,
+ ..
+ } => {
+ if let Some(mandate_ref) = mandate_reference {
+ mandate_ref.connector_mandate_id.clone()
+ } else {
+ None
+ }
+ }
+ _ => None,
+ };
+ let check_for_mit_mandates = resp.request.get_setup_mandate_details().is_none()
&& resp
.request
.get_setup_future_usage()
.map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession)
- .unwrap_or(false)
- {
+ .unwrap_or(false);
+ // insert in PaymentMethods if its a off-session mit payment
+ let connector_mandate_details = if check_for_mit_mandates {
add_connector_mandate_details_in_payment_method(
- responses,
payment_method_type,
amount,
currency,
- connector,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
)
} else {
None
@@ -196,7 +210,9 @@ where
)?;
if let Some(metadata) = pm_metadata {
payment_methods::cards::update_payment_method(
- db, pm, metadata,
+ db,
+ pm.clone(),
+ metadata,
)
.await
.change_context(
@@ -204,6 +220,24 @@ where
)
.attach_printable("Failed to add payment method in db")?;
};
+ // update if its a off-session mit payment
+ if check_for_mit_mandates {
+ let connector_mandate_details =
+ update_connector_mandate_details_in_payment_method(
+ pm.clone(),
+ payment_method_type,
+ amount,
+ currency,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
+ )
+ .await?;
+
+ payment_methods::cards::update_payment_method_connector_mandate_details(db, pm, connector_mandate_details).await.change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("Failed to update payment method in db")?;
+ }
}
Err(err) => {
if err.current_context().is_db_not_found() {
@@ -268,31 +302,54 @@ where
resp.payment_method_id = payment_method_id;
- let existing_pm =
- match payment_method {
- Ok(pm) => Ok(pm),
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &resp,
- payment_method_create_request.clone(),
- key_store,
- &merchant_account.merchant_id,
- &customer.customer_id,
- resp.metadata.clone().map(|val| val.expose()),
- customer_acceptance,
- locker_id,
- connector_mandate_details,
+ let existing_pm = match payment_method {
+ Ok(pm) => {
+ // update if its a off-session mit payment
+ if check_for_mit_mandates {
+ let connector_mandate_details =
+ update_connector_mandate_details_in_payment_method(
+ pm.clone(),
+ payment_method_type,
+ amount,
+ currency,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
)
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }
+ .await?;
+
+ payment_methods::cards::update_payment_method_connector_mandate_details(db, pm.clone(), connector_mandate_details).await.change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("Failed to update payment method in db")?;
}
- }?;
+ Ok(pm)
+ }
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ customer_acceptance,
+ locker_id,
+ connector_mandate_details,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable(
+ "Error while finding payment method",
+ )
+ }
+ }
+ }?;
payment_methods::cards::delete_card_from_locker(
state,
@@ -657,32 +714,17 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
}
}
-fn add_connector_mandate_details_in_payment_method(
- resp: types::PaymentsResponseData,
+pub fn add_connector_mandate_details_in_payment_method(
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
- connector: &api::ConnectorData,
+ merchant_connector_id: Option<String>,
+ connector_mandate_id: Option<String>,
) -> Option<storage::PaymentsMandateReference> {
let mut mandate_details = HashMap::new();
- let connector_mandate_id = match resp {
- types::PaymentsResponseData::TransactionResponse {
- mandate_reference, ..
- } => {
- if let Some(mandate_ref) = mandate_reference {
- mandate_ref.connector_mandate_id.clone()
- } else {
- None
- }
- }
- _ => None,
- };
-
- if let Some((mca_id, connector_mandate_id)) = connector
- .merchant_connector_id
- .clone()
- .zip(connector_mandate_id)
+ if let Some((mca_id, connector_mandate_id)) =
+ merchant_connector_id.clone().zip(connector_mandate_id)
{
mandate_details.insert(
mca_id,
@@ -698,3 +740,63 @@ fn add_connector_mandate_details_in_payment_method(
None
}
}
+
+pub async fn update_connector_mandate_details_in_payment_method(
+ payment_method: diesel_models::PaymentMethod,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ authorized_amount: Option<i64>,
+ authorized_currency: Option<storage_enums::Currency>,
+ merchant_connector_id: Option<String>,
+ connector_mandate_id: Option<String>,
+) -> RouterResult<Option<serde_json::Value>> {
+ let mandate_reference = match payment_method.connector_mandate_details {
+ Some(_) => {
+ let mandate_details = payment_method
+ .connector_mandate_details
+ .map(|val| {
+ val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference")
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+
+ if let Some((mca_id, connector_mandate_id)) =
+ merchant_connector_id.clone().zip(connector_mandate_id)
+ {
+ let updated_record = storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id: connector_mandate_id.clone(),
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ };
+ mandate_details.map(|mut payment_mandate_reference| {
+ payment_mandate_reference
+ .entry(mca_id)
+ .and_modify(|pm| *pm = updated_record)
+ .or_insert(storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id,
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ });
+ payment_mandate_reference
+ })
+ } else {
+ None
+ }
+ }
+ None => add_connector_mandate_details_in_payment_method(
+ payment_method_type,
+ authorized_amount,
+ authorized_currency,
+ merchant_connector_id,
+ connector_mandate_id,
+ ),
+ };
+ let connector_mandate_details = mandate_reference
+ .map(|mand| mand.encode_to_value())
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize customer acceptance to value")?;
+ Ok(connector_mandate_details)
+}