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(connector): [SANTANDER] Implement CIT, CIT PSync, MIT & MIT Psync for Pix Automatico (#11589)

Sayak Bhattacharyab1ce9378911a
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml
index 9941dd52c9..af061c559d 100644
--- a/.github/workflows/CI-pr.yml
+++ b/.github/workflows/CI-pr.yml
@@ -200,7 +200,7 @@ jobs:
- name: Run clippy
shell: bash
- run: just clippy
+ run: just clippy --jobs 3
- name: Check Cargo.lock changed
if: ${{ (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name) }}
diff --git a/.github/workflows/CI-push.yml b/.github/workflows/CI-push.yml
index e166435846..2d3543774e 100644
--- a/.github/workflows/CI-push.yml
+++ b/.github/workflows/CI-push.yml
@@ -220,7 +220,7 @@ jobs:
- name: Run clippy
shell: bash
- run: just clippy
+ run: just clippy --jobs 3
- name: Cargo hack
if: ${{ github.event_name == 'push' }}
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index ef2d4849fa..988615d84c 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -8520,6 +8520,15 @@
"write_off"
]
},
+ "AccountType": {
+ "type": "string",
+ "description": "Account type for Santander Pix Automatico recurring charges",
+ "enum": [
+ "current",
+ "savings",
+ "payment"
+ ]
+ },
"AchBankDebitAdditionalData": {
"type": "object",
"required": [
@@ -35488,6 +35497,58 @@
"propertyName": "type"
}
},
+ "PixAutomaticoCitData": {
+ "type": "object",
+ "description": "Data for Santander Pix Automatico CIT (Customer Initiated Transaction) - used during mandate setup",
+ "properties": {
+ "contract_id": {
+ "type": "string",
+ "description": "Contract ID to identify the recurring payment contract",
+ "example": "pm_16503867",
+ "nullable": true
+ },
+ "retry_policy": {
+ "type": "boolean",
+ "description": "Enable retry policy for failed payments (maps to PERMITE_3R_7D if true)",
+ "example": true,
+ "nullable": true
+ },
+ "mandate_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderMandateDetails"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "PixAutomaticoMitData": {
+ "type": "object",
+ "description": "Data for Santander Pix Automatico MIT (Merchant Initiated Transaction) - used during recurring charge creation",
+ "properties": {
+ "receiver_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderPixAutomaticoReceiverDetails"
+ }
+ ],
+ "nullable": true
+ },
+ "exec_date": {
+ "type": "string",
+ "description": "Execution date for the mandate charge (maps to data_de_vencimento). Format: YYYY-MM-DD.\nIf not provided, defaults to current date + 1 day.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "auto_adjust_date": {
+ "type": "boolean",
+ "description": "Whether to automatically adjust the due date to the next business day if it falls on a non-business day.\nMaps to ajuste_dia_util in Santander API. Defaults to true if not provided.",
+ "example": true,
+ "nullable": true
+ }
+ }
+ },
"PixAutomaticoPushAdditionalData": {
"type": "object",
"properties": {
@@ -39122,6 +39183,14 @@
}
],
"nullable": true
+ },
+ "pix_automatico": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderPixAutomaticoData"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -39135,6 +39204,47 @@
},
"additionalProperties": false
},
+ "SantanderMandateDetails": {
+ "type": "object",
+ "properties": {
+ "amount": {
+ "type": "string",
+ "description": "Maximum amount for each recurring charge",
+ "example": "5.00",
+ "nullable": true
+ },
+ "start_date": {
+ "type": "string",
+ "description": "Start date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid immediately.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "end_date": {
+ "type": "string",
+ "description": "End date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid indefinitely.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "periodicity": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderMandatePeriodicity"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "SantanderMandatePeriodicity": {
+ "type": "string",
+ "enum": [
+ "weekly",
+ "monthly",
+ "quarterly",
+ "semiannually",
+ "annually"
+ ]
+ },
"SantanderPaymentDiscountRules": {
"type": "object",
"description": "Defines the type of discount applied to a payment, such as whether it's a fixed date discount, a daily calendar discount, or a daily business discount.",
@@ -39159,6 +39269,59 @@
}
}
},
+ "SantanderPixAutomaticoData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "cit"
+ ],
+ "properties": {
+ "cit": {
+ "$ref": "#/components/schemas/PixAutomaticoCitData"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "mit"
+ ],
+ "properties": {
+ "mit": {
+ "$ref": "#/components/schemas/PixAutomaticoMitData"
+ }
+ }
+ }
+ ],
+ "description": "Represents the specific data for Santander Pix Automatico (recurring PIX payments)\nSplit into CIT (Customer Initiated Transaction) and MIT (Merchant Initiated Transaction) variants"
+ },
+ "SantanderPixAutomaticoReceiverDetails": {
+ "type": "object",
+ "description": "Represents the receiver details for Santander Pix Automatico recurring charges",
+ "properties": {
+ "branch_code": {
+ "type": "string",
+ "description": "Branch code (agencia) of the receiver's bank account",
+ "example": "0001",
+ "nullable": true
+ },
+ "account_number": {
+ "type": "string",
+ "description": "Account number (conta) of the receiver",
+ "example": "130333323",
+ "nullable": true
+ },
+ "account_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AccountType"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"ScaExemptionType": {
"type": "string",
"description": "SCA Exemptions types available for authentication",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 5d6d5fdd1c..5a5c1eca00 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -5191,6 +5191,15 @@
"propertyName": "type"
}
},
+ "AccountType": {
+ "type": "string",
+ "description": "Account type for Santander Pix Automatico recurring charges",
+ "enum": [
+ "current",
+ "savings",
+ "payment"
+ ]
+ },
"AchBankDebitAdditionalData": {
"type": "object",
"required": [
@@ -25700,6 +25709,58 @@
"propertyName": "type"
}
},
+ "PixAutomaticoCitData": {
+ "type": "object",
+ "description": "Data for Santander Pix Automatico CIT (Customer Initiated Transaction) - used during mandate setup",
+ "properties": {
+ "contract_id": {
+ "type": "string",
+ "description": "Contract ID to identify the recurring payment contract",
+ "example": "pm_16503867",
+ "nullable": true
+ },
+ "retry_policy": {
+ "type": "boolean",
+ "description": "Enable retry policy for failed payments (maps to PERMITE_3R_7D if true)",
+ "example": true,
+ "nullable": true
+ },
+ "mandate_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderMandateDetails"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "PixAutomaticoMitData": {
+ "type": "object",
+ "description": "Data for Santander Pix Automatico MIT (Merchant Initiated Transaction) - used during recurring charge creation",
+ "properties": {
+ "receiver_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderPixAutomaticoReceiverDetails"
+ }
+ ],
+ "nullable": true
+ },
+ "exec_date": {
+ "type": "string",
+ "description": "Execution date for the mandate charge (maps to data_de_vencimento). Format: YYYY-MM-DD.\nIf not provided, defaults to current date + 1 day.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "auto_adjust_date": {
+ "type": "boolean",
+ "description": "Whether to automatically adjust the due date to the next business day if it falls on a non-business day.\nMaps to ajuste_dia_util in Santander API. Defaults to true if not provided.",
+ "example": true,
+ "nullable": true
+ }
+ }
+ },
"PixAutomaticoPushAdditionalData": {
"type": "object",
"properties": {
@@ -28754,6 +28815,14 @@
}
],
"nullable": true
+ },
+ "pix_automatico": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderPixAutomaticoData"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -28767,6 +28836,47 @@
},
"additionalProperties": false
},
+ "SantanderMandateDetails": {
+ "type": "object",
+ "properties": {
+ "amount": {
+ "type": "string",
+ "description": "Maximum amount for each recurring charge",
+ "example": "5.00",
+ "nullable": true
+ },
+ "start_date": {
+ "type": "string",
+ "description": "Start date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid immediately.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "end_date": {
+ "type": "string",
+ "description": "End date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid indefinitely.",
+ "example": "2026-12-31",
+ "nullable": true
+ },
+ "periodicity": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SantanderMandatePeriodicity"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "SantanderMandatePeriodicity": {
+ "type": "string",
+ "enum": [
+ "weekly",
+ "monthly",
+ "quarterly",
+ "semiannually",
+ "annually"
+ ]
+ },
"SantanderPaymentDiscountRules": {
"type": "object",
"description": "Defines the type of discount applied to a payment, such as whether it's a fixed date discount, a daily calendar discount, or a daily business discount.",
@@ -28791,6 +28901,59 @@
}
}
},
+ "SantanderPixAutomaticoData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "cit"
+ ],
+ "properties": {
+ "cit": {
+ "$ref": "#/components/schemas/PixAutomaticoCitData"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "mit"
+ ],
+ "properties": {
+ "mit": {
+ "$ref": "#/components/schemas/PixAutomaticoMitData"
+ }
+ }
+ }
+ ],
+ "description": "Represents the specific data for Santander Pix Automatico (recurring PIX payments)\nSplit into CIT (Customer Initiated Transaction) and MIT (Merchant Initiated Transaction) variants"
+ },
+ "SantanderPixAutomaticoReceiverDetails": {
+ "type": "object",
+ "description": "Represents the receiver details for Santander Pix Automatico recurring charges",
+ "properties": {
+ "branch_code": {
+ "type": "string",
+ "description": "Branch code (agencia) of the receiver's bank account",
+ "example": "0001",
+ "nullable": true
+ },
+ "account_number": {
+ "type": "string",
+ "description": "Account number (conta) of the receiver",
+ "example": "130333323",
+ "nullable": true
+ },
+ "account_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AccountType"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"ScaExemptionType": {
"type": "string",
"description": "SCA Exemptions types available for authentication",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 4cd17d9b0c..77a995c6e6 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -11476,6 +11476,20 @@ impl FeatureMetadata {
(pix_key, value)
}
+ /// Checks if this is a Pix Automatico Journey 3 (Immediate expiration variant)
+ pub fn is_pix_immediate(&self) -> bool {
+ self.pix_additional_details
+ .as_ref()
+ .map(|details| matches!(details, PixAdditionalDetails::Immediate(_)))
+ .unwrap_or(false)
+ }
+ /// Checks if this is a Pix Automatico Journey 4 (Scheduled expiration variant)
+ pub fn is_pix_scheduled(&self) -> bool {
+ self.pix_additional_details
+ .as_ref()
+ .map(|details| matches!(details, PixAdditionalDetails::Scheduled(_)))
+ .unwrap_or(false)
+ }
}
/// additional data that might be required by hyperswitch
@@ -11571,6 +11585,20 @@ impl FeatureMetadata {
(pix_key, value)
}
+ /// Checks if this is a Pix Automatico Journey 3 (Immediate expiration variant)
+ pub fn is_pix_immediate(&self) -> bool {
+ self.pix_additional_details
+ .as_ref()
+ .map(|details| matches!(details, PixAdditionalDetails::Immediate(_)))
+ .unwrap_or(false)
+ }
+ /// Checks if this is a Pix Automatico Journey 4 (Scheduled expiration variant)
+ pub fn is_pix_scheduled(&self) -> bool {
+ self.pix_additional_details
+ .as_ref()
+ .map(|details| matches!(details, PixAdditionalDetails::Scheduled(_)))
+ .unwrap_or(false)
+ }
}
#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]
@@ -13223,6 +13251,9 @@ pub struct SantanderConnectorMetadataData {
/// Boleto-specific data and rules for Santander payments
#[smithy(value_type = "Option<SantanderBoletoData>")]
pub boleto: Option<SantanderBoletoData>,
+ /// Pix Automatico-specific data for Santander recurring payments
+ #[smithy(value_type = "Option<SantanderPixAutomaticoData>")]
+ pub pix_automatico: Option<SantanderPixAutomaticoData>,
}
/// Represents the specific data and rules related to Santander Boleto payments, including discounts, penalties, collection actions, payment constraints, beneficiary details, and document kind.
@@ -13253,6 +13284,127 @@ pub struct SantanderBoletoData {
pub document_kind: Option<common_enums::BoletoDocumentKind>,
}
+/// Account type for Santander Pix Automatico recurring charges
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[serde(rename_all = "snake_case")]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub enum AccountType {
+ /// Checking account (Conta Corrente)
+ Current,
+ /// Savings account (Conta Poupança)
+ Savings,
+ /// Payment account (Conta Pagamento)
+ Payment,
+}
+
+/// Represents the receiver details for Santander Pix Automatico recurring charges
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub struct SantanderPixAutomaticoReceiverDetails {
+ /// Branch code (agencia) of the receiver's bank account
+ #[smithy(value_type = "Option<String>")]
+ #[schema(value_type = Option<String>, example = "0001")]
+ pub branch_code: Option<Secret<String>>,
+ /// Account number (conta) of the receiver
+ #[smithy(value_type = "Option<String>")]
+ #[schema(value_type = Option<String>, example = "130333323")]
+ pub account_number: Option<Secret<String>>,
+ /// Account type (tipoConta) - CORRENTE, POUPANCA, or PAGAMENTO
+ #[smithy(value_type = "Option<AccountType>")]
+ #[schema(value_type = Option<AccountType>)]
+ pub account_type: Option<AccountType>,
+}
+
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub struct SantanderMandateDetails {
+ /// Maximum amount for each recurring charge
+ #[schema(value_type = Option<String>, example = "5.00")]
+ #[smithy(value_type = "Option<String>")]
+ pub amount: Option<StringMajorUnit>,
+ /// Start date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid immediately.
+ #[schema(value_type = Option<String>, example="2026-12-31")]
+ #[serde(default, with = "common_utils::custom_serde::date_only_optional")]
+ pub start_date: Option<PrimitiveDateTime>,
+ /// End date for the recurring charges. Format: YYYY-MM-DD. If not provided, the mandate will be valid indefinitely.
+ #[schema(value_type = Option<String>, example="2026-12-31")]
+ #[serde(default, with = "common_utils::custom_serde::date_only_optional")]
+ pub end_date: Option<PrimitiveDateTime>,
+ /// Frequency of the recurring charges (e.g., weekly, monthly). If not provided, defaults to monthly.
+ #[schema(value_type = Option<SantanderMandatePeriodicity>, example = "weekly")]
+ #[smithy(value_type = "Option<SantanderMandatePeriodicity>")]
+ pub periodicity: Option<SantanderMandatePeriodicity>,
+}
+
+#[derive(
+ Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel,
+)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+#[serde(rename_all = "snake_case")]
+pub enum SantanderMandatePeriodicity {
+ /// Every week
+ Weekly,
+ /// Every month
+ #[default]
+ Monthly,
+ /// Every 3 months
+ Quarterly,
+ /// Every 6 months
+ Semiannually,
+ /// Every year
+ Annually,
+}
+
+/// Represents the specific data for Santander Pix Automatico (recurring PIX payments)
+/// Split into CIT (Customer Initiated Transaction) and MIT (Merchant Initiated Transaction) variants
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+#[serde(rename_all = "snake_case")]
+pub enum SantanderPixAutomaticoData {
+ /// Customer Initiated Transaction - used during mandate setup
+ Cit(PixAutomaticoCitData),
+ /// Merchant Initiated Transaction - used during recurring charge creation
+ Mit(PixAutomaticoMitData),
+}
+
+/// Data for Santander Pix Automatico CIT (Customer Initiated Transaction) - used during mandate setup
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub struct PixAutomaticoCitData {
+ /// Contract ID to identify the recurring payment contract
+ #[smithy(value_type = "Option<String>")]
+ #[schema(value_type = Option<String>, example = "pm_16503867")]
+ pub contract_id: Option<String>,
+ /// Enable retry policy for failed payments (maps to PERMITE_3R_7D if true)
+ #[smithy(value_type = "Option<bool>")]
+ #[schema(value_type = Option<bool>, example = true)]
+ pub retry_policy: Option<bool>,
+ /// Mandate details for the recurring charge
+ #[smithy(value_type = "Option<SantanderMandateDetails>")]
+ #[schema(value_type = Option<SantanderMandateDetails>)]
+ pub mandate_details: Option<SantanderMandateDetails>,
+}
+
+/// Data for Santander Pix Automatico MIT (Merchant Initiated Transaction) - used during recurring charge creation
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
+#[smithy(namespace = "com.hyperswitch.smithy.types")]
+pub struct PixAutomaticoMitData {
+ /// Receiver details for the recurring charge
+ #[smithy(value_type = "Option<SantanderPixAutomaticoReceiverDetails>")]
+ #[schema(value_type = Option<SantanderPixAutomaticoReceiverDetails>)]
+ pub receiver_details: Option<SantanderPixAutomaticoReceiverDetails>,
+ /// Execution date for the mandate charge (maps to data_de_vencimento). Format: YYYY-MM-DD.
+ /// If not provided, defaults to current date + 1 day.
+ #[schema(value_type = Option<String>, example = "2026-12-31")]
+ #[serde(default, with = "common_utils::custom_serde::date_only_optional")]
+ pub exec_date: Option<PrimitiveDateTime>,
+ /// Whether to automatically adjust the due date to the next business day if it falls on a non-business day.
+ /// Maps to ajuste_dia_util in Santander API. Defaults to true if not provided.
+ #[smithy(value_type = "Option<bool>")]
+ #[schema(value_type = Option<bool>, example = true)]
+ pub auto_adjust_date: Option<bool>,
+}
+
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
/// Represents the end-recipient of a payout or fund transfer.
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs
index 105d9c1fe2..8db1aac504 100644
--- a/crates/hyperswitch_connectors/src/connectors/adyen.rs
+++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs
@@ -3455,6 +3455,7 @@ impl ConnectorSpecifications for Adyen {
api::CurrentFlowInfo::CompleteAuthorize { request_data, .. } => {
matches!(&request_data.payment_method_data, Some(payment_method_data::PaymentMethodData::GiftCard(giftcard_data)) if giftcard_data.is_givex())
}
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
index 4c5c0cbe7b..c0328efdb7 100644
--- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs
@@ -1646,6 +1646,7 @@ impl ConnectorSpecifications for Barclaycard {
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
/// Check if authentication flow is required
@@ -1671,6 +1672,7 @@ impl ConnectorSpecifications for Barclaycard {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
/// Check if post-authentication flow is required
@@ -1696,6 +1698,7 @@ impl ConnectorSpecifications for Barclaycard {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
index c8c2bb1f91..388213a378 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
@@ -2305,6 +2305,7 @@ impl ConnectorSpecifications for Cybersource {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => None,
+ api::CurrentFlowInfo::Psync { .. } => None,
}
}
fn get_alternate_flow_if_needed(
@@ -2325,6 +2326,7 @@ impl ConnectorSpecifications for Cybersource {
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => None,
api::CurrentFlowInfo::SetupMandate { .. } => None,
+ api::CurrentFlowInfo::Psync { .. } => None,
}
}
fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo) -> bool {
@@ -2336,6 +2338,7 @@ impl ConnectorSpecifications for Cybersource {
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
/// Check if authentication flow is required
@@ -2361,6 +2364,7 @@ impl ConnectorSpecifications for Cybersource {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
/// Check if post-authentication flow is required
@@ -2386,6 +2390,7 @@ impl ConnectorSpecifications for Cybersource {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
index c281bfea13..d443b9becc 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs
@@ -1368,6 +1368,7 @@ impl ConnectorSpecifications for Nexixpay {
..
} => payment_method == Some(enums::PaymentMethod::Card) && auth_type.is_three_ds(),
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
@@ -1395,6 +1396,7 @@ impl ConnectorSpecifications for Nexixpay {
// No alternate flow for complete authorize
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs
index f3979dc3d1..95962b5519 100644
--- a/crates/hyperswitch_connectors/src/connectors/nmi.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs
@@ -1207,6 +1207,7 @@ impl ConnectorSpecifications for Nmi {
auth_type,
request_data,
} => auth_type.is_three_ds() && request_data.is_card(),
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/nordea.rs b/crates/hyperswitch_connectors/src/connectors/nordea.rs
index 82ff3c8610..6a5f330a64 100644
--- a/crates/hyperswitch_connectors/src/connectors/nordea.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nordea.rs
@@ -1279,6 +1279,7 @@ impl ConnectorSpecifications for Nordea {
),
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs
index e5a59343b4..a7443b350f 100644
--- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs
@@ -1732,6 +1732,7 @@ impl ConnectorSpecifications for Nuvei {
auth_type,
request_data,
} => auth_type.is_three_ds() && request_data.is_card(),
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs
index d4b853d8ca..17c2bba806 100644
--- a/crates/hyperswitch_connectors/src/connectors/payme.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payme.rs
@@ -1481,6 +1481,7 @@ impl ConnectorSpecifications for Payme {
),
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs
index 09b8e525ec..8e3b475576 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs
@@ -2583,6 +2583,7 @@ impl ConnectorSpecifications for Paypal {
..
} => payment_method == Some(enums::PaymentMethod::Card),
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rs
index a1ebf3bbf4..598f070d1c 100644
--- a/crates/hyperswitch_connectors/src/connectors/redsys.rs
+++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs
@@ -1084,6 +1084,7 @@ impl ConnectorSpecifications for Redsys {
} => auth_type.is_three_ds() && request_data.is_card(),
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
@@ -1120,6 +1121,7 @@ impl ConnectorSpecifications for Redsys {
}
}
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rs
index 34610f6d74..f6cb6596a6 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs
@@ -57,9 +57,9 @@ use hyperswitch_masking::{Maskable, PeekInterface};
use crate::{
connectors::santander::{
requests::{
- SantanderAuthRequest, SantanderAuthType, SantanderMetadataObject,
+ AccessTokenUrlPath, SantanderAuthRequest, SantanderAuthType, SantanderMetadataObject,
SantanderPaymentRequest, SantanderPixAutomaticSolicitationRequest,
- SantanderRefundRequest, SantanderRouterData,
+ SantanderRefundRequest, SantanderRouterData, SantanderSetupMandateRequest,
},
responses::{
SanatanderAccessTokenResponse, SantanderCreatePixPayloadLocationResponse,
@@ -71,7 +71,7 @@ use crate::{
},
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
- utils::{self as connector_utils, convert_amount},
+ utils::{self as connector_utils, convert_amount, PaymentsAuthorizeRequestData},
};
#[derive(Clone)]
@@ -238,19 +238,20 @@ impl ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsRe
enums::PaymentMethod::BankTransfer => match req.request.payment_method_type {
Some(enums::PaymentMethodType::Pix) => {
let santander_variant =
- transformers::get_qr_code_type(req.request.connector_meta.clone())?;
+ transformers::get_qr_code_type(req.request.connector_meta.clone());
match santander_variant {
- enums::ExpiryType::Immediate => Ok(format!(
+ Some(enums::ExpiryType::Immediate) => Ok(format!(
"{}api/v1/cob/{}",
self.base_url(connectors),
req.request.connector_transaction_id
)),
- enums::ExpiryType::Scheduled => Ok(format!(
+ Some(enums::ExpiryType::Scheduled) => Ok(format!(
"{}api/v1/cobv/{}",
self.base_url(connectors),
req.request.connector_transaction_id
)),
+ None => Err(errors::ConnectorError::ResponseDeserializationFailed.into()),
}
}
_ => Err(errors::ConnectorError::NotSupported {
@@ -482,6 +483,19 @@ impl ConnectorCommon for Santander {
connector_metadata: None,
})
}
+ SantanderErrorResponse::PixAutomatico(response) => Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code.to_string(),
+ message: response.message.clone(),
+ reason: Some(response.description.clone()),
+ attempt_status: None,
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
SantanderErrorResponse::Boleto(response) => Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code.to_string(),
@@ -623,12 +637,26 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- match req.payment_method {
- enums::PaymentMethod::BankTransfer => Ok(format!(
+ let path = transformers::decide_access_token_key_suffix(
+ req.request.current_flow.clone(),
+ req.payment_method_type,
+ req.recurring_mandate_payment_data.is_some(),
+ )
+ .ok_or(errors::ConnectorError::GenericError {
+ error_message: "AccessToken URL decision".to_string(),
+ error_object: serde_json::Value::Null,
+ })?;
+
+ match path {
+ AccessTokenUrlPath::Leg1 => Ok(format!(
"{}oauth/token?grant_type=client_credentials",
connectors.santander.base_url
)),
- enums::PaymentMethod::Voucher => {
+ AccessTokenUrlPath::Leg2 => Ok(format!(
+ "{}auth/oauth/v2/token",
+ connectors.santander.base_url
+ )),
+ AccessTokenUrlPath::Boleto => {
let secondary_base_url = connectors.santander.secondary_base_url.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "secondary_base_url for Santander",
@@ -636,11 +664,6 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
)?;
Ok(format!("{}auth/oauth/v2/token", secondary_base_url))
}
- _ => Err(errors::ConnectorError::NotSupported {
- message: req.payment_method.to_string(),
- connector: "Santander",
- }
- .into()),
}
}
@@ -701,15 +724,102 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Santander
{
- fn build_request(
+ fn get_headers(
+ &self,
+ req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}api/v1/rec", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = SantanderRouterData::from((amount, req));
+ let connector_req = SantanderSetupMandateRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
- Err(
- errors::ConnectorError::NotImplemented("Setup Mandate flow for Santander".to_string())
- .into(),
- )
+ let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;
+
+ let request = Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .attach_default_headers()
+ .headers(self.get_headers(req, connectors)?)
+ .url(&self.get_url(req, connectors)?)
+ .add_certificate(Some(auth_details.client_id))
+ .add_certificate_key(Some(auth_details.client_secret))
+ .set_body(self.get_request_body(req, connectors)?)
+ .build(),
+ );
+ Ok(request)
+ }
+
+ fn handle_response(
+ &self,
+ data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<
+ RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ errors::ConnectorError,
+ > {
+ let response: responses::SantanderSetupMandateResponse = res
+ .response
+ .parse_struct("santander SantanderSetupMandateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
}
}
@@ -762,6 +872,9 @@ impl ConnectorIntegration<PushNotification, PushNotificationRequestData, Payment
.attach_default_headers()
.headers(types::PaymentsPushNotificationType::get_headers(
self, req, connectors,
+ )?)
+ .set_body(types::PaymentsPushNotificationType::get_request_body(
+ self, req, connectors,
)?);
Ok(Some(builder.build()))
@@ -795,6 +908,14 @@ impl ConnectorIntegration<PushNotification, PushNotificationRequestData, Payment
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Santander {
@@ -819,7 +940,17 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
match req.payment_method {
enums::PaymentMethod::BankTransfer => match req.request.payment_method_type {
- Some(enums::PaymentMethodType::Pix) => {
+ Some(enums::PaymentMethodType::Pix)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr) => {
+ // Check if this is a MIT (Merchant Initiated Transaction) for PixAutomaticoPush or PixAutomaticoQr
+ if req.request.is_mit_payment() {
+ // For MIT payments, use cobr endpoint (recurring charge endpoint)
+ return Ok(format!(
+ "{}api/v1/cobr/{}",
+ self.base_url(connectors),
+ req.connector_request_reference_id,
+ ));
+ }
match &req
.request
.feature_metadata
@@ -846,6 +977,22 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
.into()),
}
}
+ Some(enums::PaymentMethodType::PixAutomaticoPush) => {
+ // For PixAutomaticoPush MIT, use cobr endpoint
+ if req.request.is_mit_payment() {
+ Ok(format!(
+ "{}api/v1/cobr/{}",
+ self.base_url(connectors),
+ req.connector_request_reference_id,
+ ))
+ } else {
+ Err(errors::ConnectorError::NotSupported {
+ message: req.payment_method.to_string(),
+ connector: "Santander",
+ }
+ .into())
+ }
+ }
_ => Err(errors::ConnectorError::NotSupported {
message: req.payment_method.to_string(),
connector: "Santander",
@@ -908,7 +1055,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;
let method: Result<Method, error_stack::Report<errors::ConnectorError>> =
match req.payment_method_type {
- Some(enums::PaymentMethodType::Pix) => Ok(Method::Put),
+ Some(enums::PaymentMethodType::Pix)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr)
+ | Some(enums::PaymentMethodType::PixAutomaticoPush) => Ok(Method::Put),
Some(enums::PaymentMethodType::Boleto) => Ok(Method::Post),
_ => Err(errors::ConnectorError::NotSupported {
message: req.payment_method.to_string(),
@@ -949,6 +1098,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
let original_amount = match response {
SantanderPaymentsResponse::PixQRCode(ref pix_data) => pix_data.valor.original.clone(),
SantanderPaymentsResponse::Boleto(ref boleto_data) => boleto_data.nominal_value.clone(),
+ SantanderPaymentsResponse::PixAutomaticoCobr(ref automatico_data) => {
+ automatico_data.valor.original.clone()
+ }
};
event_builder.map(|i| i.set_response_body(&response));
@@ -1016,75 +1168,144 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San
_ => None,
};
- match req.payment_method {
- enums::PaymentMethod::BankTransfer => match req.request.payment_method_type {
- Some(enums::PaymentMethodType::Pix) => {
- let santander_variant =
- transformers::get_qr_code_type(req.request.connector_meta.clone())?;
- match santander_variant {
- enums::ExpiryType::Immediate => Ok(format!(
- "{}api/v1/cob/{}",
- self.base_url(connectors),
- connector_transaction_id.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "connector_transaction_id"
- }
- )?
- )),
- enums::ExpiryType::Scheduled => Ok(format!(
- "{}api/v1/cobv/{}",
+ // MIT recurring charge sync - use cobr endpoint
+ if req.request.connector_meta.is_none()
+ && matches!(
+ req.payment_method_type,
+ Some(enums::PaymentMethodType::PixAutomaticoPush)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr)
+ )
+ {
+ let txid =
+ connector_transaction_id.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_transaction_id",
+ })?;
+ return Ok(format!("{}api/v1/cobr/{}", self.base_url(connectors), txid,));
+ }
+
+ let is_journey_2_cit = req.request.amount.get_amount_as_i64() == 0
+ && matches!(
+ req.payment_method_type,
+ Some(enums::PaymentMethodType::PixAutomaticoQr)
+ );
+
+ if is_journey_2_cit {
+ let mandate_id = req.request.connector_reference_id.as_ref().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_reference_id for Journey 2 CIT",
+ },
+ )?;
+ // Journey 2 CIT flow
+ Ok(format!(
+ "{}api/v1/rec/{}",
+ self.base_url(connectors),
+ mandate_id,
+ ))
+ } else {
+ match req.payment_method {
+ enums::PaymentMethod::BankTransfer => match req.request.payment_method_type {
+ Some(enums::PaymentMethodType::Pix)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr) => {
+ let santander_variant =
+ transformers::get_qr_code_type(req.request.connector_meta.clone());
+ match santander_variant {
+ // Pix One-off Immediate type or Journey 3 CIT Flow
+ Some(enums::ExpiryType::Immediate) => Ok(format!(
+ "{}api/v1/cob/{}",
+ self.base_url(connectors),
+ connector_transaction_id.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_transaction_id"
+ }
+ )?
+ )),
+ // Pix One-off Scheduled type or Journey 4 CIT flow
+ Some(enums::ExpiryType::Scheduled) => Ok(format!(
+ "{}api/v1/cobv/{}",
+ self.base_url(connectors),
+ connector_transaction_id.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_transaction_id"
+ }
+ )?
+ )),
+ // Journey 1/2 CIT flow (no QR code type found)
+ None => {
+ let mandate_id = req
+ .request
+ .mandate_id
+ .as_ref()
+ .and_then(|ids| match &ids.mandate_reference_id {
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
+ connector_mandate_ids,
+ )) => connector_mandate_ids.get_connector_mandate_id(),
+ _ => None,
+ })
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
+ Ok(format!(
+ "{}api/v1/rec/{}",
+ self.base_url(connectors),
+ mandate_id,
+ ))
+ }
+ }
+ }
+ // Journey 1 CIT flow
+ Some(enums::PaymentMethodType::PixAutomaticoPush) => {
+ let mandate_id = req
+ .request
+ .connector_reference_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
+ Ok(format!(
+ "{}api/v1/rec/{}",
self.base_url(connectors),
- connector_transaction_id.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "connector_transaction_id"
- }
- )?
- )),
+ mandate_id,
+ ))
}
- }
- _ => Err(errors::ConnectorError::NotSupported {
- message: req.payment_method.to_string(),
- connector: "Santander",
- }
- .into()),
- },
- enums::PaymentMethod::Voucher => match req.request.payment_method_type {
- Some(enums::PaymentMethodType::Boleto) => {
- let boleto_mca_metadata = santander_mca_metadata
- .boleto
- .ok_or(errors::ConnectorError::NoConnectorMetaData)?;
- let boleto_base_url = connectors
- .santander
- .secondary_base_url
- .clone()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- let connector_transaction_id = connector_transaction_id.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "connector_transaction_id",
- },
- )?;
- let workspace_id = boleto_mca_metadata.workspace_id.peek();
- let version = santander_constants::SANTANDER_VERSION;
- let voucher_data = req
- .request
- .connector_meta
- .clone()
- .map(|data| {
- data.parse_value::<api_models::payments::VoucherNextStepData>(
- "VoucherNextStepData",
- )
- .change_context(errors::ConnectorError::ParsingFailed)
- })
- .transpose()?;
-
- let (expiry_date, issue_date) = voucher_data
- .as_ref()
- .and_then(|data| data.expiry_date.zip(data.entry_date.clone()))
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "issue_date/due_date",
- })?;
-
- Ok(format!(
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: req.payment_method.to_string(),
+ connector: "Santander",
+ }
+ .into()),
+ },
+ enums::PaymentMethod::Voucher => match req.request.payment_method_type {
+ Some(enums::PaymentMethodType::Boleto) => {
+ let boleto_mca_metadata = santander_mca_metadata
+ .boleto
+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;
+ let boleto_base_url = connectors
+ .santander
+ .secondary_base_url
+ .clone()
+ .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
+ let connector_transaction_id = connector_transaction_id.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_transaction_id",
+ },
+ )?;
+ let workspace_id = boleto_mca_metadata.workspace_id.peek();
+ let version = santander_constants::SANTANDER_VERSION;
+ let voucher_data = req
+ .request
+ .connector_meta
+ .clone()
+ .map(|data| {
+ data.parse_value::<api_models::payments::VoucherNextStepData>(
+ "VoucherNextStepData",
+ )
+ .change_context(errors::ConnectorError::ParsingFailed)
+ })
+ .transpose()?;
+
+ let (expiry_date, issue_date) = voucher_data
+ .as_ref()
+ .and_then(|data| data.expiry_date.zip(data.entry_date.clone()))
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "issue_date/due_date",
+ })?;
+
+ Ok(format!(
"{boleto_base_url}collection_bill_management/{version}/workspaces/{workspace_id}/bank_slips?\
paymentDateFinal={due_date}&\
paymentDateInitial={issue_date}&\
@@ -1097,18 +1318,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San
issue_date = issue_date,
connector_transaction_id = connector_transaction_id
))
- }
+ }
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: req.payment_method.to_string(),
+ connector: "Santander",
+ }
+ .into()),
+ },
_ => Err(errors::ConnectorError::NotSupported {
message: req.payment_method.to_string(),
connector: "Santander",
}
.into()),
- },
- _ => Err(errors::ConnectorError::NotSupported {
- message: req.payment_method.to_string(),
- connector: "Santander",
}
- .into()),
}
}
@@ -1142,20 +1364,31 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San
.parse_struct("santander SantanderPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
let original_amount = match response {
SantanderPaymentsSyncResponse::PixQRCode(ref pix_data) => {
pix_data.valor.original.clone()
}
+ // No amount is sent back in Boleto response
SantanderPaymentsSyncResponse::Boleto(_) => convert_amount(
self.amount_converter,
data.request.amount,
data.request.currency,
)?,
+ SantanderPaymentsSyncResponse::PixAutomaticoConsultAndActivateJourney(_) => {
+ convert_amount(
+ self.amount_converter,
+ data.request.amount,
+ data.request.currency,
+ )?
+ }
+ SantanderPaymentsSyncResponse::PixAutomaticoCobrSync(ref cobr_data) => {
+ cobr_data.valor.original.clone()
+ }
};
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
-
let response_integrity_object = connector_utils::get_sync_integrity_object(
self.amount_converter,
original_amount,
@@ -1712,6 +1945,28 @@ static SANTANDER_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
},
);
+ santander_supported_payment_methods.add(
+ enums::PaymentMethod::BankTransfer,
+ enums::PaymentMethodType::PixAutomaticoQr,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::Supported,
+ refunds: enums::FeatureStatus::NotSupported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+
+ santander_supported_payment_methods.add(
+ enums::PaymentMethod::BankTransfer,
+ enums::PaymentMethodType::PixAutomaticoPush,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::Supported,
+ refunds: enums::FeatureStatus::NotSupported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+
santander_supported_payment_methods.add(
enums::PaymentMethod::Voucher,
enums::PaymentMethodType::Boleto,
@@ -1757,7 +2012,9 @@ impl ConnectorSpecifications for Santander {
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
match payment_attempt.payment_method_type {
- Some(enums::PaymentMethodType::Pix) => {
+ Some(enums::PaymentMethodType::Pix)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr)
+ | Some(enums::PaymentMethodType::PixAutomaticoPush) => {
if is_config_enabled_to_send_payment_id_as_connector_request_id
&& payment_intent.is_payment_id_from_merchant.unwrap_or(false)
{
@@ -1794,6 +2051,7 @@ impl ConnectorSpecifications for Santander {
Some(CurrentFlowInfo::SetupMandate { .. }) => true,
Some(CurrentFlowInfo::CompleteAuthorize { .. })
| Some(CurrentFlowInfo::Authorize { .. })
+ | Some(CurrentFlowInfo::Psync { .. })
| None => false,
}
}
@@ -1805,7 +2063,9 @@ impl ConnectorSpecifications for Santander {
Some(enums::PaymentMethodType::PixAutomaticoPush)
) && request_data.mandate_id.is_none()
}
- CurrentFlowInfo::Authorize { .. } | CurrentFlowInfo::CompleteAuthorize { .. } => false,
+ CurrentFlowInfo::Authorize { .. }
+ | CurrentFlowInfo::CompleteAuthorize { .. }
+ | CurrentFlowInfo::Psync { .. } => false,
}
}
fn is_generate_qr_flow_required(&self, current_flow: CurrentFlowInfo) -> bool {
@@ -1816,7 +2076,9 @@ impl ConnectorSpecifications for Santander {
Some(enums::PaymentMethodType::PixAutomaticoQr)
) && request_data.mandate_id.is_none()
}
- CurrentFlowInfo::Authorize { .. } | CurrentFlowInfo::CompleteAuthorize { .. } => false,
+ CurrentFlowInfo::Authorize { .. }
+ | CurrentFlowInfo::CompleteAuthorize { .. }
+ | CurrentFlowInfo::Psync { .. } => false,
}
}
}
@@ -1826,22 +2088,30 @@ impl ConnectorAccessTokenSuffix for Santander {
&self,
router_data: &dyn api::AccessTokenData,
merchant_connector_id_or_connector_name: String,
- _current_flow: Option<CurrentFlowInfo>,
+ current_flow: Option<CurrentFlowInfo>,
) -> CustomResult<String, errors::ConnectorError> {
- let pmt = router_data.get_payment_method_type();
- let merchant_id = router_data.get_merchant_id();
+ let merchant_id = &router_data.get_merchant_id();
+ let url_path = transformers::decide_access_token_key_suffix(
+ current_flow.clone(),
+ router_data.get_payment_method_type(),
+ router_data.is_mit_payment(),
+ );
- let key_suffix = pmt.map(|p| p.to_string());
+ let suffix = url_path.map(|path| match path {
+ AccessTokenUrlPath::Leg1 => "pix",
+ AccessTokenUrlPath::Leg2 => "pix_automatico",
+ AccessTokenUrlPath::Boleto => "boleto",
+ });
- match key_suffix {
- Some(key) => Ok(format!(
+ match suffix {
+ Some(suffix) => Ok(format!(
"access_token_{}_{}_{}",
merchant_id.get_string_repr(),
merchant_connector_id_or_connector_name,
- key
+ suffix,
)),
None => Ok(common_utils::access_token::get_default_access_token_key(
- &merchant_id,
+ merchant_id,
merchant_connector_id_or_connector_name,
)),
}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/requests.rs b/crates/hyperswitch_connectors/src/connectors/santander/requests.rs
index 1751ca3801..07e204d9df 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/requests.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/requests.rs
@@ -80,6 +80,16 @@ pub struct PixMetadataObject {
pub merchant_city: String,
}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PixAutomaticoMetadataObject {
+ pub client_id: Secret<String>,
+ pub client_secret: Secret<String>,
+ // might not be req for J1/J2, cross check
+ pub pix_key_value: Secret<String>,
+ // might not be req for J1/J2, cross check
+ pub pix_key_type: responses::SantanderPixKeyType,
+}
+
pub struct SantanderRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
@@ -124,7 +134,6 @@ pub struct SantanderDebtor {
pub cnpj: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cpf: Option<Secret<String>>,
- // Name
#[serde(skip_serializing_if = "Option::is_none")]
pub nome: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -247,6 +256,7 @@ pub struct SantanderRefundRequest {
pub enum SantanderPaymentRequest {
PixQR(Box<SantanderPixQRPaymentRequest>),
Boleto(Box<SantanderBoletoPaymentRequest>),
+ PixAutomaticoCobr(Box<SantanderPixAutomaticoCobrRequest>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -397,10 +407,184 @@ pub type BoletoAdditionalFields = (
),
);
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PixAutomaticoMetadataObject {
- pub client_id: Secret<String>,
- pub client_secret: Secret<String>,
- pub pix_key_value: Secret<String>,
- pub pix_key_type: responses::SantanderPixKeyType,
+// SetupMandate (Pix Automatico) Request Structures
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderSetupMandateRequest {
+ /// Information about the recurring object/service
+ pub vinculo: RecurrenceLink,
+ /// Calendar information for the recurrence
+ pub calendario: RecurrenceCalendar,
+ /// Retry policy for failed payments
+ pub politica_retentativa: RetryPolicy,
+ /// Location ID for QR code
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc: Option<i64>,
+ /// Value information (optional, for fixed amount mandates)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub valor: Option<RecurrenceValue>,
+ /// Activation data (required for Journey 3)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ativacao: Option<RecurrenceActivation>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceValue {
+ /// Fixed recurring value
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub valor_rec: Option<StringMajorUnit>,
+ /// Minimum value set by receiver
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub valor_minimo_recebedor: Option<StringMajorUnit>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceActivation {
+ /// Journey-specific data
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dados_jornada: Option<JourneyData>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct JourneyData {
+ /// Transaction ID for Journey 3
+ pub txid: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceLink {
+ /// Contract identifier
+ pub contrato: String,
+ /// Debtor information
+ pub devedor: RecurrenceDebtor,
+ /// Description of the recurring object
+ pub objeto: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceDebtor {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cnpj: Option<Secret<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpf: Option<Secret<String>>,
+ pub nome: Secret<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceCalendar {
+ /// Initial date in YYYY-MM-DD format
+ pub data_inicial: String,
+ /// Periodicity of the recurrence
+ pub periodicidade: Periodicidade,
+ /// Optional end date in YYYY-MM-DD format
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data_final: Option<String>,
+}
+
+/// Periodicity of recurring payments
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum Periodicidade {
+ /// Weekly
+ Semanal,
+ /// Monthly
+ Mensal,
+ /// Quarterly
+ Trimestral,
+ /// Semi-annually (every 6 months)
+ Semestral,
+ /// Annually
+ Anual,
+}
+
+/// Retry policy for failed recurring payments
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum RetryPolicy {
+ /// Does not allow retries
+ #[serde(rename = "NAO_PERMITE")]
+ NaoPermite,
+ /// Allows 3 retries over 7 days
+ #[serde(rename = "PERMITE_3R_7D")]
+ Permite3r7d,
+}
+
+/// Represents receiver details for Pix Automático recurring charge (cobr endpoint)
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoRecebedor {
+ /// Branch code (agencia) of the receiver's account
+ pub agencia: Secret<String>,
+ /// Account number (conta) of the receiver
+ pub conta: Secret<String>,
+ /// Account type (tipoConta) - CORRENTE, POUPANCA, or PAGAMENTO
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(rename = "tipoConta")]
+ pub tipo_conta: Option<SantanderAccountType>,
+}
+
+/// Represents calendar information for recurring charge (cobr endpoint)
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrCalendario {
+ /// Due date in YYYY-MM-DD format
+ pub data_de_vencimento: String,
+}
+
+/// Represents value information for recurring charge (cobr endpoint)
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrValor {
+ /// The amount to be charged
+ pub original: StringMajorUnit,
+}
+
+/// Request for creating a recurring Pix Automático charge (cobr endpoint)
+/// This is used when a MIT (Merchant Initiated Transaction) mandate is active
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrRequest {
+ /// Recurring charge ID - must be 29 alphanumeric characters (RR + 27 chars)
+ pub id_rec: String,
+ /// Additional information about the charge
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub info_adicional: Option<String>,
+ /// Calendar information (due date)
+ pub calendario: SantanderPixAutomaticoCobrCalendario,
+ /// Amount to be charged
+ pub valor: SantanderPixAutomaticoCobrValor,
+ /// Whether to adjust due date to next business day if due date falls on non-business day
+ pub ajuste_dia_util: bool,
+ /// Receiver/beneficiary details
+ pub recebedor: SantanderPixAutomaticoRecebedor,
+ /// Optional debtor information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub devedor: Option<SantanderDebtor>,
+}
+
+impl hyperswitch_masking::SerializableSecret for SantanderAccountType {}
+
+/// Portuguese equivalents for account types used in Santander API
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
+pub enum SantanderAccountType {
+ /// Checking account
+ #[serde(rename = "CORRENTE")]
+ Corrente,
+ /// Savings account
+ #[serde(rename = "POUPANCA")]
+ Poupanca,
+ /// Payment account
+ #[serde(rename = "PAGAMENTO")]
+ Pagamento,
+}
+
+pub enum AccessTokenUrlPath {
+ Leg1,
+ Leg2,
+ Boleto,
}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/responses.rs b/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
index 859c48ac44..b4d169a73d 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/responses.rs
@@ -96,6 +96,7 @@ pub enum SantanderVoidStatus {
pub enum SantanderPaymentsResponse {
PixQRCode(Box<SantanderPixQRCodePaymentsResponse>),
Boleto(Box<SantanderBoletoPaymentsResponse>),
+ PixAutomaticoCobr(Box<SantanderPixAutomaticoCobrResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -133,6 +134,62 @@ pub struct SantanderPixQRCodePaymentsResponse {
pub pix_copia_e_cola: Option<String>,
}
+/// Response for Pix Automático recurring charge (cobr endpoint)
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrResponse {
+ /// Recurring charge ID
+ pub id_rec: String,
+ /// Transaction ID
+ pub txid: String,
+ /// Additional information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub info_adicional: Option<String>,
+ /// Calendar information (due date)
+ pub calendario: SantanderPixAutomaticoCobrCalendarResponse,
+ /// Amount information
+ pub valor: requests::SantanderPixAutomaticoCobrValor,
+ /// Status of the recurring charge
+ pub status: SantanderPixAutomaticoCobrStatus,
+ /// Retry policy
+ pub politica_retentativa: String,
+ /// Adjustment for business days
+ pub ajuste_dia_util: bool,
+ /// Receiver details
+ pub recebedor: requests::SantanderPixAutomaticoRecebedor,
+ /// Optional debtor information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub devedor: Option<requests::SantanderDebtor>,
+}
+
+/// Calendar information in cobr response
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrCalendarResponse {
+ /// Due date in YYYY-MM-DD format
+ pub data_de_vencimento: String,
+ /// Creation date in YYYY-MM-DD format
+ pub criacao: String,
+}
+
+/// Status of Pix Automático recurring charge
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum SantanderPixAutomaticoCobrStatus {
+ /// Created
+ Criada,
+ /// Active
+ Ativa,
+ /// Completed
+ Concluida,
+ /// Expired
+ Expirada,
+ /// Rejected
+ Rejeitada,
+ /// Cancelled
+ Cancelada,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderBoletoPaymentsResponse {
@@ -330,6 +387,8 @@ pub struct SantanderCalendarResponse {
pub enum SantanderPaymentsSyncResponse {
PixQRCode(Box<SantanderPixQRCodeSyncResponse>),
Boleto(Box<SantanderBoletoPSyncResponse>),
+ PixAutomaticoConsultAndActivateJourney(Box<SantanderPixAutomaticRecResponse>),
+ PixAutomaticoCobrSync(Box<SantanderPixAutomaticoCobrSyncResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -347,6 +406,87 @@ pub struct SantanderPix {
pub info_pagador: Option<String>,
}
+/// Response for consulting a recurring charge via cobr endpoint (GET /api/v1/cobr/{txid})
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderPixAutomaticoCobrSyncResponse {
+ /// Recurring charge ID (idRec)
+ pub id_rec: String,
+ /// Transaction ID
+ pub txid: String,
+ /// Additional information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub info_adicional: Option<String>,
+ /// Calendar information (due date, creation date)
+ pub calendario: SantanderPixAutomaticoCobrCalendarResponse,
+ /// Amount information
+ pub valor: requests::SantanderPixAutomaticoCobrValor,
+ /// Adjustment for business days
+ pub ajuste_dia_util: bool,
+ /// Receiver details
+ pub recebedor: serde_json::Value,
+ /// Status of the recurring charge
+ pub status: SantanderPixAutomaticoCobrStatus,
+ /// Retry policy
+ pub politica_retentativa: String,
+ /// Optional debtor information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub devedor: Option<serde_json::Value>,
+ /// Pix transaction details (present when payment is completed)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pix: Option<Vec<SantanderCobrSyncPix>>,
+ /// Status update history
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub atualizacao: Option<Vec<SantanderCobrSyncStatusUpdate>>,
+ /// Attempt history
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tentativas: Option<Vec<SantanderCobrSyncTentativa>>,
+}
+
+/// Pix transaction detail inside cobr sync response
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderCobrSyncPix {
+ /// EndToEndIdentification from PACS messages
+ pub end_to_end_id: Secret<String>,
+ /// Transaction ID
+ pub txid: String,
+ /// Value information
+ pub valor: serde_json::Value,
+ /// Timestamp when the Pix was processed
+ pub horario: String,
+ /// Optional payer info
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub info_pagador: Option<String>,
+}
+
+/// Status update entry in cobr sync response
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderCobrSyncStatusUpdate {
+ /// Status of the charge
+ pub status: String,
+ /// Date/time of the status update (RFC 3339)
+ pub data: String,
+}
+
+/// Attempt history entry in cobr sync response
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderCobrSyncTentativa {
+ /// Liquidation date (YYYY-MM-DD)
+ pub data_liquidacao: Option<String>,
+ /// Attempt type (AGND, NTAG, RIFL)
+ pub tipo: String,
+ /// Attempt status
+ pub status: String,
+ /// EndToEndIdentification
+ pub end_to_end_id: Option<Secret<String>>,
+ /// Status update history for this attempt
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub atualizacao: Option<Vec<SantanderCobrSyncStatusUpdate>>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SantanderUpdateBoletoResponse {
@@ -392,11 +532,21 @@ pub struct SantanderTime {
pub liquidacao: Option<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SantanderPixAutomaticoErrorResponse {
+ pub code: i32,
+ pub message: String,
+ pub level: String,
+ pub description: String,
+}
+
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SantanderErrorResponse {
PixQrCode(SantanderPixQRCodeErrorResponse),
Boleto(SantanderBoletoErrorResponse),
+ // Pix Automatico API returns 401 Unauthorized when access token is expired
+ PixAutomatico(SantanderPixAutomaticoErrorResponse),
Generic(SantanderGenericErrorResponse),
}
@@ -491,11 +641,12 @@ pub struct SantanderPixQRCodeErrorResponse {
#[serde(rename = "type")]
pub field_type: Secret<String>,
pub title: String,
- pub status: String,
+ // could be i64/String as well
+ pub status: serde_json::Value,
pub detail: Option<String>,
pub correlation_id: Option<String>,
- // Violations
- pub violacoes: Option<Vec<SantanderViolations>>,
+ // Violations - required to distinguish from Pattern1ErrorResponse
+ pub violacoes: Vec<SantanderViolations>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -592,7 +743,7 @@ pub enum SanatanderAccessTokenResponse {
#[serde(untagged)]
pub enum SanatanderTokenResponse {
Pix(SanatanderPixAccessTokenResponse),
- Boleto(SanatanderBoletoAccessTokenResponse),
+ PixAutomaticoBoleto(SantanderPixAutomaticoOrBoletoAccessTokenResponse),
}
#[derive(Debug, Serialize, Deserialize)]
@@ -607,7 +758,7 @@ pub struct SanatanderPixAccessTokenResponse {
}
#[derive(Debug, Serialize, Deserialize)]
-pub struct SanatanderBoletoAccessTokenResponse {
+pub struct SantanderPixAutomaticoOrBoletoAccessTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
pub token_type: String,
@@ -884,6 +1035,7 @@ pub struct SantanderPixAutomaticRecResponse {
/// Activation information for the recurrence
pub ativacao: Option<SantanderPixAutomaticoAtivacao>,
/// QR code data associated with the recurrence
+ // #[serde(rename = "dadosQR", alias = "dadosqr")]
#[serde(rename = "dadosQR")]
pub dados_qr: Option<SantanderPixAutomaticQrData>,
}
@@ -1018,3 +1170,101 @@ pub struct SantanderPixAutomaticoValor {
/// Minimum amount required from the recipient/creditor
pub valor_minimo_recebedor: Option<StringMajorUnit>,
}
+
+// SetupMandate (Pix Automatico) Response Structures
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SantanderSetupMandateResponse {
+ /// Recurrence ID
+ pub id_rec: String,
+ /// Information about the recurring object/service
+ pub vinculo: RecurrenceLinkResponse,
+ /// Calendar information for the recurrence
+ pub calendario: RecurrenceCalendarResponse,
+ /// Receiver information
+ pub recebedor: RecurrenceReceiver,
+ /// Status of the recurrence
+ pub status: RecurrenceStatus,
+ /// Retry policy for failed payments
+ pub politica_retentativa: requests::RetryPolicy,
+ /// Location information
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc: Option<LocationResponse>,
+ /// Update history
+ pub atualizacao: Vec<RecurrenceStatusUpdate>,
+}
+
+/// Information linking the recurrence to the service/contract
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceLinkResponse {
+ /// Description of the recurring object/service
+ pub objeto: String,
+ /// Debtor information
+ pub devedor: RecurrenceDebtorResponse,
+ /// Contract identifier
+ pub contrato: String,
+}
+
+/// Debtor information for recurring payments
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceDebtorResponse {
+ /// CNPJ (Business tax ID)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cnpj: Option<Secret<String>>,
+ /// CPF (Individual tax ID)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpf: Option<Secret<String>>,
+ /// Name of the debtor
+ pub nome: Secret<String>,
+}
+
+/// Calendar information for the recurring payment schedule
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceCalendarResponse {
+ /// Initial date in YYYY-MM-DD format
+ pub data_inicial: String,
+ /// Periodicity of the recurrence
+ pub periodicidade: requests::Periodicidade,
+ /// Optional end date in YYYY-MM-DD format
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data_final: Option<String>,
+}
+
+/// Receiver (merchant) information for recurring payments
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceReceiver {
+ /// Receiver's CNPJ (Business tax ID)
+ pub cnpj: Secret<String>,
+ /// Receiver's name
+ pub nome: Secret<String>,
+ /// Covenant/agreement code
+ pub convenio: String,
+}
+
+/// Location information for QR code
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocationResponse {
+ /// Location ID
+ pub id: i64,
+ /// Location URL
+ pub location: String,
+ /// Creation timestamp
+ pub criacao: String,
+ /// Recurrence ID
+ pub id_rec: String,
+}
+
+/// Status update history entry for the recurrence
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecurrenceStatusUpdate {
+ /// Status of the recurrence
+ pub status: Option<RecurrenceStatus>,
+ /// Date/time of this status update
+ pub data: String,
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
index 9d1ebec3cc..778a7e8739 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
@@ -1,7 +1,7 @@
use api_models::payments::{
- BeneficiaryDetails, BoletoPaymentTypeConstraints, CalculationType, ConnectorMetadata,
- DiscountTier, DiscountType, PollConfig, ProtestType, QrCodeInformation, SantanderData,
- SantanderPaymentDiscountRules, VoucherNextStepData,
+ AccountType, BeneficiaryDetails, BoletoPaymentTypeConstraints, CalculationType,
+ ConnectorMetadata, DiscountTier, DiscountType, PollConfig, ProtestType, QrCodeInformation,
+ SantanderData, SantanderMandatePeriodicity, SantanderPaymentDiscountRules, VoucherNextStepData,
};
use common_enums::{enums, AttemptStatus, BoletoDocumentKind, ExpiryType, PixKey};
use common_utils::{
@@ -14,10 +14,13 @@ use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, BoletoVoucherData, PaymentMethodData, VoucherData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
- router_flow_types::{payments::PushNotification, AuthorizeSessionToken, GenerateQr},
+ router_flow_types::{
+ payments::PushNotification, AuthorizeSessionToken, GenerateQr, SetupMandate,
+ },
router_request_types::{
- AuthorizeSessionTokenData, GenerateQrRequestData, PaymentsUpdateMetadataData,
- PushNotificationRequestData, ResponseId,
+ AuthorizeSessionTokenData, CurrentFlowInfo, GenerateQrRequestData,
+ PaymentsUpdateMetadataData, PushNotificationRequestData, ResponseId,
+ SetupMandateRequestData,
},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
@@ -37,32 +40,41 @@ use url::Url;
use crate::{
connectors::santander::{
requests::{
- BoletoAdditionalFields, Discount, DiscountObject, Environment, SantanderAuthRequest,
- SantanderAuthType, SantanderBoletoCancelOperation, SantanderBoletoCancelRequest,
- SantanderBoletoPaymentRequest, SantanderBoletoUpdateRequest, SantanderDebtor,
- SantanderDiscountType, SantanderGrantType, SantanderMetadataObject,
- SantanderPaymentRequest, SantanderPaymentsCancelRequest,
- SantanderPixAutomaticCalendarRequest, SantanderPixAutomaticDestinationRequest,
- SantanderPixAutomaticSolicitationRequest, SantanderPixCancelRequest,
- SantanderPixDueDateCalendarRequest, SantanderPixImmediateCalendarRequest,
- SantanderPixQRPaymentRequest, SantanderPixRequestCalendar, SantanderProtestType,
- SantanderRefundRequest, SantanderRouterData, SantanderValue, SantanderValueType,
+ AccessTokenUrlPath, BoletoAdditionalFields, Discount, DiscountObject, Environment,
+ JourneyData, Periodicidade, RecurrenceActivation, RecurrenceCalendar, RecurrenceDebtor,
+ RecurrenceLink, RecurrenceValue, RetryPolicy, SantanderAccountType,
+ SantanderAuthRequest, SantanderAuthType, SantanderBoletoCancelOperation,
+ SantanderBoletoCancelRequest, SantanderBoletoPaymentRequest,
+ SantanderBoletoUpdateRequest, SantanderDebtor, SantanderDiscountType,
+ SantanderGrantType, SantanderMetadataObject, SantanderPaymentRequest,
+ SantanderPaymentsCancelRequest, SantanderPixAutomaticCalendarRequest,
+ SantanderPixAutomaticDestinationRequest, SantanderPixAutomaticSolicitationRequest,
+ SantanderPixAutomaticoCobrCalendario, SantanderPixAutomaticoCobrRequest,
+ SantanderPixAutomaticoCobrValor, SantanderPixAutomaticoRecebedor,
+ SantanderPixCancelRequest, SantanderPixDueDateCalendarRequest,
+ SantanderPixImmediateCalendarRequest, SantanderPixQRPaymentRequest,
+ SantanderPixRequestCalendar, SantanderPostProcessingStepRequest, SantanderProtestType,
+ SantanderRefundRequest, SantanderRouterData, SantanderSetupMandateRequest,
+ SantanderValue, SantanderValueType,
},
responses::{
Beneficiary, Key, NsuComposite, Payer, RecurrenceStatus, SanatanderAccessTokenResponse,
SanatanderTokenResponse, SantanderAdditionalInfo, SantanderBoletoDocumentKind,
SantanderBoletoPaymentType, SantanderBoletoStatus,
- SantanderCreatePixPayloadLocationResponse, SantanderDocumentKind,
+ SantanderCreatePixPayloadLocationResponse, SantanderDocumentKind, SantanderJourneyType,
SantanderPaymentStatus, SantanderPaymentsResponse, SantanderPaymentsSyncResponse,
SantanderPixAutomaticRecResponse, SantanderPixAutomaticSolicitationResponse,
+ SantanderPixAutomaticoCobrStatus, SantanderPixAutomaticoCobrSyncResponse,
SantanderPixKeyType, SantanderPixQRCodePaymentsResponse,
SantanderPixQRCodeSyncResponse, SantanderRefundResponse, SantanderRefundStatus,
- SantanderUpdateMetadataResponse, SantanderVoidResponse, SantanderVoidStatus,
- WaitScreenData,
+ SantanderSetupMandateResponse, SantanderUpdateMetadataResponse, SantanderVoidResponse,
+ SantanderVoidStatus, WaitScreenData,
},
},
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
- utils::{self as connector_utils, QrImage, RouterData as _},
+ utils::{
+ self as connector_utils, PaymentsAuthorizeRequestData, QrImage, RouterData as RouterDataExt,
+ },
};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -194,13 +206,22 @@ impl
>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.status);
+ let journey = item
+ .response
+ .dados_qr
+ .as_ref()
+ .map(|qr_data| qr_data.jornada.clone())
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "response.dadosQR.jornada",
+ })?;
+ let expiry_type = journey.and_then(Option::<ExpiryType>::from);
let connector_metadata = match item
.response
.dados_qr
.as_ref()
.and_then(|dados_qr| dados_qr.pix_copia_e_cola.clone())
{
- Some(pix_copia_e_cola) => convert_pix_data_to_value(pix_copia_e_cola, None)?,
+ Some(pix_copia_e_cola) => convert_pix_data_to_value(pix_copia_e_cola, expiry_type)?,
None => None,
};
let mandate_reference = Box::new(Some(MandateReference {
@@ -467,7 +488,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SanatanderAccessTokenResponse, T, Acces
}),
..item.data
}),
- SanatanderTokenResponse::Boleto(boleto_response) => Ok(Self {
+ SanatanderTokenResponse::PixAutomaticoBoleto(boleto_response) => Ok(Self {
response: Ok(AccessToken {
token: boleto_response.access_token,
expires: boleto_response.expires_in,
@@ -500,12 +521,18 @@ impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>> for SantanderPa
fn try_from(
value: &SantanderRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
- if value.router_data.request.capture_method != Some(enums::CaptureMethod::Automatic) {
- return Err(errors::ConnectorError::FlowNotSupported {
- flow: format!("{:?}", value.router_data.request.capture_method),
- connector: "Santander".to_string(),
- }
- .into());
+ // Check if this is a MIT (Merchant Initiated Transaction) for PixAutomaticoPush or PixAutomaticoQr
+ if value.router_data.request.is_mit_payment()
+ && matches!(
+ value.router_data.request.payment_method_type,
+ Some(enums::PaymentMethodType::PixAutomaticoPush)
+ | Some(enums::PaymentMethodType::PixAutomaticoQr)
+ )
+ {
+ // Handle MIT recurring charge creation via cobr endpoint
+ return Ok(Self::PixAutomaticoCobr(Box::new(
+ SantanderPixAutomaticoCobrRequest::try_from(value)?,
+ )));
}
match value.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
@@ -751,6 +778,7 @@ impl
&BankTransferData,
),
) -> Result<Self, Self::Error> {
+ // Regular Pix QR payment flow
let santander_mca_metadata =
SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;
@@ -883,6 +911,120 @@ impl
}
}
+impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>>
+ for SantanderPixAutomaticoCobrRequest
+{
+ type Error = Error;
+ fn try_from(
+ value: &SantanderRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let mit_data = value
+ .router_data
+ .request
+ .connector_intent_metadata
+ .clone()
+ .and_then(|m| m.santander)
+ .and_then(|santander| santander.pix_automatico)
+ .and_then(|pix_automatico| match pix_automatico {
+ api_models::payments::SantanderPixAutomaticoData::Mit(mit) => Some(mit),
+ _ => None,
+ })
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_metadata.santander.pix_automatico.mit",
+ })?;
+
+ let receiver_details =
+ mit_data
+ .receiver_details
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_metadata.santander.pix_automatico.mit.receiver_details",
+ })?;
+
+ let branch_code =
+ receiver_details
+ .branch_code
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name:
+ "connector_metadata.santander.pix_automatico.mit.receiver_details.branch_code",
+ })?;
+
+ let account_number = receiver_details
+ .account_number
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name:
+ "connector_metadata.santander.pix_automatico.mit.receiver_details.account_number",
+ })?;
+
+ let account_type =
+ receiver_details
+ .account_type
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name:
+ "connector_metadata.santander.pix_automatico.mit.receiver_details.account_type",
+ })?;
+
+ let recebedor = SantanderPixAutomaticoRecebedor {
+ agencia: branch_code,
+ conta: account_number,
+ tipo_conta: Some(SantanderAccountType::from(account_type)),
+ };
+
+ let id_rec = value.router_data.request.get_connector_mandate_id()?;
+
+ // Use exec_date from MIT data if provided, otherwise default to current date + 1 day
+ let due_date = match mit_data.exec_date {
+ Some(exec_date) => format_as_date_only(Some(exec_date))?,
+ None => time::OffsetDateTime::now_utc()
+ .checked_add(time::Duration::days(1))
+ .ok_or(errors::ConnectorError::DateFormattingFailed)?
+ .date()
+ .format(&time::macros::format_description!("[year]-[month]-[day]"))
+ .change_context(errors::ConnectorError::DateFormattingFailed)?,
+ };
+
+ let calendario = SantanderPixAutomaticoCobrCalendario {
+ data_de_vencimento: due_date,
+ };
+
+ let ajuste_dia_util = mit_data.auto_adjust_date.unwrap_or(true);
+
+ let valor = SantanderPixAutomaticoCobrValor {
+ original: value.amount.to_owned(),
+ };
+
+ let info_adicional = value.router_data.description.clone().or_else(|| {
+ value
+ .router_data
+ .request
+ .billing_descriptor
+ .as_ref()
+ .and_then(|bd| bd.statement_descriptor.clone())
+ });
+
+ let devedor = Some(SantanderDebtor {
+ cpf: None,
+ cnpj: None,
+ nome: Some(value.router_data.get_billing_full_name()?),
+ logradouro: None,
+ cidade: None,
+ uf: None,
+ cep: None,
+ });
+
+ Ok(Self {
+ id_rec,
+ info_adicional,
+ calendario,
+ valor,
+ ajuste_dia_util,
+ recebedor,
+ devedor,
+ })
+ }
+}
+
impl From<SantanderPaymentStatus> for AttemptStatus {
fn from(item: SantanderPaymentStatus) -> Self {
match item {
@@ -894,6 +1036,52 @@ impl From<SantanderPaymentStatus> for AttemptStatus {
}
}
+// Helper function to convert SantanderPixAutomaticoCobrStatus to AttemptStatus with MIT flag
+fn cobr_status_to_attempt_status(
+ status: SantanderPixAutomaticoCobrStatus,
+ is_mit: bool,
+) -> AttemptStatus {
+ match status {
+ SantanderPixAutomaticoCobrStatus::Criada => match is_mit {
+ false => AttemptStatus::AuthenticationPending,
+ true => AttemptStatus::Pending,
+ },
+ SantanderPixAutomaticoCobrStatus::Ativa => AttemptStatus::AuthenticationPending,
+ SantanderPixAutomaticoCobrStatus::Concluida => AttemptStatus::Charged,
+ SantanderPixAutomaticoCobrStatus::Expirada => AttemptStatus::Failure,
+ SantanderPixAutomaticoCobrStatus::Rejeitada => AttemptStatus::Failure,
+ SantanderPixAutomaticoCobrStatus::Cancelada => AttemptStatus::Voided,
+ }
+}
+
+/// Helper function to determine AttemptStatus from cobr sync response.
+/// For CONCLUIDA status, only marks as Charged if endToEndId is present in the pix array.
+fn cobr_sync_status_to_attempt_status(
+ cobr_data: &SantanderPixAutomaticoCobrSyncResponse,
+) -> AttemptStatus {
+ match cobr_data.status {
+ SantanderPixAutomaticoCobrStatus::Criada => AttemptStatus::Pending,
+ SantanderPixAutomaticoCobrStatus::Ativa => AttemptStatus::Pending,
+ SantanderPixAutomaticoCobrStatus::Concluida => {
+ // Only mark as Charged if endToEndId is present in the pix object
+ let has_end_to_end_id = cobr_data
+ .pix
+ .as_ref()
+ .and_then(|pix_list| pix_list.first())
+ .map(|pix| !pix.end_to_end_id.clone().expose().is_empty())
+ .unwrap_or(false);
+ if has_end_to_end_id {
+ AttemptStatus::Charged
+ } else {
+ AttemptStatus::Failure
+ }
+ }
+ SantanderPixAutomaticoCobrStatus::Expirada => AttemptStatus::Failure,
+ SantanderPixAutomaticoCobrStatus::Rejeitada => AttemptStatus::Failure,
+ SantanderPixAutomaticoCobrStatus::Cancelada => AttemptStatus::Voided,
+ }
+}
+
impl From<SantanderBoletoStatus> for AttemptStatus {
fn from(item: SantanderBoletoStatus) -> Self {
match item {
@@ -982,6 +1170,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
let response = item.response.clone();
match response {
+ // Journey 3/4
SantanderPaymentsSyncResponse::PixQRCode(pix_data) => {
let attempt_status = AttemptStatus::from(pix_data.status.clone());
match attempt_status {
@@ -1029,6 +1218,16 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
}
}
}
+ // Journey 1/2
+ SantanderPaymentsSyncResponse::PixAutomaticoConsultAndActivateJourney(res) => {
+ let status = AttemptStatus::from(res.status);
+ // TODO : Make a write on connector_metadata to modify the ExpiryType as it may chance after approval of Recurrence
+ Ok(Self {
+ status,
+ response: item.data.response,
+ ..item.data
+ })
+ }
SantanderPaymentsSyncResponse::Boleto(res) => {
let status = res.content.first().map(|data| data.status.clone()).ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -1041,6 +1240,37 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme
..item.data
})
}
+ // MIT recurring charge sync (cobr endpoint consultation)
+ SantanderPaymentsSyncResponse::PixAutomaticoCobrSync(cobr_data) => {
+ let attempt_status = cobr_sync_status_to_attempt_status(&cobr_data);
+ let connector_metadata = cobr_data
+ .pix
+ .as_ref()
+ .and_then(|pix_list| pix_list.first())
+ .map(|pix| {
+ let data = SantanderData {
+ end_to_end_id: Some(pix.end_to_end_id.clone().expose()),
+ };
+ serde_json::to_value(data)
+ .change_context(errors::ConnectorError::ParsingFailed)
+ })
+ .transpose()?;
+ Ok(Self {
+ status: attempt_status,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(cobr_data.txid.clone()),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata,
+ network_txn_id: None,
+ connector_response_reference_id: Some(cobr_data.id_rec.clone()),
+ incremental_authorization_allowed: None,
+ authentication_data: None,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
}
}
}
@@ -1173,6 +1403,30 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsR
..item.data
})
}
+ SantanderPaymentsResponse::PixAutomaticoCobr(cobr_data) => {
+ // passing is_mit as true since this struct comes only when MITs are triggered
+ let attempt_status = cobr_status_to_attempt_status(cobr_data.status.clone(), true);
+ Ok(Self {
+ status: attempt_status,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(cobr_data.txid.clone()),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(Some(MandateReference {
+ connector_mandate_id: Some(cobr_data.id_rec.clone()),
+ payment_method_id: None,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: Some(cobr_data.txid.clone()),
+ })),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(cobr_data.id_rec.clone()),
+ incremental_authorization_allowed: None,
+ authentication_data: None,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
}
}
}
@@ -1596,22 +1850,14 @@ where
}
}
-pub fn get_qr_code_type(
- metadata: Option<Value>,
-) -> CustomResult<ExpiryType, errors::ConnectorError> {
- let qr_data_santander: Option<QrCodeInformation> = metadata
- .clone()
- .map(|qr_code_data| qr_code_data.parse_value("QrDataUrlSantander"))
- .transpose()
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+pub fn get_qr_code_type(metadata: Option<Value>) -> Option<ExpiryType> {
+ let qr_data_santander: Option<QrCodeInformation> =
+ metadata.and_then(|qr_code_data| qr_code_data.parse_value("QrDataUrlSantander").ok());
- let santander_variant = match qr_data_santander {
+ match qr_data_santander {
Some(QrCodeInformation::QrCodeUrl { expiry_type, .. }) => expiry_type,
- _ => {
- return Err(errors::ConnectorError::ResponseDeserializationFailed.into());
- }
- };
- Ok(santander_variant.ok_or_else(|| errors::ConnectorError::ResponseDeserializationFailed)?)
+ _ => None,
+ }
}
fn extract_boleto_components(input: &str) -> Result<NsuComposite, errors::ConnectorError> {
@@ -1810,12 +2056,247 @@ fn get_boleto_additional_fields_from_connector_metadata(
.unwrap_or_default()
}
+impl
+ TryFrom<
+ &SantanderRouterData<
+ &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ >,
+ > for SantanderSetupMandateRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ value: &SantanderRouterData<
+ &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let item = value.router_data;
+ let santander_meta = item
+ .request
+ .connector_intent_metadata
+ .as_ref()
+ .and_then(|metadata| metadata.santander.as_ref())
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_metadata.santander",
+ })?;
+
+ let pix_automatico_meta = santander_meta.pix_automatico.as_ref().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "pix_automatico metadata",
+ },
+ )?;
+
+ let cit_data = match pix_automatico_meta {
+ api_models::payments::SantanderPixAutomaticoData::Cit(cit) => cit,
+ _ => {
+ return Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_metadata.santander.pix_automatico.cit",
+ })?;
+ }
+ };
+
+ let contrato = cit_data
+ .contract_id
+ .clone()
+ .unwrap_or_else(|| item.payment_id.clone());
+
+ let politica_retentativa = if cit_data.retry_policy.unwrap_or(false) {
+ RetryPolicy::Permite3r7d
+ } else {
+ RetryPolicy::NaoPermite
+ };
+
+ let customer_name = item
+ .get_optional_billing_full_name()
+ .or(item.request.customer_name.clone())
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer_name",
+ })?;
+
+ let (cpf, cnpj) = item
+ .customer_document_details
+ .as_ref()
+ .map(|details| match details.document_type {
+ common_types::customers::DocumentKind::Cpf => {
+ (Some(details.document_number.clone()), None)
+ }
+ common_types::customers::DocumentKind::Cnpj => {
+ (None, Some(details.document_number.clone()))
+ }
+ })
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer.document_details",
+ })?;
+
+ let objeto =
+ item.description
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "description",
+ })?;
+
+ let loc = item
+ .session_token
+ .as_ref()
+ .and_then(|token| token.parse::<i64>().ok());
+
+ let mandate_details = cit_data.mandate_details.as_ref();
+
+ let data_inicial = match mandate_details.and_then(|md| md.start_date) {
+ Some(start_date) => format_as_date_only(Some(start_date))?,
+ None => time::OffsetDateTime::now_utc()
+ .date()
+ .format(&time::macros::format_description!("[year]-[month]-[day]"))
+ .change_context(errors::ConnectorError::DateFormattingFailed)?,
+ };
+
+ let data_final = mandate_details
+ .and_then(|md| md.end_date)
+ .map(|end_date| format_as_date_only(Some(end_date)))
+ .transpose()?;
+
+ let periodicidade = mandate_details
+ .and_then(|md| md.periodicity.as_ref())
+ .map(|p| Periodicidade::from(p.clone()))
+ .unwrap_or(Periodicidade::Semanal);
+
+ // either of valor or valor_minimo_recebedor can be passed at one time
+ let valor = Some(RecurrenceValue {
+ valor_rec: mandate_details
+ .and_then(|md| md.amount.clone())
+ .or_else(|| Some(value.amount.clone())),
+ valor_minimo_recebedor: None,
+ });
+
+ let is_immediate = item
+ .request
+ .feature_metadata
+ .as_ref()
+ .and_then(|f| f.pix_additional_details.as_ref())
+ .map(|pix_details| {
+ matches!(
+ pix_details,
+ api_models::payments::PixAdditionalDetails::Immediate(_)
+ )
+ })
+ .unwrap_or(false);
+
+ let is_journey_3 = if is_immediate {
+ item.request.payment_method_type == Some(enums::PaymentMethodType::PixAutomaticoQr)
+ && item.request.amount > 0
+ } else {
+ false
+ };
+
+ // pass ativacao only when Journey 4
+ let ativacao = if is_journey_3 {
+ Some(RecurrenceActivation {
+ dados_jornada: Some(JourneyData {
+ txid: item.connector_request_reference_id.clone(),
+ }),
+ })
+ } else {
+ None
+ };
+
+ Ok(Self {
+ vinculo: RecurrenceLink {
+ contrato,
+ devedor: RecurrenceDebtor {
+ cpf,
+ cnpj,
+ nome: customer_name,
+ },
+ objeto,
+ },
+ calendario: RecurrenceCalendar {
+ data_inicial,
+ periodicidade,
+ data_final,
+ },
+ politica_retentativa,
+ loc,
+ valor,
+ ativacao,
+ })
+ }
+}
+
+impl<F>
+ TryFrom<
+ ResponseRouterData<
+ F,
+ SantanderSetupMandateResponse,
+ SetupMandateRequestData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ item: ResponseRouterData<
+ F,
+ SantanderSetupMandateResponse,
+ SetupMandateRequestData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: AttemptStatus::from(item.response.status.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
+ item.data.connector_request_reference_id.clone(),
+ ),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(Some(MandateReference {
+ connector_mandate_id: Some(item.response.id_rec.clone()),
+ payment_method_id: None,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: None,
+ })),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charges: None,
+ authentication_data: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPostProcessingStepRequest {
+ type Error = Error;
+ fn try_from(value: &PaymentsPushNotificationRouterData) -> Result<Self, Self::Error> {
+ match &value.request.payment_method_data {
+ Some(PaymentMethodData::BankTransfer(bank_transfer_data)) => {
+ match bank_transfer_data.as_ref() {
+ BankTransferData::PixAutomaticoPush { .. } => {
+ let solicitation_request =
+ SantanderPixAutomaticSolicitationRequest::try_from(value)?;
+ Ok(Self::PixAutomaticoPush(solicitation_request))
+ }
+ // For PixAutomaticoQr, since there are no additional details needed in the request body,it should be null
+ BankTransferData::PixAutomaticoQr {} => Ok(Self::PixAutomaticoQr()),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Santander"),
+ ))?,
+ }
+ }
+ _ => Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Santander"),
+ ))?,
+ }
+ }
+}
impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPixAutomaticSolicitationRequest {
type Error = Error;
fn try_from(item: &PaymentsPushNotificationRouterData) -> Result<Self, Self::Error> {
// Extract expiration time from feature_metadata using the helper function
- let expires_in_secs = item
+ let expiry_time_seconds = item
.request
.feature_metadata
.as_ref()
@@ -1826,13 +2307,17 @@ impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPixAutomaticSolic
.change_context(errors::ConnectorError::ParsingFailed)
.attach_printable("Failed to get pix_automatico_push expiry time")?;
- // Calculate expiration datetime from current time + expires_in_secs
- let data_expiracao_solicitacao = (time::OffsetDateTime::now_utc()
- + time::Duration::seconds(i64::from(expires_in_secs)))
- .format(&time::format_description::well_known::Rfc3339)
- .change_context(errors::ConnectorError::InvalidDataFormat {
- field_name: "data_expiracao_solicitacao",
- })?;
+ let expiry_seconds = i64::from(expiry_time_seconds);
+ let offset_datetime = time::OffsetDateTime::now_utc()
+ .checked_add(time::Duration::seconds(expiry_seconds))
+ .ok_or(errors::ConnectorError::ParsingFailed)?;
+
+ // Format as ISO 8601 with Z timezone: YYYY-MM-ddTHH:mm:ss.SSSZ
+ let data_expiracao_solicitacao = offset_datetime
+ .format(&time::macros::format_description!(
+ "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
+ ))
+ .change_context(errors::ConnectorError::DateFormattingFailed)?;
// Extract bank transfer data for PixAutomaticoPush
let bank_transfer_data = match &item.request.payment_method_data {
@@ -1872,7 +2357,10 @@ impl TryFrom<&PaymentsPushNotificationRouterData> for SantanderPixAutomaticSolic
};
Ok(Self {
- id_rec: item.connector_request_reference_id.clone(),
+ id_rec: item
+ .request
+ .get_connector_mandate_id()
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
calendario: SantanderPixAutomaticCalendarRequest {
data_expiracao_solicitacao,
},
@@ -1925,3 +2413,134 @@ fn get_wait_screen_metadata(
}),
})))
}
+
+impl From<AccountType> for SantanderAccountType {
+ fn from(account_type: AccountType) -> Self {
+ match account_type {
+ AccountType::Current => Self::Corrente,
+ AccountType::Savings => Self::Poupanca,
+ AccountType::Payment => Self::Pagamento,
+ }
+ }
+}
+
+impl From<SantanderMandatePeriodicity> for Periodicidade {
+ fn from(item: SantanderMandatePeriodicity) -> Self {
+ match item {
+ SantanderMandatePeriodicity::Weekly => Self::Semanal,
+ SantanderMandatePeriodicity::Monthly => Self::Mensal,
+ SantanderMandatePeriodicity::Quarterly => Self::Trimestral,
+ SantanderMandatePeriodicity::Semiannually => Self::Semestral,
+ SantanderMandatePeriodicity::Annually => Self::Anual,
+ }
+ }
+}
+
+pub fn decide_access_token_key_suffix(
+ current_flow_info: Option<CurrentFlowInfo>,
+ payment_method_type: Option<enums::PaymentMethodType>,
+ is_mit: bool,
+) -> Option<AccessTokenUrlPath> {
+ match is_mit {
+ true => Some(AccessTokenUrlPath::Leg2),
+ false => {
+ match (current_flow_info, payment_method_type) {
+ // Authorize flow
+ (
+ Some(CurrentFlowInfo::Authorize { .. }),
+ Some(enums::PaymentMethodType::Boleto),
+ ) => Some(AccessTokenUrlPath::Boleto),
+ (Some(CurrentFlowInfo::Authorize { .. }), Some(enums::PaymentMethodType::Pix)) => {
+ Some(AccessTokenUrlPath::Leg1)
+ }
+ (
+ Some(CurrentFlowInfo::Authorize { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoPush),
+ ) => {
+ // redundant case
+ Some(AccessTokenUrlPath::Leg2)
+ }
+ (
+ Some(CurrentFlowInfo::Authorize { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoQr),
+ ) => Some(AccessTokenUrlPath::Leg1),
+ // CompleteAuthorize flow
+ (
+ Some(CurrentFlowInfo::CompleteAuthorize { .. }),
+ Some(enums::PaymentMethodType::Boleto),
+ ) => Some(AccessTokenUrlPath::Boleto),
+ (
+ Some(CurrentFlowInfo::CompleteAuthorize { .. }),
+ Some(enums::PaymentMethodType::Pix),
+ ) => Some(AccessTokenUrlPath::Leg1),
+ (
+ Some(CurrentFlowInfo::CompleteAuthorize { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoPush),
+ ) => {
+ // redundant case
+ Some(AccessTokenUrlPath::Leg2)
+ }
+ (
+ Some(CurrentFlowInfo::CompleteAuthorize { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoQr),
+ ) => {
+ // redundant case
+ Some(AccessTokenUrlPath::Leg2)
+ }
+ // SetupMandate flow
+ (
+ Some(CurrentFlowInfo::SetupMandate { .. }),
+ Some(enums::PaymentMethodType::Boleto),
+ ) => Some(AccessTokenUrlPath::Boleto),
+ (
+ Some(CurrentFlowInfo::SetupMandate { .. }),
+ Some(enums::PaymentMethodType::Pix),
+ ) => Some(AccessTokenUrlPath::Leg1),
+ (
+ Some(CurrentFlowInfo::SetupMandate { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoPush),
+ ) => Some(AccessTokenUrlPath::Leg2),
+ (
+ Some(CurrentFlowInfo::SetupMandate { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoQr),
+ ) => Some(AccessTokenUrlPath::Leg2),
+
+ (None, Some(enums::PaymentMethodType::Boleto)) => Some(AccessTokenUrlPath::Boleto),
+ (None, Some(enums::PaymentMethodType::Pix)) => Some(AccessTokenUrlPath::Leg1),
+ (
+ Some(CurrentFlowInfo::Psync { .. }),
+ Some(enums::PaymentMethodType::PixAutomaticoPush),
+ ) => Some(AccessTokenUrlPath::Leg2),
+ (
+ Some(CurrentFlowInfo::Psync { request_data }),
+ Some(enums::PaymentMethodType::PixAutomaticoQr),
+ ) => {
+ let expiry_type = get_qr_code_type(request_data.connector_meta);
+ match expiry_type {
+ Some(ExpiryType::Immediate) | Some(ExpiryType::Scheduled) => {
+ Some(AccessTokenUrlPath::Leg1)
+ }
+ None => Some(AccessTokenUrlPath::Leg2),
+ }
+ }
+ (None, Some(enums::PaymentMethodType::PixAutomaticoPush)) => {
+ Some(AccessTokenUrlPath::Leg2)
+ }
+ (None, Some(enums::PaymentMethodType::PixAutomaticoQr)) => None,
+ // No payment method type or unsupported payment method type
+ (_, None) => None,
+ (_, Some(_)) => None,
+ }
+ }
+ }
+}
+
+impl From<SantanderJourneyType> for Option<ExpiryType> {
+ fn from(item: SantanderJourneyType) -> Self {
+ match item {
+ SantanderJourneyType::Jornada3 => Some(ExpiryType::Immediate),
+ SantanderJourneyType::Jornada4 => Some(ExpiryType::Scheduled),
+ _ => None,
+ }
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rs
index b04138d1aa..cb29a0c868 100644
--- a/crates/hyperswitch_connectors/src/connectors/shift4.rs
+++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs
@@ -1108,6 +1108,7 @@ impl ConnectorSpecifications for Shift4 {
// No alternate flow for complete authorize and SetupMandate
api::CurrentFlowInfo::SetupMandate { .. }
| api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs
index bf70b85282..de683cfeba 100644
--- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs
@@ -1494,6 +1494,7 @@ impl ConnectorSpecifications for Trustpay {
),
api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
api::CurrentFlowInfo::SetupMandate { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs
index a755fa7c35..2557d28bd4 100644
--- a/crates/hyperswitch_connectors/src/connectors/xendit.rs
+++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs
@@ -1189,6 +1189,7 @@ impl ConnectorSpecifications for Xendit {
}
api::CurrentFlowInfo::SetupMandate { .. }
| api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
+ api::CurrentFlowInfo::Psync { .. } => false,
}
}
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 1f0d21b3ca..1751c40fe7 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -2630,6 +2630,7 @@ pub trait PaymentsSyncRequestData {
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
fn is_mandate_payment(&self) -> bool;
fn get_optional_connector_transaction_id(&self) -> Option<String>;
+ fn get_connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsSyncRequestData for PaymentsSyncData {
@@ -2664,6 +2665,19 @@ impl PaymentsSyncRequestData for PaymentsSyncData {
_ => None,
}
}
+ fn get_connector_mandate_id(&self) -> Option<String> {
+ self.mandate_id
+ .as_ref()
+ .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
+ Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
+ connector_mandate_ids.get_connector_mandate_id()
+ }
+ Some(payments::MandateReferenceId::NetworkMandateId(_))
+ | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_))
+ | Some(payments::MandateReferenceId::CardWithLimitedData)
+ | None => None,
+ })
+ }
}
pub trait PaymentsPostSessionTokensRequestData {
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 1d5a130dbe..a582eaebbc 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -60,6 +60,21 @@ pub enum CurrentFlowInfo {
/// The payment setup mandate request data
request_data: Box<SetupMandateRequestData>,
},
+ Psync {
+ /// The payment setup mandate request data
+ request_data: Box<PaymentsSyncData>,
+ },
+}
+
+impl CurrentFlowInfo {
+ pub fn get_feature_metadata(&self) -> Option<api_models::payments::FeatureMetadata> {
+ match self {
+ Self::Authorize { request_data, .. } => request_data.feature_metadata.clone(),
+ Self::CompleteAuthorize { .. } => None,
+ Self::SetupMandate { .. } => None,
+ Self::Psync { request_data } => request_data.feature_metadata.clone(),
+ }
+ }
}
#[derive(Debug, Clone, Serialize)]
@@ -1804,6 +1819,7 @@ pub struct SetupMandateRequestData {
pub partner_merchant_identifier_details:
Option<common_types::payments::PartnerMerchantIdentifierDetails>,
pub authentication_data: Option<AuthenticationData>,
+ pub connector_intent_metadata: Option<ConnectorMetadata>,
}
#[derive(Debug, Clone)]
@@ -1820,6 +1836,13 @@ pub struct DisputeSyncData {
pub connector_dispute_id: String,
}
+/// Trait for request data types that carry an optional mandate_id.
+/// Implemented by request types used in flows triggered after SetupMandate,
+/// where the mandate_id from the SetupMandate response needs to be propagated.
+pub trait MandateIdSettable {
+ fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds);
+}
+
#[derive(Debug, Clone, Serialize)]
pub struct PushNotificationRequestData {
pub payment_method_data: Option<PaymentMethodData>,
@@ -1828,6 +1851,12 @@ pub struct PushNotificationRequestData {
pub amount: Option<i64>,
}
+impl MandateIdSettable for PushNotificationRequestData {
+ fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds) {
+ self.mandate_id = Some(mandate_id);
+ }
+}
+
impl PushNotificationRequestData {
pub fn get_connector_mandate_id(&self) -> Option<String> {
self.mandate_id
@@ -1850,6 +1879,12 @@ pub struct GenerateQrRequestData {
pub mandate_id: Option<api_models::payments::MandateIds>,
}
+impl MandateIdSettable for GenerateQrRequestData {
+ fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds) {
+ self.mandate_id = Some(mandate_id);
+ }
+}
+
impl GenerateQrRequestData {
pub fn get_connector_mandate_id(&self) -> Option<String> {
self.mandate_id
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 9893bdd687..078688d88f 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -1001,6 +1001,8 @@ pub trait AccessTokenData {
fn get_payment_method_type(&self) -> Option<PaymentMethodType>;
/// Get the merchant id from RouterData
fn get_merchant_id(&self) -> common_utils::id_type::MerchantId;
+ /// Check if the payment is a MIT payment
+ fn is_mit_payment(&self) -> bool;
}
impl<F, Req, Res> AccessTokenData for RouterData<F, Req, Res> {
@@ -1010,6 +1012,9 @@ impl<F, Req, Res> AccessTokenData for RouterData<F, Req, Res> {
fn get_merchant_id(&self) -> common_utils::id_type::MerchantId {
self.merchant_id.clone()
}
+ fn is_mit_payment(&self) -> bool {
+ self.recurring_mandate_payment_data.is_some()
+ }
}
/// Trait ConnectorAccessTokenSuffix
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index fb8244695c..4de3c37392 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -334,6 +334,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::BoletoPaymentType,
api_models::payments::ExternalThreeDsData,
api_models::payments::PaymentMethodTokenizationDetails,
+ api_models::payments::SantanderMandateDetails,
+ api_models::payments::SantanderMandatePeriodicity,
+ api_models::payments::AccountType,
api_models::refunds::RefundRequest,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
@@ -628,6 +631,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ClickToPaySessionResponse,
api_models::payments::SantanderConnectorMetadataData,
api_models::payments::SantanderBoletoData,
+ api_models::payments::SantanderPixAutomaticoData,
+ api_models::payments::PixAutomaticoCitData,
+ api_models::payments::PixAutomaticoMitData,
+ api_models::payments::SantanderPixAutomaticoReceiverDetails,
api_models::payments::BoletoPaymentTypeConstraints,
api_models::payments::BeneficiaryDetails,
api_models::payments::InterestDetail,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 4d0c4c2640..94cd787490 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -251,6 +251,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::NetworkParams,
api_models::payments::Cryptogram,
api_models::payments::ExternalThreeDsData,
+ api_models::payments::SantanderMandateDetails,
+ api_models::payments::SantanderMandatePeriodicity,
+ api_models::payments::AccountType,
common_types::payments::MerchantCountryCode,
common_utils::request::Method,
api_models::errors::types::GenericErrorResponseOpenApi,
@@ -711,6 +714,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::Address,
api_models::payments::SantanderConnectorMetadataData,
api_models::payments::SantanderBoletoData,
+ api_models::payments::SantanderPixAutomaticoData,
+ api_models::payments::PixAutomaticoCitData,
+ api_models::payments::PixAutomaticoMitData,
+ api_models::payments::SantanderPixAutomaticoReceiverDetails,
api_models::payments::BoletoPaymentTypeConstraints,
api_models::payments::BeneficiaryDetails,
api_models::payments::InterestDetail,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index b024cf6a98..1fc714fca0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4540,7 +4540,7 @@ where
&call_connector_action,
);
- // AuthorizeSessionTokenFlow needs access token to be added in router data before creating session token, as the session token creation might require access token in headers for some connectors (like Santander)
+ // AuthorizeSessionTokenFlow needs access token to be added in router data before creating session token, as the session token creation might require access token in headers for some connectors(like Santander)
router_data
.add_session_token(state, &connector, &context)
.await?;
@@ -4759,13 +4759,14 @@ where
.await?;
*payment_data = new_payment_data;
- let mut router_data = call_connector_service_response.router_data;
+ let router_data = call_connector_service_response.router_data;
let gateway_context = call_connector_service_response.gateway_context;
let router_data = if call_connector_service_response.should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
+ let mut router_data = router_data;
router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
@@ -4774,7 +4775,7 @@ where
call_connector_action,
call_connector_service_response.connector_request,
business_profile,
- header_payload,
+ header_payload.clone(),
return_raw_connector_response,
gateway_context.clone(),
)
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index 041595292c..f16e1e953a 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -170,13 +170,16 @@ impl Feature<api::PSync, types::PaymentsSyncData>
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
+ let current_flow = Some(hyperswitch_interfaces::api::CurrentFlowInfo::Psync {
+ request_data: Box::new(self.request.clone()),
+ });
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
- None,
+ current_flow,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 10d2b5b1e8..1af6b13b5f 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -453,8 +453,13 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
connector.connector_name
);
let setup_mandate_request_data = self.request.clone();
- let generate_qr_request_data =
+ let mut generate_qr_request_data =
types::GenerateQrRequestData::try_from(self.request.to_owned())?;
+ // Extract mandate_id from SetupMandate response and populate it in GenerateQRRequestData
+ helpers::update_request_data_with_mandate_id(
+ &mut generate_qr_request_data,
+ &self.response,
+ );
let generate_qr_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
@@ -515,8 +520,13 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
connector.connector_name
);
let setup_mandate_request_data = self.request.clone();
- let push_notification_request_data =
+ let mut push_notification_request_data =
types::PushNotificationRequestData::try_from(self.request.to_owned())?;
+ // Extract mandate_id from SetupMandate response and populate it in PushNotificationRequestData
+ helpers::update_request_data_with_mandate_id(
+ &mut push_notification_request_data,
+ &self.response,
+ );
let push_notification_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1f06b3349b..3b98c34b12 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -48,6 +48,7 @@ use hyperswitch_domain_models::{
payment_intent::PaymentIntentFetchConstraints, PaymentIntent,
},
router_data::{InteracCustomerInfo, KlarnaSdkResponse, PaymentMethodToken},
+ router_request_types::MandateIdSettable,
};
pub use hyperswitch_interfaces::{
api::ConnectorSpecifications,
@@ -9143,3 +9144,36 @@ pub fn get_merchant_advice_code_recommended_action(
_ => None,
}
}
+
+// Update request data with mandate_id received from SetupMandate router response.
+// Mandate information is needed in consecutive flows (e.g., PaymentTrigger, GenerateQR)
+// triggered after successful completion of the SetupMandate flow.
+pub fn update_request_data_with_mandate_id(
+ request_data: &mut impl MandateIdSettable,
+ setup_mandate_response: &Result<PaymentsResponseData, ErrorResponse>,
+) {
+ if let Ok(PaymentsResponseData::TransactionResponse {
+ mandate_reference, ..
+ }) = setup_mandate_response
+ {
+ if let Some(mandate_ref) = mandate_reference.as_ref() {
+ if let Some(connector_mandate_id) = &mandate_ref.connector_mandate_id {
+ request_data.set_mandate_id(api_models::payments::MandateIds {
+ mandate_id: Some(connector_mandate_id.clone()),
+ mandate_reference_id: Some(
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ api_models::payments::ConnectorMandateReferenceId::new(
+ Some(connector_mandate_id.clone()),
+ None,
+ None,
+ None,
+ None,
+ None,
+ ),
+ ),
+ ),
+ });
+ }
+ }
+ }
+}
diff --git a/crates/router/src/core/payments/session_token.rs b/crates/router/src/core/payments/session_token.rs
index c0da3b02f4..b951bfe037 100644
--- a/crates/router/src/core/payments/session_token.rs
+++ b/crates/router/src/core/payments/session_token.rs
@@ -55,7 +55,7 @@ where
.map_err(|error| {
logger::error!(session_token_create_error = error.reason);
report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "Faied to perform session token call".to_string()
+ message: "Failed to perform session token call".to_string()
})
})
.attach_printable(format!(
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 1344f52b42..e6c67a67c3 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1580,6 +1580,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>(
partner_merchant_identifier_details: None,
authentication_data: None,
feature_metadata: None,
+ connector_intent_metadata: None,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
@@ -4564,6 +4565,10 @@ pub fn bank_transfer_next_steps_check(
payment_attempt.payment_method
{
if payment_attempt.payment_method_type != Some(diesel_models::enums::PaymentMethodType::Pix)
+ && payment_attempt.payment_method_type
+ != Some(diesel_models::enums::PaymentMethodType::PixAutomaticoQr)
+ && payment_attempt.payment_method_type
+ != Some(diesel_models::enums::PaymentMethodType::PixAutomaticoPush)
{
let bank_transfer_next_steps: Option<api_models::payments::BankTransferNextStepsData> =
payment_attempt
@@ -5195,7 +5200,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
},
encoded_data: payment_data.payment_attempt.encoded_data,
capture_method,
- connector_meta: payment_data.payment_attempt.connector_metadata,
+ connector_meta: payment_data.payment_attempt.connector_metadata.clone(),
sync_type: match payment_data.multiple_capture_data {
Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync(
multiple_capture_data.get_pending_connector_capture_ids(),
@@ -6191,6 +6196,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ
.attach_printable("Failed parsing FeatureMetadata")
})
.transpose()?,
+ connector_intent_metadata: payment_data
+ .payment_intent
+ .connector_metadata
+ .clone()
+ .map(|metadata| {
+ metadata
+ .parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed parsing ConnectorMetadata")
+ })
+ .transpose()?,
})
}
}
diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rs
index f9ea08a6ca..e2ed4564fe 100644
--- a/crates/router/src/workflows/payout_sync.rs
+++ b/crates/router/src/workflows/payout_sync.rs
@@ -96,8 +96,13 @@ impl ProcessTrackerWorkflow<SessionState> for PayoutSyncWorkFlow {
.change_context(core_errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
- payouts::create_payout_retrieve(state, &platform, &connector_data, &mut payout_data)
- .await?;
+ Box::pin(payouts::create_payout_retrieve(
+ state,
+ &platform,
+ &connector_data,
+ &mut payout_data,
+ ))
+ .await?;
let dimensions = configs::dimension_state::Dimensions::new()
.with_merchant_id(merchant_id.clone())