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/connector): [SANTANDER] Implemented Incoming Webhooks for PixQr, PixAutomaticoQr, PixAutomaticoPush (#13477)

Sayak Bhattacharya4cc106344b4c
diff --git a/Cargo.lock b/Cargo.lock
index d0e45c25cd..c1285ffbcb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4890,6 +4890,7 @@ dependencies = [
"serde",
"serde_json",
"serde_with",
+ "strum 0.26.3",
"time 0.3.41",
"url 2.5.4",
"utoipa",
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 6bb75250a7..ad7abffa71 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -46636,6 +46636,14 @@
"example": "E9040088820260710172800044983797",
"nullable": true
},
+ "journey_name": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderJourneyName"
+ }
+ ],
+ "nullable": true
+ },
"paid_at": {
"type": "string",
"format": "date-time",
@@ -46646,6 +46654,16 @@
},
"additionalProperties": false
},
+ "SantanderJourneyName": {
+ "type": "string",
+ "enum": [
+ "journey_1",
+ "journey_2",
+ "journey_3",
+ "journey_4",
+ "awaiting_definition"
+ ]
+ },
"SantanderMandateDetails": {
"type": "object",
"properties": {
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index bf4878b1fa..f12aaf9b5a 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -32939,6 +32939,14 @@
"example": "E9040088820260710172800044983797",
"nullable": true
},
+ "journey_name": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderJourneyName"
+ }
+ ],
+ "nullable": true
+ },
"paid_at": {
"type": "string",
"format": "date-time",
@@ -32949,6 +32957,16 @@
},
"additionalProperties": false
},
+ "SantanderJourneyName": {
+ "type": "string",
+ "enum": [
+ "journey_1",
+ "journey_2",
+ "journey_3",
+ "journey_4",
+ "awaiting_definition"
+ ]
+ },
"SantanderMandateDetails": {
"type": "object",
"properties": {
diff --git a/config/config.example.toml b/config/config.example.toml
index b63f4ba921..f125cee90f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -767,6 +767,8 @@ wallet.apple_pay = { connector_list = "stripe,adyen,braintree,cybersource,noon,b
wallet.samsung_pay = { connector_list = "cybersource" }
wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet,novalnet,worldpayxml,imerchantsolutions,datatrans,moneris,shift4,revolv3" }
bank_redirect.giropay = { connector_list = "globalpay" }
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
network_token.network_token.connector_list = "peachpayments"
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 532fc0848c..e56c321fed 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -315,6 +315,8 @@ bank_redirect.bancontact_card.connector_list="adyen,stripe"
bank_redirect.trustly.connector_list="adyen,aci"
bank_redirect.open_banking_uk.connector_list="adyen"
bank_redirect.eps.connector_list="globalpay,nexinets,aci,multisafepay"
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 355fa556c8..b78085db32 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -319,6 +319,8 @@ bank_redirect.bancontact_card.connector_list="adyen,stripe"
bank_redirect.trustly.connector_list="adyen,aci"
bank_redirect.open_banking_uk.connector_list="adyen"
bank_redirect.eps.connector_list="globalpay,nexinets,aci,multisafepay"
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 7b46cf12da..824871a360 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -322,6 +322,8 @@ bank_redirect.bancontact_card.connector_list="adyen,stripe"
bank_redirect.trustly.connector_list="adyen,aci"
bank_redirect.open_banking_uk.connector_list="adyen"
bank_redirect.eps.connector_list="globalpay,nexinets,aci,multisafepay"
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
diff --git a/config/development.toml b/config/development.toml
index d568fa0caf..f8a8e0c18b 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1406,6 +1406,8 @@ bank_redirect.bancontact_card.connector_list = "adyen,stripe"
bank_redirect.trustly.connector_list = "adyen,aci"
bank_redirect.open_banking_uk.connector_list = "adyen"
bank_redirect.eps.connector_list = "globalpay,nexinets,aci,multisafepay"
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
[mandates.update_mandate_supported]
card.credit = { connector_list = "cybersource" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 43232343a5..e72df1d3e2 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -1292,6 +1292,8 @@ bank_debit.sepa = { connector_list = "gocardless,adyen" }
bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay,aci" }
bank_redirect.sofort = { connector_list = "globalpay,aci" }
bank_redirect.giropay = { connector_list = "globalpay,aci" }
+bank_transfer.pix_automatico_push = { connector_list = "santander" }
+bank_transfer.pix_automatico_qr = { connector_list = "santander" }
network_token.network_token.connector_list = "peachpayments"
[mandates.update_mandate_supported]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index e5cac4ee73..5e6a9fe165 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -10782,6 +10782,9 @@ pub struct SantanderData {
#[schema(value_type = Option<String>, example = "E9040088820260710172800044983797")]
#[serde(skip_serializing_if = "Option::is_none")]
pub end_to_end_id: Option<String>,
+ #[schema(value_type = Option<SantanderJourneyName>, example = "journey_1")]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub journey_name: Option<SantanderJourneyName>,
/// Actual timestamp when the payment was completed, as reported by Santander.
#[schema(value_type = Option<PrimitiveDateTime>, example = "2025-07-20T14:35:00Z")]
#[serde(
@@ -10791,6 +10794,28 @@ pub struct SantanderData {
pub paid_at: Option<PrimitiveDateTime>,
}
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel,
+)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub enum SantanderJourneyName {
+ #[serde(rename = "journey_1")]
+ // PixAutomaticoPush payment method type for zero-amount payments.
+ Journey1,
+ #[serde(rename = "journey_2")]
+ // PixAutomaticoQr payment method type for zero-amount payments.
+ Journey2,
+ #[serde(rename = "journey_3")]
+ // PixAutomaticoQr payment method type for non-zero payments with immediate QR expiry.
+ Journey3,
+ #[serde(rename = "journey_4")]
+ // PixAutomaticoQr payment method type for non-zero payments with scheduled QR expiry.
+ Journey4,
+ #[serde(rename = "awaiting_definition")]
+ // Journey could not be determined from the connector response.
+ AwaitingDefinition,
+}
+
impl ConnectorMetadata {
pub fn from_value(
value: pii::SecretSerdeValue,
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index f6b3397351..b9b8607cd1 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -46,6 +46,8 @@ pub enum IncomingWebhookEvent {
DisputeLost,
MandateActive,
MandateRevoked,
+ // Mandate created at the connector, waiting for the customer to approve it
+ MandateActionRequired,
EndpointVerification,
ExternalAuthenticationARes,
FrmApproved,
@@ -301,6 +303,7 @@ impl From<IncomingWebhookEvent> for WebhookFlow {
IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => {
Self::Mandate
}
+ IncomingWebhookEvent::MandateActionRequired => Self::ReturnResponse,
IncomingWebhookEvent::PaymentAssociatedDataUpdate => Self::AssociatedDataUpdate,
IncomingWebhookEvent::DisputeOpened
| IncomingWebhookEvent::DisputeAccepted
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 52d7be8d03..8dc7ed43d2 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -11231,6 +11231,42 @@ impl From<ConnectorMandateStatus> for ConnectorTokenStatus {
}
}
+impl From<AttemptStatus> for ConnectorTokenStatus {
+ fn from(status: AttemptStatus) -> Self {
+ match status {
+ AttemptStatus::Charged
+ | AttemptStatus::Authorized
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::PartiallyAuthorized => Self::Active,
+ AttemptStatus::Failure
+ | AttemptStatus::Voided
+ | AttemptStatus::VoidedPostCharge
+ | AttemptStatus::Started
+ | AttemptStatus::Pending
+ | AttemptStatus::Unresolved
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::Authorizing
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::AutoRefunded
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::DeviceDataCollectionPending
+ | AttemptStatus::IntegrityFailure
+ | AttemptStatus::Expired
+ | AttemptStatus::CaptureReview => Self::Inactive,
+ }
+ }
+}
+
impl From<ConnectorTokenStatus> for ConnectorMandateStatus {
fn from(status: ConnectorTokenStatus) -> Self {
match status {
diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rs
index 23ab114ac5..6b75145074 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs
@@ -4,15 +4,20 @@ pub mod transformers;
use std::sync::LazyLock;
-use api_models::merchant_connector_webhook_management::{Scope, ScopeIdentifier};
+use api_models::{
+ merchant_connector_webhook_management::{Scope, ScopeIdentifier},
+ payments::PaymentIdType,
+ webhooks::{IncomingWebhookEvent, ObjectReferenceId},
+};
use common_enums::enums;
use common_utils::{
+ crypto,
errors::CustomResult,
- ext_traits::{BytesExt, ValueExt},
+ ext_traits::{ByteSliceExt, BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
- types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
+ types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
@@ -66,7 +71,7 @@ use hyperswitch_interfaces::{
types::{self, ConnectorWebhookRegisterType, RefreshTokenType, Response},
webhooks,
};
-use hyperswitch_masking::{Maskable, PeekInterface};
+use hyperswitch_masking::{Maskable, PeekInterface, Secret};
use crate::{
connectors::santander::{
@@ -82,8 +87,10 @@ use crate::{
SantanderCreatePixPayloadLocationResponse, SantanderEmptyResponse,
SantanderErrorResponse, SantanderGenericErrorResponse, SantanderPaymentsResponse,
SantanderPaymentsSyncResponse, SantanderPixAutomaticRecResponse,
- SantanderPixAutomaticSolicitationResponse, SantanderPixWebhookRegisterResponse,
+ SantanderPixAutomaticSolicitationResponse, SantanderPixAutomaticoRecWebhookBody,
+ SantanderPixQrWebhookBody, SantanderPixWebhookRegisterResponse,
SantanderRefundResponse, SantanderUpdateResponse, SantanderVoidResponse,
+ SantanderWebhookBody,
},
},
constants::headers,
@@ -1498,13 +1505,15 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San
SantanderPaymentsSyncResponse::PixQRCode(ref pix_data) => {
pix_data.valor.original.clone()
}
- // No amount is sent back in Boleto response
- SantanderPaymentsSyncResponse::Boleto(_) => convert_amount(
+ SantanderPaymentsSyncResponse::PixQrWebhook(_) => convert_amount(
self.amount_converter,
data.request.amount,
data.request.currency,
)?,
- SantanderPaymentsSyncResponse::PixAutomaticoConsultAndActivateJourney(_) => {
+ // No amount is sent back in Boleto response
+ SantanderPaymentsSyncResponse::Boleto(_)
+ | SantanderPaymentsSyncResponse::PixAutomaticoRecWebhook(_)
+ | SantanderPaymentsSyncResponse::PixAutomaticoConsultAndActivateJourney(_) => {
convert_amount(
self.amount_converter,
data.request.amount,
@@ -2055,27 +2064,251 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Santander
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Santander {
- fn get_webhook_object_reference_id(
+ async fn verify_webhook_source(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
+ _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
+ _connector_name: &str,
+ ) -> CustomResult<bool, errors::ConnectorError> {
+ // Source verification for Santander is MTLS which is handled at the transport layer. No additional verification is needed here in application side
+ Ok(true)
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
+ // Santander sends an empty-body request (typically GET) to validate the
+ // webhook URL during registration. There is no object reference in such probe requests
+ if request.body.is_empty() {
+ return Err(errors::ConnectorError::WebhookReferenceIdNotFound.into());
+ }
+
+ let body: SantanderWebhookBody = request
+ .body
+ .parse_struct("SantanderWebhookBody")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ match body {
+ SantanderWebhookBody::PixQr(SantanderPixQrWebhookBody { pix }) => {
+ let txid = pix
+ .first()
+ .map(|entry| entry.txid.peek().to_owned())
+ .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ Ok(ObjectReferenceId::PaymentId(
+ PaymentIdType::ConnectorTransactionId(txid),
+ ))
+ }
+ SantanderWebhookBody::Recurrence(SantanderPixAutomaticoRecWebhookBody { recs }) => {
+ let entry = recs
+ .first()
+ .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ // Santander sends a dummy webhook with "TESTE" in idRec during
+ // webhook registration, skip DB lookups for these
+ if transformers::is_dummy_webhook(&entry.id_rec) {
+ return Err(errors::ConnectorError::WebhookReferenceIdNotFound.into());
+ }
+
+ if matches!(&entry.status, responses::RecurrenceStatus::Criada) {
+ return Err(errors::ConnectorError::WebhookReferenceIdNotFound.into());
+ }
+
+ match transformers::get_pix_automatico_journey_type(entry) {
+ Some(
+ responses::SantanderJourneyType::Jornada1
+ | responses::SantanderJourneyType::Jornada2,
+ ) => Ok(ObjectReferenceId::PaymentId(
+ PaymentIdType::ConnectorTransactionId(entry.id_rec.clone()),
+ )),
+ Some(
+ responses::SantanderJourneyType::Jornada3
+ | responses::SantanderJourneyType::Jornada4,
+ ) => {
+ let connector_transaction_id = entry
+ .ativacao
+ .as_ref()
+ .and_then(|activation| activation.dados_jornada.as_ref())
+ .and_then(|journey| journey.txid.clone())
+ .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ Ok(ObjectReferenceId::PaymentId(
+ PaymentIdType::ConnectorTransactionId(connector_transaction_id),
+ ))
+ }
+ _ => Err(errors::ConnectorError::WebhookReferenceIdNotFound.into()),
+ }
+ }
+ }
}
fn get_webhook_event_type(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_context: Option<&webhooks::WebhookContext>,
- ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ // Santander sends an empty-body request (typically GET) to validate the
+ // webhook URL during registration. Acknowledge these probe requests
+ // without further processing.
+ if request.body.is_empty() {
+ return Ok(IncomingWebhookEvent::EndpointVerification);
+ }
+
+ let body: SantanderWebhookBody = request
+ .body
+ .parse_struct("SantanderWebhookBody")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+
+ match body {
+ SantanderWebhookBody::PixQr(SantanderPixQrWebhookBody { pix }) => {
+ // The presence of `endToEndId` inside the pix entries indicates the payment was received successfully.
+ let is_payment_successful = pix
+ .first()
+ .is_some_and(|entry| !entry.end_to_end_id.peek().is_empty());
+
+ if is_payment_successful {
+ Ok(IncomingWebhookEvent::PaymentIntentSuccess)
+ } else {
+ Ok(IncomingWebhookEvent::PaymentIntentFailure)
+ }
+ }
+ SantanderWebhookBody::Recurrence(SantanderPixAutomaticoRecWebhookBody { recs }) => {
+ let entry = recs
+ .first()
+ .ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?;
+
+ if transformers::is_dummy_webhook(&entry.id_rec) {
+ return Ok(IncomingWebhookEvent::EventNotSupported);
+ }
+
+ match entry.status {
+ responses::RecurrenceStatus::Aprovada => {
+ match transformers::get_pix_automatico_journey_type(entry) {
+ Some(
+ responses::SantanderJourneyType::Jornada1
+ | responses::SantanderJourneyType::Jornada2,
+ ) => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
+ Some(
+ responses::SantanderJourneyType::Jornada3
+ | responses::SantanderJourneyType::Jornada4,
+ ) => Ok(IncomingWebhookEvent::MandateActive),
+ _ => Ok(IncomingWebhookEvent::EventNotSupported),
+ }
+ }
+ responses::RecurrenceStatus::Criada => {
+ Ok(IncomingWebhookEvent::MandateActionRequired)
+ }
+ responses::RecurrenceStatus::Rejeitada
+ | responses::RecurrenceStatus::Expirada
+ | responses::RecurrenceStatus::Cancelada => {
+ Ok(IncomingWebhookEvent::MandateRevoked)
+ }
+ _ => Ok(IncomingWebhookEvent::EventNotSupported),
+ }
+ }
+ }
+ }
+
+ fn get_webhook_mandate_details_update(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Option<webhooks::IncomingWebhookMandateDetailsUpdate>, errors::ConnectorError>
+ {
+ if request.body.is_empty() {
+ return Ok(None);
+ }
+
+ let body: SantanderWebhookBody = request
+ .body
+ .parse_struct("SantanderWebhookBody")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ match body {
+ SantanderWebhookBody::PixQr(SantanderPixQrWebhookBody { pix }) => {
+ let pix = pix
+ .first()
+ .filter(|pix| !pix.end_to_end_id.peek().is_empty());
+
+ pix.map(|pix| {
+ let amount = serde_json::Value::String(pix.valor.clone())
+ .parse_value::<StringMajorUnit>("StringMajorUnit")
+ .change_context(errors::ConnectorError::ParsingFailed)
+ .and_then(|amount| {
+ self.amount_converter
+ .convert_back(amount, enums::Currency::BRL)
+ .change_context(errors::ConnectorError::ParsingFailed)
+ })?;
+
+ Ok(webhooks::IncomingWebhookMandateDetailsUpdate {
+ connector_mandate_status: None,
+ original_payment_authorized_amount: Some(amount),
+ original_payment_authorized_currency: Some(enums::Currency::BRL),
+ })
+ })
+ .transpose()
+ }
+ SantanderWebhookBody::Recurrence(SantanderPixAutomaticoRecWebhookBody { recs }) => {
+ let entry = recs
+ .first()
+ .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ if transformers::is_dummy_webhook(&entry.id_rec) {
+ return Ok(None);
+ }
+
+ match entry.status {
+ responses::RecurrenceStatus::Aprovada => {
+ match transformers::get_pix_automatico_journey_type(entry) {
+ Some(
+ responses::SantanderJourneyType::Jornada1
+ | responses::SantanderJourneyType::Jornada2,
+ ) => Ok(Some(webhooks::IncomingWebhookMandateDetailsUpdate {
+ connector_mandate_status: Some(
+ enums::ConnectorMandateStatus::Active,
+ ),
+ original_payment_authorized_amount: Some(MinorUnit::zero()),
+ original_payment_authorized_currency: Some(enums::Currency::BRL),
+ })),
+ Some(
+ responses::SantanderJourneyType::Jornada3
+ | responses::SantanderJourneyType::Jornada4,
+ ) => Ok(Some(webhooks::IncomingWebhookMandateDetailsUpdate {
+ connector_mandate_status: Some(
+ enums::ConnectorMandateStatus::Active,
+ ),
+ original_payment_authorized_amount: None,
+ original_payment_authorized_currency: None,
+ })),
+ _ => Ok(None),
+ }
+ }
+ responses::RecurrenceStatus::Rejeitada
+ | responses::RecurrenceStatus::Expirada
+ | responses::RecurrenceStatus::Cancelada => {
+ Ok(Some(webhooks::IncomingWebhookMandateDetailsUpdate {
+ connector_mandate_status: Some(enums::ConnectorMandateStatus::Inactive),
+ original_payment_authorized_amount: None,
+ original_payment_authorized_currency: None,
+ }))
+ }
+ _ => Ok(None),
+ }
+ }
+ }
}
fn get_webhook_resource_object(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>, errors::ConnectorError>
{
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ let body: SantanderWebhookBody = request
+ .body
+ .parse_struct("SantanderWebhookBody")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+ Ok(Box::new(body))
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/responses.rs b/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
index 0e68d222fa..3e7912cfe5 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
@@ -397,9 +397,11 @@ pub struct SantanderCalendarResponse {
#[serde(untagged)]
pub enum SantanderPaymentsSyncResponse {
PixQRCode(Box<SantanderPixQRCodeSyncResponse>),
+ PixAutomaticoCobrSync(Box<SantanderPixAutomaticoCobrSyncResponse>),
+ PixQrWebhook(Box<SantanderPixQrWebhookResponse>),
+ PixAutomaticoRecWebhook(Box<SantanderPixAutomaticoRecWebhookBody>),
Boleto(Box<SantanderBoletoPSyncResponse>),
PixAutomaticoConsultAndActivateJourney(Box<SantanderPixAutomaticRecResponse>),
- PixAutomaticoCobrSync(Box<SantanderPixAutomaticoCobrSyncResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -911,6 +913,49 @@ pub struct SantanderPaymentDetails {
pub tx_id: Option<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixQrWebhookBody {
+ pub pix: Vec<SantanderPix>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct SantanderPixQrWebhookResponse {
+ pub pix: Vec<SantanderPix>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoRecWebhookEntry {
+ /// Recurrence ID (maps to Hyperswitch connector_mandate_id)
+ pub id_rec: String,
+ /// Current status of the recurrence
+ pub status: RecurrenceStatus,
+ /// Status update history
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub atualizacao: Option<Vec<SantanderPixAutomaticoAtualizacao>>,
+ /// Activation journey details
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ativacao: Option<SantanderPixAutomaticoAtivacao>,
+ /// Closure details (present on cancellation/rejection)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub encerramento: Option<SantanderPixAutomaticoEncerramento>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoRecWebhookBody {
+ pub recs: Vec<SantanderPixAutomaticoRecWebhookEntry>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum SantanderWebhookBody {
+ PixQr(SantanderPixQrWebhookBody),
+ Recurrence(SantanderPixAutomaticoRecWebhookBody),
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SantanderBoletoStatus {
@@ -1100,6 +1145,8 @@ pub struct SantanderPixAutomaticoLoc {
pub struct SantanderPixAutomaticoEncerramento {
/// Rejection information if the recurrence was closed due to rejection
pub rejeicao: Option<SantanderPixAutomaticoRejeicao>,
+ /// Cancellation information if the recurrence was cancelled
+ pub cancelamento: Option<SantanderPixAutomaticoCancelamento>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -1111,11 +1158,22 @@ pub struct SantanderPixAutomaticoRejeicao {
pub descricao: Option<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCancelamento {
+ /// Who requested the cancellation (e.g. "USUARIO_PAGADOR")
+ pub solicitante: Option<String>,
+ /// Cancellation code
+ pub codigo: Option<String>,
+ /// Description of the cancellation reason
+ pub descricao: Option<String>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderPixAutomaticoAtivacao {
/// Type of journey/flow used to activate the recurrence
- pub tipo_jornada: Option<String>,
+ pub tipo_jornada: Option<SantanderJourneyType>,
/// Data associated with the activation journey
pub dados_jornada: Option<SantanderPixAutomaticoDadosJornada>,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
index ddcd0289d8..f1e8b09d3c 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
@@ -1,7 +1,8 @@
use api_models::payments::{
AccountType, BeneficiaryDetails, BoletoPaymentTypeConstraints, CalculationType, DiscountTier,
DiscountType, FeatureMetadata, PollConfig, ProtestType, QrCodeInformation, SantanderData,
- SantanderMandatePeriodicity, SantanderPaymentDiscountRules, VoucherNextStepData,
+ SantanderJourneyName, SantanderMandatePeriodicity, SantanderPaymentDiscountRules,
+ VoucherNextStepData,
};
use common_enums::{enums, AttemptStatus, BoletoDocumentKind, ExpiryType, PixKey};
use common_utils::{
@@ -73,6 +74,7 @@ use crate::{
SantanderPaymentStatus, SantanderPaymentsResponse, SantanderPaymentsSyncResponse,
SantanderPixAutomaticRecResponse, SantanderPixAutomaticSolicitationResponse,
SantanderPixAutomaticoCobrStatus, SantanderPixAutomaticoCobrSyncResponse,
+ SantanderPixAutomaticoRecWebhookBody, SantanderPixAutomaticoRecWebhookEntry,
SantanderPixKeyType, SantanderPixQRCodePaymentsResponse,
SantanderPixQRCodeSyncResponse, SantanderPixWebhookRegisterResponse,
SantanderRefundResponse, SantanderRefundStatus, SantanderSetupMandateResponse,
@@ -165,8 +167,7 @@ impl
.status
.map(AttemptStatus::from)
.unwrap_or(AttemptStatus::Pending);
- let resource_id =
- ResponseId::ConnectorTransactionId(item.data.connector_request_reference_id.clone());
+ let resource_id = ResponseId::ConnectorTransactionId(item.response.id_rec.clone().expose());
let connector_response_reference_id = Some(item.response.id_solic_rec.clone().expose());
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.id_rec.clone().expose()),
@@ -226,7 +227,7 @@ impl
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "response.dadosQR.jornada".into(),
})?;
- let expiry_type = journey.and_then(Option::<ExpiryType>::from);
+ let expiry_type = journey.clone().and_then(Option::<ExpiryType>::from);
let connector_metadata = match item
.response
.dados_qr
@@ -236,14 +237,33 @@ impl
Some(pix_copia_e_cola) => convert_pix_data_to_value(pix_copia_e_cola, expiry_type)?,
None => None,
};
+ let connector_mandate_request_reference_id = item
+ .response
+ .ativacao
+ .as_ref()
+ .and_then(|activation| activation.dados_jornada.as_ref())
+ .and_then(|journey| journey.txid.clone());
let mandate_reference = Box::new(Some(MandateReference {
connector_mandate_id: Some(item.response.id_rec.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
- connector_mandate_request_reference_id: None,
+ connector_mandate_request_reference_id: connector_mandate_request_reference_id.clone(),
}));
- let resource_id =
- ResponseId::ConnectorTransactionId(item.data.connector_request_reference_id.clone());
+ let connector_transaction_id = match journey.as_ref() {
+ Some(SantanderJourneyType::Jornada3 | SantanderJourneyType::Jornada4) => Some(
+ connector_mandate_request_reference_id
+ .unwrap_or_else(|| item.data.connector_request_reference_id.clone()),
+ ),
+ Some(SantanderJourneyType::Jornada2) | None => {
+ Some(item.response.id_rec.clone().expose())
+ }
+ Some(SantanderJourneyType::Jornada1 | SantanderJourneyType::AguardandoDefinicao) => {
+ None
+ }
+ };
+ let resource_id = connector_transaction_id
+ .map(ResponseId::ConnectorTransactionId)
+ .unwrap_or(ResponseId::NoResponseId);
Ok(Self {
status,
@@ -1260,7 +1280,7 @@ impl From<RecurrenceStatus> for AttemptStatus {
RecurrenceStatus::Aprovada => Self::Charged,
RecurrenceStatus::Rejeitada => Self::Failure,
RecurrenceStatus::Expirada => Self::Failure,
- RecurrenceStatus::Cancelada => Self::Voided,
+ RecurrenceStatus::Cancelada => Self::Failure,
RecurrenceStatus::Recebida | RecurrenceStatus::Aceita | RecurrenceStatus::Enviada => {
Self::Pending
}
@@ -1355,6 +1375,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
.map(|pix| {
let data = SantanderData {
end_to_end_id: Some(pix.end_to_end_id.clone().expose()),
+ journey_name: None,
paid_at: (attempt_status == AttemptStatus::Charged)
.then_some(pix.horario),
};
@@ -1399,7 +1420,105 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
}
}
}
+ SantanderPaymentsSyncResponse::PixQrWebhook(pix_data) => {
+ let has_end_to_end_id = pix_data
+ .pix
+ .first()
+ .map(|pix| !pix.end_to_end_id.clone().expose().is_empty())
+ .unwrap_or(false);
+ let attempt_status = if has_end_to_end_id {
+ AttemptStatus::Charged
+ } else {
+ AttemptStatus::Failure
+ };
+ let connector_metadata = pix_data
+ .pix
+ .first()
+ .map(|pix| {
+ let data = SantanderData {
+ end_to_end_id: Some(pix.end_to_end_id.clone().expose()),
+ journey_name: None,
+ paid_at: (attempt_status == AttemptStatus::Charged)
+ .then_some(pix.horario),
+ };
+ serde_json::to_value(data)
+ .change_context(errors::ConnectorError::ParsingFailed)
+ })
+ .transpose()?;
+
+ let txid = pix_data
+ .pix
+ .first()
+ .map(|pix| pix.txid.clone().expose())
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "txid".into(),
+ })?;
+
+ let response = match item.data.response.clone() {
+ Ok(PaymentsResponseData::TransactionResponse {
+ redirection_data,
+ mandate_reference,
+ network_txn_id,
+ connector_response_reference_id,
+ incremental_authorization_allowed,
+ authentication_data,
+ charges,
+ ..
+ }) => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(txid),
+ redirection_data,
+ mandate_reference,
+ connector_metadata,
+ network_txn_id,
+ network_txn_link_id: None,
+ connector_response_reference_id,
+ incremental_authorization_allowed,
+ authentication_data,
+ charges,
+ payment_account_reference: None,
+ }),
+ other => other,
+ };
+
+ Ok(Self {
+ status: attempt_status,
+ response,
+ ..item.data
+ })
+ }
// Journey 1/2
+ SantanderPaymentsSyncResponse::PixAutomaticoRecWebhook(rec_data) => {
+ let entry =
+ rec_data
+ .recs
+ .first()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "recs".into(),
+ })?;
+
+ let status = AttemptStatus::from(entry.status.clone());
+ let connector_metadata =
+ get_pix_automatico_rec_webhook_connector_metadata(&rec_data)?;
+
+ let mut response = item.data.response.clone();
+ if let Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ref mut rid,
+ connector_response_reference_id: ref mut conn_response_ref_id,
+ connector_metadata: ref mut cm,
+ ..
+ }) = response
+ {
+ *rid = ResponseId::ConnectorTransactionId(entry.id_rec.clone());
+ *conn_response_ref_id = Some(entry.id_rec.clone());
+ *cm = connector_metadata;
+ }
+
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
SantanderPaymentsSyncResponse::PixAutomaticoConsultAndActivateJourney(res) => {
let status = AttemptStatus::from(res.status.clone());
let connector_metadata = if matches!(res.status, RecurrenceStatus::Aprovada) {
@@ -1409,6 +1528,11 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
.map(|update| {
let data = SantanderData {
end_to_end_id: None,
+ journey_name: res
+ .ativacao
+ .as_ref()
+ .and_then(|activation| activation.tipo_jornada.as_ref())
+ .map(SantanderJourneyName::from),
paid_at: Some(update.data),
};
serde_json::to_value(data)
@@ -1448,6 +1572,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
let paid_at = data.payment.date;
let data = SantanderData {
end_to_end_id: None,
+ journey_name: None,
paid_at,
};
serde_json::to_value(data)
@@ -1478,6 +1603,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
.map(|pix| {
let data = SantanderData {
end_to_end_id: Some(pix.end_to_end_id.clone().expose()),
+ journey_name: None,
paid_at: (attempt_status == AttemptStatus::Charged)
.then_some(pix.horario),
};
@@ -3260,3 +3386,71 @@ impl
})
}
}
+
+pub fn is_dummy_webhook(id_rec: &str) -> bool {
+ id_rec.to_uppercase().contains("TESTE")
+}
+
+fn get_pix_automatico_rec_webhook_connector_metadata(
+ rec_data: &SantanderPixAutomaticoRecWebhookBody,
+) -> Result<Option<Value>, Error> {
+ let connector_metadata = rec_data
+ .recs
+ .first()
+ .filter(|entry| {
+ matches!(entry.status, RecurrenceStatus::Aprovada)
+ && matches!(
+ get_pix_automatico_journey_type(entry),
+ Some(SantanderJourneyType::Jornada1 | SantanderJourneyType::Jornada2)
+ )
+ })
+ .and_then(|entry| {
+ entry
+ .atualizacao
+ .as_ref()
+ .and_then(|updates| {
+ updates
+ .iter()
+ .find(|update| matches!(update.status, Some(RecurrenceStatus::Aprovada)))
+ })
+ .map(|update| (entry, update))
+ })
+ .map(|(entry, update)| {
+ let data = SantanderData {
+ end_to_end_id: None,
+ journey_name: get_pix_automatico_journey_name(entry),
+ paid_at: Some(update.data),
+ };
+ serde_json::to_value(data).change_context(errors::ConnectorError::ParsingFailed)
+ })
+ .transpose()?;
+
+ Ok(connector_metadata)
+}
+
+fn get_pix_automatico_journey_name(
+ entry: &SantanderPixAutomaticoRecWebhookEntry,
+) -> Option<SantanderJourneyName> {
+ get_pix_automatico_journey_type(entry).map(SantanderJourneyName::from)
+}
+
+impl From<&SantanderJourneyType> for SantanderJourneyName {
+ fn from(journey_type: &SantanderJourneyType) -> Self {
+ match journey_type {
+ SantanderJourneyType::Jornada1 => Self::Journey1,
+ SantanderJourneyType::Jornada2 => Self::Journey2,
+ SantanderJourneyType::Jornada3 => Self::Journey3,
+ SantanderJourneyType::Jornada4 => Self::Journey4,
+ SantanderJourneyType::AguardandoDefinicao => Self::AwaitingDefinition,
+ }
+ }
+}
+
+pub fn get_pix_automatico_journey_type(
+ entry: &SantanderPixAutomaticoRecWebhookEntry,
+) -> Option<&SantanderJourneyType> {
+ entry
+ .ativacao
+ .as_ref()
+ .and_then(|activation| activation.tipo_jornada.as_ref())
+}
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index 22ded2e4b2..e34d4976a4 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -45,6 +45,7 @@ rustc-hash = "1.1.0"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
serde_with = "3.12.0"
+strum = { version = "0.26", features = ["derive"] }
time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] }
url = { version = "2.5.4", features = ["serde"] }
utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order", "time"] }
diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs
index 5840b73e5f..6071a4fc52 100644
--- a/crates/hyperswitch_domain_models/src/mandates.rs
+++ b/crates/hyperswitch_domain_models/src/mandates.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use api_models::payments::{
MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType,
};
-use common_enums::Currency;
+use common_enums::{AttemptStatus, Currency};
use common_types::payments as common_payments_types;
use common_utils::{
date_time,
@@ -15,7 +15,7 @@ use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use time::PrimitiveDateTime;
-use crate::router_data::RecurringMandatePaymentData;
+use crate::{payments::payment_attempt::PaymentAttempt, router_data::RecurringMandatePaymentData};
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
@@ -603,6 +603,50 @@ pub enum MandateTransactionType {
RecurringMandateTransaction,
}
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum MandateActivation {
+ /// The connector issued a mandate identifier but the customer's action is still pending
+ Pending,
+ /// The payment succeeded and the connector mandate can be treated as active
+ Successful,
+ /// The mandate could not be activated (non-success status)
+ Failed,
+}
+
+#[cfg(feature = "v1")]
+impl From<&PaymentAttempt> for MandateActivation {
+ fn from(payment_attempt: &PaymentAttempt) -> Self {
+ let has_connector_mandate_id = payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .and_then(|cmr| cmr.connector_mandate_id.as_ref())
+ .is_some();
+
+ match (has_connector_mandate_id, payment_attempt.status) {
+ (true, AttemptStatus::AuthenticationPending) => Self::Pending,
+ (
+ true,
+ AttemptStatus::Charged
+ | AttemptStatus::Authorized
+ | AttemptStatus::PartiallyAuthorized,
+ ) => Self::Successful,
+ _ => Self::Failed,
+ }
+ }
+}
+
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct MandateIds {
pub mandate_id: Option<String>,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index fc322884b5..1f438412d3 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -178,6 +178,16 @@ pub struct PaymentsAuthorizeData {
pub business_country: Option<common_enums::CountryAlpha2>,
}
+impl PaymentsAuthorizeData {
+ pub fn is_connector_mandate(&self) -> bool {
+ self.customer_acceptance.is_some()
+ && matches!(
+ self.setup_future_usage,
+ Some(storage_enums::FutureUsage::OffSession)
+ )
+ }
+}
+
#[derive(Debug, Clone, Serialize)]
pub struct ExternalVaultProxyPaymentsData {
pub payment_method_data: ExternalVaultPaymentMethodData,
@@ -1915,6 +1925,16 @@ pub struct SetupMandateRequestData {
pub business_country: Option<common_enums::CountryAlpha2>,
}
+impl SetupMandateRequestData {
+ pub fn is_connector_mandate(&self) -> bool {
+ self.customer_acceptance.is_some()
+ && matches!(
+ self.setup_future_usage,
+ Some(storage_enums::FutureUsage::OffSession)
+ )
+ }
+}
+
#[derive(Debug, Clone)]
pub struct VaultRequestData {
pub payment_method_vaulting_data: Option<PaymentMethodCustomVaultingData>,
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index 1974f329d8..292ba105b4 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -421,6 +421,19 @@ impl IncomingWebhook for ConnectorEnum {
}
}
+ fn get_webhook_mandate_details_update(
+ &self,
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<
+ Option<crate::webhooks::IncomingWebhookMandateDetailsUpdate>,
+ errors::ConnectorError,
+ > {
+ match self {
+ Self::Old(connector) => connector.get_webhook_mandate_details_update(request),
+ Self::New(connector) => connector.get_webhook_mandate_details_update(request),
+ }
+ }
+
fn get_additional_payment_method_data(
&self,
request: &IncomingWebhookRequestDetails<'_>,
diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs
index c99aebe5ea..6b94c8bf9e 100644
--- a/crates/hyperswitch_interfaces/src/webhooks.rs
+++ b/crates/hyperswitch_interfaces/src/webhooks.rs
@@ -145,6 +145,17 @@ impl From<&WebhookResourceData> for WebhookContext {
}
}
+/// Connector-provided mandate updates extracted from an incoming webhook.
+#[derive(Clone, Debug)]
+pub struct IncomingWebhookMandateDetailsUpdate {
+ /// Connector mandate status to persist, when the webhook carries a mandate state signal.
+ pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
+ /// Original authorized amount to persist when the webhook confirms the activation payment.
+ pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>,
+ /// Currency for the original authorized amount.
+ pub original_payment_authorized_currency: Option<common_enums::Currency>,
+}
+
/// Trait defining incoming webhook
#[async_trait::async_trait]
pub trait IncomingWebhook: ConnectorCommon + Sync {
@@ -385,6 +396,16 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
Ok(None)
}
+ /// Connector-specific mandate updates derived from a webhook. Use this when
+ /// the webhook tells us whether the mandate should become active/inactive,
+ /// or provides the payment amount that activated the mandate.
+ fn get_webhook_mandate_details_update(
+ &self,
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Option<IncomingWebhookMandateDetailsUpdate>, errors::ConnectorError> {
+ Ok(None)
+ }
+
/// fn to get associated data about a payment from the webhook body, if any
fn get_associated_data(
&self,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 03b1f35199..2f2167aa09 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -630,6 +630,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ConnectorMetadata,
api_models::payments::ConnectorMetadataResponse,
api_models::payments::SantanderData,
+ api_models::payments::SantanderJourneyName,
api_models::payments::WorldpayxmlData,
api_models::payments::CheckoutData,
api_models::payments::WorldpayxmlFundingTransactionType,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 8e11a8bc8a..ccbc9b8807 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -524,6 +524,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ConnectorMetadata,
api_models::payments::ConnectorMetadataResponse,
api_models::payments::SantanderData,
+ api_models::payments::SantanderJourneyName,
api_models::payments::WorldpayxmlData,
api_models::payments::CheckoutData,
api_models::payments::WorldpayxmlFundingTransactionType,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 8e709449e8..c47e262abd 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -25,7 +25,7 @@ use hyperswitch_domain_models::payments::{
PaymentConfirmData, PaymentIntentData, PaymentStatusData,
};
use hyperswitch_domain_models::{
- mandates::{self, ConnectorMandateReferenceId, MandateReferenceId},
+ mandates::{self, ConnectorMandateReferenceId, MandateActivation, MandateReferenceId},
payments::payment_attempt::PaymentAttempt,
};
use hyperswitch_masking::{ExposeInterface, PeekInterface};
@@ -257,13 +257,15 @@ where
.change_context(
::payment_methods::errors::ModularPaymentMethodError::UpdateFailed,
)?;
+ let connector_token_status =
+ ConnectorTokenStatus::from(resp.status);
mandate_reference
.connector_mandate_id
.map(|connector_mandate_id| {
::payment_methods::types::ConnectorTokenDetails {
connector_id,
token_type: TokenizationType::MultiUse,
- status: ConnectorTokenStatus::Active,
+ status: connector_token_status,
connector_token_request_reference_id: mandate_reference
.connector_mandate_request_reference_id,
original_payment_authorized_amount: Some(
@@ -434,8 +436,16 @@ where
| enums::AttemptStatus::PartiallyAuthorized
);
- let is_eligible_for_mandate_update =
- is_valid_response && is_integrity_ok && is_payment_successful;
+ // Some connectors register a mandate before the customer completes the action
+ // Store the connector_mandate_id early so that the mandate webhooks can be consumed without requiring a payment to be successful.
+ let is_mandate_pending_activation = matches!(
+ MandateActivation::from(payment_attempt),
+ MandateActivation::Pending
+ );
+
+ let is_eligible_for_mandate_update = is_valid_response
+ && is_integrity_ok
+ && (is_payment_successful || is_mandate_pending_activation);
if let (true, Some(payment_method), Some(mca_id)) = (
is_eligible_for_mandate_update,
@@ -485,22 +495,23 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference")?;
- let is_active_mandate = mandate_details
+ let existing_connector_mandate_status = mandate_details
.payments
.as_ref()
.and_then(|payments| payments.0.get(&mca_id))
- .is_some_and(|record| {
- record.connector_mandate_status
- == Some(common_enums::ConnectorMandateStatus::Active)
- });
+ .and_then(|record| record.connector_mandate_status);
+
+ let is_active_mandate =
+ existing_connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active);
let is_off_session = matches!(
payment_intent.setup_future_usage,
Some(common_enums::FutureUsage::OffSession)
);
- // Combine business logic conditions: not active mandate AND off_session
- if !is_active_mandate && is_off_session {
+ // Combine business logic conditions: not active mandate AND
+ // (off_session OR a pending mandate that the connector already issued).
+ if !is_active_mandate && (is_off_session || is_mandate_pending_activation) {
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) =
payment_attempt
.connector_mandate_detail
@@ -513,6 +524,12 @@ where
)
})
.unwrap_or((None, None, None));
+ let connector_mandate_status = match MandateActivation::from(payment_attempt) {
+ MandateActivation::Pending => existing_connector_mandate_status
+ .unwrap_or(common_enums::ConnectorMandateStatus::Inactive),
+ MandateActivation::Successful => common_enums::ConnectorMandateStatus::Active,
+ MandateActivation::Failed => common_enums::ConnectorMandateStatus::Inactive,
+ };
let connector_mandate_details = tokenization::update_connector_mandate_details(
Some(mandate_details),
@@ -527,6 +544,7 @@ where
payment_attempt.merchant_connector_id.clone(),
connector_mandate_id,
mandate_metadata,
+ connector_mandate_status,
connector_mandate_request_reference_id,
)?;
@@ -554,6 +572,100 @@ where
Ok(())
}
+#[cfg(feature = "v1")]
+async fn persist_connector_mandate_on_payment_method<F>(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payment_data: &PaymentData<F>,
+ connector_mandate_reference_id: &Option<ConnectorMandateReferenceId>,
+) -> RouterResult<()>
+where
+ F: Clone + Send + Sync,
+{
+ if let (
+ Some(payment_method_info),
+ Some(merchant_connector_id),
+ Some(connector_mandate_reference_id),
+ ) = (
+ payment_data.payment_method_info.as_ref(),
+ payment_data.payment_attempt.merchant_connector_id.clone(),
+ connector_mandate_reference_id.clone(),
+ ) {
+ let existing_mandate_details = payment_method_info
+ .get_common_mandate_reference()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse existing payment method mandate details")?;
+
+ let is_active_connector_mandate = existing_mandate_details
+ .payments
+ .as_ref()
+ .and_then(|payments| payments.0.get(&merchant_connector_id))
+ .and_then(|record| record.connector_mandate_status)
+ == Some(common_enums::ConnectorMandateStatus::Active);
+
+ if is_active_connector_mandate {
+ logger::info!(
+ ?merchant_connector_id,
+ "Skipping inactive connector mandate persistence because an active mandate already exists"
+ );
+ } else {
+ let has_connector_mandate_id = connector_mandate_reference_id
+ .get_connector_mandate_id()
+ .is_some();
+ let connector_mandate_status = match (
+ has_connector_mandate_id,
+ payment_data.payment_attempt.status,
+ ) {
+ (
+ true,
+ enums::AttemptStatus::Charged
+ | enums::AttemptStatus::Authorized
+ | enums::AttemptStatus::PartiallyAuthorized
+ | enums::AttemptStatus::PartialCharged
+ | enums::AttemptStatus::PartialChargedAndChargeable,
+ ) => common_enums::ConnectorMandateStatus::Active,
+ _ => common_enums::ConnectorMandateStatus::Inactive,
+ };
+ let authorized_amount = Some(
+ payment_data
+ .payment_attempt
+ .net_amount
+ .get_total_amount()
+ .get_amount_as_i64(),
+ );
+ let authorized_currency = payment_data.payment_attempt.currency;
+
+ let connector_mandate_details = tokenization::update_connector_mandate_details(
+ Some(existing_mandate_details),
+ payment_data.payment_attempt.payment_method_type,
+ authorized_amount,
+ authorized_currency,
+ Some(merchant_connector_id),
+ connector_mandate_reference_id.get_connector_mandate_id(),
+ connector_mandate_reference_id.get_mandate_metadata(),
+ connector_mandate_status,
+ connector_mandate_reference_id.get_connector_mandate_request_reference_id(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to build connector mandate details for payment method")?;
+
+ payment_methods::cards::update_payment_method_connector_mandate_details(
+ platform.get_provider().get_key_store(),
+ &*state.store,
+ payment_method_info.clone(),
+ connector_mandate_details,
+ platform.get_provider().get_account().storage_scheme,
+ platform.get_initiator(),
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method connector mandate details")?;
+ }
+ }
+ Ok(())
+}
+
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(
@@ -726,11 +838,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
&async_dimension,
));
- let is_connector_mandate = resp.request.customer_acceptance.is_some()
- && matches!(
- resp.request.setup_future_usage,
- Some(enums::FutureUsage::OffSession)
- );
+ let is_connector_mandate = resp.request.is_connector_mandate();
let is_legacy_mandate = resp.request.setup_mandate_details.is_some()
&& matches!(
@@ -829,6 +937,17 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
} else {
None
};
+
+ // Persist the connector mandate reference on the payment method so that
+ // subsequent mandate-status webhooks can resolve the payment method.
+ persist_connector_mandate_on_payment_method(
+ state,
+ platform,
+ payment_data,
+ &connector_mandate_reference_id,
+ )
+ .await?;
+
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.connector_mandate_detail =
connector_mandate_reference_id
@@ -2180,6 +2299,18 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
} else {
None
};
+ let is_connector_mandate = resp.request.is_connector_mandate();
+
+ if is_connector_mandate {
+ persist_connector_mandate_on_payment_method(
+ state,
+ platform,
+ payment_data,
+ &connector_mandate_reference_id,
+ )
+ .await?;
+ }
+
let mandate_id = mandate::mandate_procedure(
state,
resp,
@@ -4291,7 +4422,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthor
Some(data) => Some(mandates::MandateIds {
mandate_id: None,
mandate_reference_id: Some(mandates::MandateReferenceId::ConnectorMandateId(
- mandates::ConnectorMandateReferenceId::new(
+ ConnectorMandateReferenceId::new(
mandate_reference_id,
None,
None,
@@ -4844,14 +4975,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRe
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector id")?;
-
let net_amount = payment_data.payment_attempt.amount_details.get_net_amount();
let currency = payment_data.payment_intent.amount_details.currency;
-
+ let connector_token_status =
+ common_enums::ConnectorTokenStatus::from(router_data.status);
let connector_token_details_for_payment_method_update =
api_models::payment_methods::ConnectorTokenDetails {
connector_id,
- status: common_enums::ConnectorTokenStatus::Active,
+ status: connector_token_status,
connector_token_request_reference_id: connector_token
.and_then(|details| details.connector_token_request_reference_id),
original_payment_authorized_amount: Some(net_amount),
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 7e4a076655..d9ed682011 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -24,6 +24,7 @@ use crate::{
types::{
api, domain,
storage::{self, enums},
+ transformers::ForeignFrom,
},
utils::OptionExt,
};
@@ -522,19 +523,37 @@ async fn get_tracker_for_sync<
.await
.transpose()?;
+ let mandate_id = payment_attempt
+ .mandate_id
+ .clone()
+ .map(|id| mandates::MandateIds {
+ mandate_id: Some(id),
+ mandate_reference_id: None,
+ })
+ .or_else(|| {
+ // Some CIT setup flows only have the connector mandate reference at this point.
+ // Preserve it so status responses can still carry mandate details before an
+ // internal mandate_id is available.
+ payment_attempt
+ .connector_mandate_detail
+ .clone()
+ .map(|connector_mandate_detail| mandates::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(mandates::MandateReferenceId::ConnectorMandateId(
+ mandates::ConnectorMandateReferenceId::foreign_from(
+ connector_mandate_detail,
+ ),
+ )),
+ })
+ });
+
let payment_data = PaymentData {
flow: PhantomData,
previous_db_records: (payment_attempt.clone(), payment_intent.clone()),
payment_intent,
currency,
amount,
- mandate_id: payment_attempt
- .mandate_id
- .clone()
- .map(|id| mandates::MandateIds {
- mandate_id: Some(id),
- mandate_reference_id: None,
- }),
+ mandate_id,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 98eb4a7761..c2322d31e8 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1910,6 +1910,7 @@ pub fn update_router_data_with_payment_method_token_result<F: Clone, T>(
}
}
+#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v1")]
pub fn add_connector_mandate_details_in_payment_method(
payment_method_type: Option<storage_enums::PaymentMethodType>,
@@ -1918,6 +1919,7 @@ pub fn add_connector_mandate_details_in_payment_method(
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
mandate_metadata: Option<Secret<serde_json::Value>>,
+ connector_mandate_status: ConnectorMandateStatus,
connector_mandate_request_reference_id: Option<String>,
) -> Option<CommonMandateReference> {
let mut mandate_details = HashMap::new();
@@ -1933,7 +1935,7 @@ pub fn add_connector_mandate_details_in_payment_method(
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata,
- connector_mandate_status: Some(ConnectorMandateStatus::Active),
+ connector_mandate_status: Some(connector_mandate_status),
connector_mandate_request_reference_id,
connector_customer_id: None,
},
@@ -1957,6 +1959,7 @@ pub fn update_connector_mandate_details(
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
mandate_metadata: Option<Secret<serde_json::Value>>,
+ connector_mandate_status: ConnectorMandateStatus,
connector_mandate_request_reference_id: Option<String>,
) -> RouterResult<Option<CommonMandateReference>> {
let mandate_reference = match mandate_details
@@ -1967,28 +1970,33 @@ pub fn update_connector_mandate_details(
if let Some((mca_id, connector_mandate_id)) =
merchant_connector_id.clone().zip(connector_mandate_id)
{
- let updated_record = PaymentsMandateReferenceRecord {
- connector_mandate_id: connector_mandate_id.clone(),
- payment_method_type,
- original_payment_authorized_amount: authorized_amount,
- original_payment_authorized_currency: authorized_currency,
- mandate_metadata: mandate_metadata.clone(),
- connector_mandate_status: Some(ConnectorMandateStatus::Active),
- connector_mandate_request_reference_id: connector_mandate_request_reference_id
- .clone(),
- connector_customer_id: None,
- };
-
payment_mandate_reference
.entry(mca_id)
- .and_modify(|pm| *pm = updated_record)
+ .and_modify(|pm| {
+ pm.connector_mandate_id = connector_mandate_id.clone();
+ pm.payment_method_type = payment_method_type;
+ if authorized_amount.is_some() {
+ pm.original_payment_authorized_amount = authorized_amount;
+ }
+ if authorized_currency.is_some() {
+ pm.original_payment_authorized_currency = authorized_currency;
+ }
+ if mandate_metadata.is_some() {
+ pm.mandate_metadata = mandate_metadata.clone();
+ }
+ pm.connector_mandate_status = Some(connector_mandate_status);
+ if connector_mandate_request_reference_id.is_some() {
+ pm.connector_mandate_request_reference_id =
+ connector_mandate_request_reference_id.clone();
+ }
+ })
.or_insert(PaymentsMandateReferenceRecord {
connector_mandate_id,
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata: mandate_metadata.clone(),
- connector_mandate_status: Some(ConnectorMandateStatus::Active),
+ connector_mandate_status: Some(connector_mandate_status),
connector_mandate_request_reference_id,
connector_customer_id: None,
});
@@ -2010,6 +2018,7 @@ pub fn update_connector_mandate_details(
merchant_connector_id,
connector_mandate_id,
mandate_metadata,
+ connector_mandate_status,
connector_mandate_request_reference_id,
),
};
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 8c980a6f6c..3e20c1663e 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -6,6 +6,7 @@ use api_models::{
enums::Connector,
webhooks::{self, WebhookResponseTracker},
};
+use common_enums::enums::ConnectorMandateStatus;
pub use common_enums::{connector_enums::InvoiceStatus, enums::ProcessTrackerRunner};
use common_utils::{
errors::ReportSwitchExt,
@@ -657,6 +658,7 @@ async fn process_webhook_business_logic(
webhook_details,
source_verified,
event_type,
+ merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for mandates failed"),
@@ -985,6 +987,7 @@ async fn payments_incoming_webhook_flow(
&state,
&platform,
webhook_details.object_reference_id.clone(),
+ event_type,
connector,
request_details,
)
@@ -2309,90 +2312,315 @@ async fn mandates_incoming_webhook_flow(
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
+ merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
- if source_verified {
- let db = &*state.store;
- let mandate = match webhook_details.object_reference_id {
- webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId(
- mandate_id,
- )) => db
- .find_mandate_by_merchant_id_mandate_id(
- platform.get_processor().get_account().get_id(),
- mandate_id.as_str(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
- webhooks::ObjectReferenceId::MandateId(
- webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id),
- ) => db
- .find_mandate_by_merchant_id_connector_mandate_id(
- platform.get_processor().get_account().get_id(),
- connector_mandate_id.as_str(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
- _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("received a non-mandate id for retrieving mandate")?,
- };
- let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type)
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("event type to mandate status mapping failed")?;
- let mandate_id = mandate.mandate_id.clone();
- let updated_mandate = db
- .update_mandate_by_merchant_id_mandate_id(
- platform.get_processor().get_account().get_id(),
- &mandate_id,
- storage::MandateUpdate::StatusUpdate { mandate_status },
- mandate,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
- let mandates_response = Box::new(
- api::mandates::MandateResponse::from_db_mandate(
- &state,
- platform.get_processor().get_key_store().clone(),
- updated_mandate.clone(),
- platform.get_processor().get_account(),
- )
- .await?,
- );
- let event_type: Option<enums::EventType> = updated_mandate.mandate_status.into();
- if let Some(outgoing_event_type) = event_type {
- let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
- &state,
- &platform,
- &business_profile,
- None, // Mandates do not carry created_by, default to processor
- )
- .await?;
- Box::pin(super::create_event_and_trigger_outgoing_webhook(
- state,
- platform,
- outgoing_event_type,
- enums::EventClass::Mandates,
- updated_mandate.mandate_id.clone(),
- enums::EventObjectType::MandateDetails,
- api::OutgoingWebhookContent::MandateDetails(mandates_response),
- Some(updated_mandate.created_at),
- webhook_recipient,
- None,
- business_profile,
- ))
- .await?;
+ match event_type {
+ webhooks::IncomingWebhookEvent::MandateActionRequired => {
+ Ok(WebhookResponseTracker::NoEffect)
}
- Ok(WebhookResponseTracker::Mandate {
- mandate_id: updated_mandate.mandate_id,
- status: updated_mandate.mandate_status,
- })
- } else {
- logger::error!("Webhook source verification failed for mandates webhook flow");
- Err(report!(
+ _ if source_verified => {
+ let db = &*state.store;
+
+ match webhook_details.object_reference_id {
+ webhooks::ObjectReferenceId::MandateId(mandate_id_type) => {
+ let mandate = match mandate_id_type {
+ webhooks::MandateIdType::MandateId(mandate_id) => db
+ .find_mandate_by_merchant_id_mandate_id(
+ platform.get_processor().get_account().get_id(),
+ mandate_id.as_str(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
+ webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db
+ .find_mandate_by_merchant_id_connector_mandate_id(
+ platform.get_processor().get_account().get_id(),
+ connector_mandate_id.as_str(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
+ };
+
+ update_existing_mandate(state, platform, business_profile, mandate, event_type)
+ .await
+ }
+ webhooks::ObjectReferenceId::PaymentId(
+ api::payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id),
+ ) => {
+ Box::pin(update_connector_managed_mandate_by_connector_txn_id(
+ state,
+ platform,
+ business_profile,
+ merchant_connector_account,
+ connector_transaction_id,
+ event_type,
+ ))
+ .await
+ }
+ _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("received a non-mandate id for retrieving mandate"),
+ }
+ }
+ _ => Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
+ )),
+ }
+}
+
+#[instrument(skip_all)]
+async fn update_connector_managed_mandate_by_connector_txn_id(
+ state: SessionState,
+ platform: domain::Platform,
+ business_profile: domain::Profile,
+ merchant_connector_account: domain::MerchantConnectorAccount,
+ connector_transaction_id: String,
+ event_type: webhooks::IncomingWebhookEvent,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let merchant_id = platform.get_processor().get_account().get_id();
+ let storage_scheme = platform.get_processor().get_account().storage_scheme;
+
+ let setup_attempt = db
+ .find_payment_attempt_by_processor_merchant_id_connector_txn_id(
+ merchant_id,
+ connector_transaction_id.as_str(),
+ storage_scheme,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let payment_method_id = setup_attempt
+ .payment_method_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("payment method id not found for connector managed mandate webhook")?;
+
+ let payment_method = db
+ .find_payment_method(
+ platform.get_provider().get_key_store(),
+ payment_method_id.as_str(),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ update_payment_method_mandate_status(
+ &state,
+ &platform,
+ &business_profile,
+ payment_method,
+ &merchant_connector_account.get_id(),
+ event_type,
+ )
+ .await
+}
+
+#[instrument(skip_all)]
+async fn update_existing_mandate(
+ state: SessionState,
+ platform: domain::Platform,
+ business_profile: domain::Profile,
+ mandate: storage::Mandate,
+ event_type: webhooks::IncomingWebhookEvent,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type)
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("event type to mandate status mapping failed")?;
+ let mandate_id = mandate.mandate_id.clone();
+ let updated_mandate = db
+ .update_mandate_by_merchant_id_mandate_id(
+ platform.get_processor().get_account().get_id(),
+ &mandate_id,
+ storage::MandateUpdate::StatusUpdate { mandate_status },
+ mandate,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
+ let mandates_response = Box::new(
+ api::mandates::MandateResponse::from_db_mandate(
+ &state,
+ platform.get_processor().get_key_store().clone(),
+ updated_mandate.clone(),
+ platform.get_processor().get_account(),
+ )
+ .await?,
+ );
+ let event_type: Option<enums::EventType> = updated_mandate.mandate_status.into();
+ if let Some(outgoing_event_type) = event_type {
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ &state,
+ &platform,
+ &business_profile,
+ None, // Mandates do not carry created_by, default to processor
+ )
+ .await?;
+ Box::pin(super::create_event_and_trigger_outgoing_webhook(
+ state,
+ platform,
+ outgoing_event_type,
+ enums::EventClass::Mandates,
+ updated_mandate.mandate_id.clone(),
+ enums::EventObjectType::MandateDetails,
+ api::OutgoingWebhookContent::MandateDetails(mandates_response),
+ Some(updated_mandate.created_at),
+ webhook_recipient,
+ None,
+ business_profile,
+ ))
+ .await?;
+ }
+ Ok(WebhookResponseTracker::Mandate {
+ mandate_id: updated_mandate.mandate_id,
+ status: updated_mandate.mandate_status,
+ })
+}
+
+#[instrument(skip_all)]
+async fn update_payment_method_mandate_status(
+ state: &SessionState,
+ platform: &domain::Platform,
+ business_profile: &domain::Profile,
+ payment_method: domain::PaymentMethod,
+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
+ event_type: webhooks::IncomingWebhookEvent,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ let db = &*state.store;
+
+ let common_mandate_reference = payment_method
+ .get_common_mandate_reference()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse payment method mandate details")?;
+ let payment_method_id = payment_method.get_id().clone();
+ let payment_method_name = payment_method
+ .get_payment_method_type()
+ .map(|payment_method| payment_method.to_string())
+ .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("payment method type not found for mandate webhook")?;
+ let payment_method_type = payment_method
+ .get_payment_method_subtype()
+ .map(|payment_method_type| payment_method_type.to_string());
+ let created_at = payment_method.created_at;
+ let created_by = payment_method.created_by.clone();
+
+ let (connector_mandate_status, mandate_status, payment_method_status, tracker_status) =
+ match event_type {
+ webhooks::IncomingWebhookEvent::MandateActive => Ok((
+ ConnectorMandateStatus::Active,
+ common_enums::MandateStatus::Active,
+ Some(enums::PaymentMethodStatus::Active),
+ enums::PaymentMethodStatus::Active,
+ )),
+ webhooks::IncomingWebhookEvent::MandateRevoked => Ok((
+ ConnectorMandateStatus::Inactive,
+ common_enums::MandateStatus::Revoked,
+ None,
+ enums::PaymentMethodStatus::Inactive,
+ )),
+ _ => Err(report!(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("received a non-mandate status event")),
+ }?;
+
+ let payment_mandate_reference = common_mandate_reference
+ .payments
+ .clone()
+ .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("no payment mandate reference found for payment method")?;
+
+ let updated_mandate_details = tokenization::update_connector_mandate_details_status(
+ merchant_connector_id.clone(),
+ payment_mandate_reference,
+ connector_mandate_status,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update connector mandate details status")?;
+
+ let updated_mandate_details = updated_mandate_details
+ .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("no updated mandate details for payment method")?;
+ let connector_mandate_id = updated_mandate_details
+ .payments
+ .as_ref()
+ .and_then(|payments| payments.get(merchant_connector_id))
+ .map(|mandate_record| mandate_record.connector_mandate_id.clone())
+ .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("connector mandate id not found for payment method mandate webhook")?;
+ let connector_mandate_details_value = updated_mandate_details
+ .get_mandate_details_value()
+ .map_err(|err| {
+ router_env::logger::error!("Failed to get get_mandate_details_value : {:?}", err);
+ errors::ApiErrorResponse::MandateUpdateFailed
+ })?;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodBatchUpdate {
+ connector_mandate_details: Some(Secret::new(connector_mandate_details_value)),
+ network_transaction_id: None,
+ network_transaction_link_id: None,
+ status: payment_method_status,
+ payment_method_data: None,
+ payment_method_type: None,
+ scheme: None,
+ last_modified_by: platform
+ .get_initiator()
+ .and_then(|initiator| initiator.to_created_by())
+ .map(|last_modified_by| last_modified_by.to_string()),
+ };
+
+ db.update_payment_method(
+ platform.get_provider().get_key_store(),
+ payment_method.clone(),
+ pm_update,
+ platform.get_provider().get_account().storage_scheme,
+ None,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let outgoing_event_type: Option<enums::EventType> = mandate_status.into();
+ if let Some(outgoing_event_type) = outgoing_event_type {
+ let webhook_recipient = utils::resolve_webhook_recipient_from_created_by(
+ state,
+ platform,
+ business_profile,
+ created_by.as_ref(),
+ )
+ .await?;
+ let mandate_response = api::mandates::MandateResponse {
+ mandate_id: connector_mandate_id.clone(),
+ status: mandate_status,
+ payment_method_id: payment_method_id.to_string(),
+ payment_method: payment_method_name,
+ payment_method_type,
+ card: None,
+ customer_acceptance: None,
+ };
+
+ // PM-backed mandates do not have a entry in mandate table. Use the
+ // connector mandate id as the outgoing mandate resource id so revocation
+ // webhooks are about the mandate, not one arbitrary CIT/MIT payment.
+ Box::pin(super::create_event_and_trigger_outgoing_webhook(
+ state.clone(),
+ platform.clone(),
+ outgoing_event_type,
+ enums::EventClass::Mandates,
+ connector_mandate_id,
+ enums::EventObjectType::MandateDetails,
+ api::OutgoingWebhookContent::MandateDetails(Box::new(mandate_response)),
+ Some(created_at),
+ webhook_recipient,
+ None,
+ business_profile.clone(),
))
+ .await?;
}
+
+ Ok(WebhookResponseTracker::PaymentMethod {
+ payment_method_id,
+ status: tracker_status,
+ })
}
#[instrument(skip_all)]
@@ -3322,7 +3550,14 @@ fn should_update_connector_mandate_details(
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> bool {
- source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess
+ source_verified
+ && matches!(
+ event_type,
+ webhooks::IncomingWebhookEvent::PaymentIntentSuccess
+ | webhooks::IncomingWebhookEvent::PaymentIntentFailure
+ | webhooks::IncomingWebhookEvent::MandateActive
+ | webhooks::IncomingWebhookEvent::MandateRevoked
+ )
}
async fn update_additional_payment_method_data(
@@ -3371,6 +3606,7 @@ async fn update_connector_mandate_details(
state: &SessionState,
platform: &domain::Platform,
object_ref_id: api::ObjectReferenceId,
+ event_type: webhooks::IncomingWebhookEvent,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<(), errors::ApiErrorResponse> {
@@ -3386,9 +3622,17 @@ async fn update_connector_mandate_details(
"Could not find connector network transaction id in incoming webhook body",
)?;
- // Either one OR both of the fields are present
+ let webhook_mandate_details_update = connector
+ .get_webhook_mandate_details_update(request_details)
+ .switch()
+ .attach_printable(
+ "Could not find connector mandate details update in incoming webhook body",
+ )?;
+
+ // Either one OR more of these fields are present.
if webhook_connector_mandate_details.is_some()
|| webhook_connector_network_transaction_id.is_some()
+ || webhook_mandate_details_update.is_some()
{
let payment_attempt = get_payment_attempt_from_object_reference_id(
state,
@@ -3407,19 +3651,19 @@ async fn update_connector_mandate_details(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- // Update connector's mandate details
- let updated_connector_mandate_details =
- if let Some(webhook_mandate_details) = webhook_connector_mandate_details {
- let mandate_details = payment_method_info
- .get_common_mandate_reference()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize to Payment Mandate Reference")?;
-
- let merchant_connector_account_id = payment_attempt
- .merchant_connector_id
- .clone()
- .get_required_value("merchant_connector_id")?;
+ let mandate_details = payment_method_info
+ .get_common_mandate_reference()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference")?;
+ let merchant_connector_account_id = payment_attempt
+ .merchant_connector_id
+ .clone()
+ .get_required_value("merchant_connector_id")?;
+
+ // Update connector's mandate details
+ let mut updated_connector_mandate_details =
+ if let Some(webhook_mandate_details) = webhook_connector_mandate_details.as_ref() {
if mandate_details.payments.as_ref().is_none_or(|payments| {
!payments.0.contains_key(&merchant_connector_account_id)
}) {
@@ -3472,8 +3716,9 @@ async fn update_connector_mandate_details(
insert_mandate_details(
&payment_attempt,
- &webhook_mandate_details,
- Some(mandate_details),
+ webhook_mandate_details,
+ Some(mandate_details.clone()),
+ event_type,
)?
} else {
logger::info!(
@@ -3485,6 +3730,97 @@ async fn update_connector_mandate_details(
None
};
+ if let Some(mandate_details_update) = webhook_mandate_details_update {
+ let mandate_details = updated_connector_mandate_details
+ .clone()
+ .or_else(|| Some(mandate_details.clone()));
+
+ let existing_connector_mandate_record = mandate_details
+ .as_ref()
+ .and_then(|common_mandate| common_mandate.payments.as_ref())
+ .and_then(|payments| payments.0.get(&merchant_connector_account_id));
+
+ let connector_mandate_id = webhook_connector_mandate_details
+ .as_ref()
+ .map(|details| details.connector_mandate_id.peek().to_string())
+ .or_else(|| {
+ existing_connector_mandate_record
+ .map(|record| record.connector_mandate_id.clone())
+ })
+ .or_else(|| {
+ payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .and_then(|details| details.connector_mandate_id.clone())
+ });
+
+ let connector_mandate_status = mandate_details_update
+ .connector_mandate_status
+ .or_else(|| {
+ existing_connector_mandate_record
+ .and_then(|record| record.connector_mandate_status)
+ })
+ .unwrap_or(ConnectorMandateStatus::Inactive);
+
+ updated_connector_mandate_details = tokenization::update_connector_mandate_details(
+ mandate_details,
+ payment_attempt.payment_method_type,
+ mandate_details_update
+ .original_payment_authorized_amount
+ .map(|amount| amount.get_amount_as_i64()),
+ mandate_details_update.original_payment_authorized_currency,
+ Some(merchant_connector_account_id.clone()),
+ connector_mandate_id.clone(),
+ None,
+ connector_mandate_status,
+ None,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update connector mandate details from webhook")?;
+
+ if connector_mandate_id.is_some()
+ && payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .is_none_or(|details| details.connector_mandate_id.is_none())
+ {
+ let attempt_update =
+ storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
+ connector_mandate_detail: Some(ConnectorMandateReferenceId {
+ connector_mandate_id,
+ payment_method_id: Some(payment_method_id.to_string()),
+ mandate_metadata: payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .and_then(|details| details.mandate_metadata.clone()),
+ connector_mandate_request_reference_id: payment_attempt
+ .connector_mandate_detail
+ .as_ref()
+ .and_then(|details| {
+ details.connector_mandate_request_reference_id.clone()
+ }),
+ }),
+ tokenization: None,
+ updated_by: platform
+ .get_processor()
+ .get_account()
+ .storage_scheme
+ .to_string(),
+ };
+
+ state
+ .store
+ .update_payment_attempt_with_attempt_id(
+ payment_attempt.clone(),
+ attempt_update,
+ platform.get_processor().get_account().storage_scheme,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ }
+ }
+
let connector_mandate_details_value = updated_connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
@@ -3532,6 +3868,7 @@ fn insert_mandate_details(
payment_attempt: &PaymentAttempt,
webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails,
payment_method_mandate_details: Option<CommonMandateReference>,
+ event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> {
let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt
.connector_mandate_detail
@@ -3543,6 +3880,24 @@ fn insert_mandate_details(
)
})
.unwrap_or((None, None));
+ let connector_mandate_id = webhook_mandate_details
+ .connector_mandate_id
+ .peek()
+ .to_string();
+ let existing_connector_mandate_status = payment_attempt
+ .merchant_connector_id
+ .as_ref()
+ .and_then(|mca_id| {
+ payment_method_mandate_details
+ .as_ref()
+ .and_then(|mandate_details| mandate_details.payments.as_ref())
+ .and_then(|payments| payments.0.get(mca_id))
+ })
+ .and_then(|record| record.connector_mandate_status);
+ let connector_mandate_status = match event_type {
+ webhooks::IncomingWebhookEvent::MandateActive => ConnectorMandateStatus::Active,
+ _ => existing_connector_mandate_status.unwrap_or(ConnectorMandateStatus::Inactive),
+ };
let connector_mandate_details = tokenization::update_connector_mandate_details(
payment_method_mandate_details,
payment_attempt.payment_method_type,
@@ -3554,13 +3909,9 @@ fn insert_mandate_details(
),
payment_attempt.currency,
payment_attempt.merchant_connector_id.clone(),
- Some(
- webhook_mandate_details
- .connector_mandate_id
- .peek()
- .to_string(),
- ),
+ Some(connector_mandate_id),
mandate_metadata,
+ connector_mandate_status,
connector_mandate_request_reference_id,
)?;
Ok(connector_mandate_details)
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index 33ac3733b3..a62f760782 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -1584,6 +1584,7 @@ impl RecoveryAction {
| webhooks::IncomingWebhookEvent::DisputeLost
| webhooks::IncomingWebhookEvent::MandateActive
| webhooks::IncomingWebhookEvent::MandateRevoked
+ | webhooks::IncomingWebhookEvent::MandateActionRequired
| webhooks::IncomingWebhookEvent::EndpointVerification
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure