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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(connector): [SANTANDER] Implemented Pix and Boleto (#9937)
Sayak Bhattacharya0282a9321d5b
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex e95e8180b9..e12cf369d1 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -13057,6 +13057,71 @@}}},+ "BoletoAdditionalDetails": {+ "type": "object",+ "properties": {+ "due_date": {+ "type": "string",+ "description": "Due Date for the Boleto",+ "example": "2026-12-31",+ "nullable": true+ },+ "document_kind": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoDocumentKind"+ }+ ],+ "nullable": true+ },+ "payment_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoPaymentType"+ }+ ],+ "nullable": true+ },+ "covenant_code": {+ "type": "string",+ "example": "3568253",+ "nullable": true+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },+ "BoletoDocumentKind": {+ "type": "string",+ "enum": [+ "commercial_invoice",+ "service_invoice",+ "promissory_note",+ "rural_promissory_note",+ "receipt",+ "insurance_policy",+ "credit_card_invoice",+ "proposal",+ "deposit_or_funding",+ "cheque",+ "direct_promissory_note",+ "other"+ ]+ },+ "BoletoPaymentType": {+ "type": "string",+ "enum": [+ "fixed_amount",+ "flexible_amount",+ "installment"+ ]+ },"BoletoVoucherData": {"type": "object","properties": {@@ -13076,7 +13141,6 @@"$ref": "#/components/schemas/DocumentKind"}],- "default": "cnpj","nullable": true},"fine_percentage": {@@ -17805,6 +17869,27 @@"dispute_lost"]},+ "DocumentDetails": {+ "type": "object",+ "required": [+ "document_number"+ ],+ "properties": {+ "document_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/DocumentKind"+ }+ ],+ "nullable": true+ },+ "document_number": {+ "type": "string",+ "description": "Cpf or Cnpj number",+ "example": "20201210000155"+ }+ }+ },"DocumentKind": {"type": "string","description": "Represents the type of identification document used for validation.",@@ -18644,6 +18729,22 @@}],"nullable": true+ },+ "pix_additional_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixAdditionalDetails"+ }+ ],+ "nullable": true+ },+ "boleto_additional_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoAdditionalDetails"+ }+ ],+ "nullable": true}}},@@ -18889,6 +18990,28 @@}}},+ {+ "type": "object",+ "required": [+ "user_document_type"+ ],+ "properties": {+ "user_document_type": {+ "type": "object",+ "required": [+ "options"+ ],+ "properties": {+ "options": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ }+ }+ },{"type": "string","enum": [@@ -20454,6 +20577,28 @@"propertyName": "method_key"}},+ "ImmediateExpirationTime": {+ "type": "object",+ "required": [+ "time"+ ],+ "properties": {+ "time": {+ "type": "integer",+ "format": "int32",+ "description": "Expiration time in seconds",+ "minimum": 0+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },"IncrementalAuthorizationResponse": {"type": "object","required": [@@ -30752,6 +30897,14 @@"metadata": {"type": "object","description": "Metadata is useful for storing additional, unstructured information on an object."+ },+ "feature_metadata": {+ "allOf": [+ {+ "$ref": "#/components/schemas/FeatureMetadata"+ }+ ],+ "nullable": true}},"additionalProperties": false@@ -30759,7 +30912,8 @@"PaymentsUpdateMetadataResponse": {"type": "object","required": [- "payment_id"+ "payment_id",+ "status"],"properties": {"payment_id": {@@ -30770,6 +30924,22 @@"type": "object","description": "Metadata is useful for storing additional, unstructured information on an object.","nullable": true+ },+ "status": {+ "allOf": [+ {+ "$ref": "#/components/schemas/IntentStatus"+ }+ ],+ "default": "requires_confirmation"+ },+ "feature_metadata": {+ "allOf": [+ {+ "$ref": "#/components/schemas/FeatureMetadata"+ }+ ],+ "nullable": true}}},@@ -33089,6 +33259,32 @@}}},+ "PixAdditionalDetails": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "immediate"+ ],+ "properties": {+ "immediate": {+ "$ref": "#/components/schemas/ImmediateExpirationTime"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "scheduled"+ ],+ "properties": {+ "scheduled": {+ "$ref": "#/components/schemas/ScheduledExpirationTime"+ }+ }+ }+ ]+ },"PixBankTransfer": {"type": "object","required": [@@ -33168,6 +33364,103 @@}}},+ "PixKey": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "cpf"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "cnpj"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "email"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "phone"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "evp_token"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ }+ ],+ "discriminator": {+ "propertyName": "type"+ }+ },"PlatformAccountCreateRequest": {"type": "object","required": [@@ -36266,6 +36559,35 @@"transaction_risk_analysis"]},+ "ScheduledExpirationTime": {+ "type": "object",+ "required": [+ "date"+ ],+ "properties": {+ "date": {+ "type": "string",+ "description": "Expiration time in terms of date, format: YYYY-MM-DD",+ "example": "2026-07-08"+ },+ "validity_after_expiration": {+ "type": "integer",+ "format": "int32",+ "description": "Days after expiration date for which the QR code remains valid",+ "example": 10,+ "nullable": true,+ "minimum": 0+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },"SdkDisplayMode": {"type": "string","description": "Display mode options for controlling how messages are shown.",diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex c721d7b56c..39369ab529 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -8990,6 +8990,71 @@}}},+ "BoletoAdditionalDetails": {+ "type": "object",+ "properties": {+ "due_date": {+ "type": "string",+ "description": "Due Date for the Boleto",+ "example": "2026-12-31",+ "nullable": true+ },+ "document_kind": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoDocumentKind"+ }+ ],+ "nullable": true+ },+ "payment_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoPaymentType"+ }+ ],+ "nullable": true+ },+ "covenant_code": {+ "type": "string",+ "example": "3568253",+ "nullable": true+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },+ "BoletoDocumentKind": {+ "type": "string",+ "enum": [+ "commercial_invoice",+ "service_invoice",+ "promissory_note",+ "rural_promissory_note",+ "receipt",+ "insurance_policy",+ "credit_card_invoice",+ "proposal",+ "deposit_or_funding",+ "cheque",+ "direct_promissory_note",+ "other"+ ]+ },+ "BoletoPaymentType": {+ "type": "string",+ "enum": [+ "fixed_amount",+ "flexible_amount",+ "installment"+ ]+ },"BoletoVoucherData": {"type": "object","properties": {@@ -9009,7 +9074,6 @@"$ref": "#/components/schemas/DocumentKind"}],- "default": "cnpj","nullable": true},"fine_percentage": {@@ -12759,6 +12823,27 @@"dispute_lost"]},+ "DocumentDetails": {+ "type": "object",+ "required": [+ "document_number"+ ],+ "properties": {+ "document_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/DocumentKind"+ }+ ],+ "nullable": true+ },+ "document_number": {+ "type": "string",+ "description": "Cpf or Cnpj number",+ "example": "20201210000155"+ }+ }+ },"DocumentKind": {"type": "string","description": "Represents the type of identification document used for validation.",@@ -13493,6 +13578,22 @@}],"nullable": true+ },+ "pix_additional_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixAdditionalDetails"+ }+ ],+ "nullable": true+ },+ "boleto_additional_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BoletoAdditionalDetails"+ }+ ],+ "nullable": true}}},@@ -13738,6 +13839,28 @@}}},+ {+ "type": "object",+ "required": [+ "user_document_type"+ ],+ "properties": {+ "user_document_type": {+ "type": "object",+ "required": [+ "options"+ ],+ "properties": {+ "options": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ }+ }+ },{"type": "string","enum": [@@ -15327,6 +15450,28 @@"propertyName": "method_key"}},+ "ImmediateExpirationTime": {+ "type": "object",+ "required": [+ "time"+ ],+ "properties": {+ "time": {+ "type": "integer",+ "format": "int32",+ "description": "Expiration time in seconds",+ "minimum": 0+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },"IncrementalAuthorizationResponse": {"type": "object","required": [@@ -24854,6 +24999,32 @@}}},+ "PixAdditionalDetails": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "immediate"+ ],+ "properties": {+ "immediate": {+ "$ref": "#/components/schemas/ImmediateExpirationTime"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "scheduled"+ ],+ "properties": {+ "scheduled": {+ "$ref": "#/components/schemas/ScheduledExpirationTime"+ }+ }+ }+ ]+ },"PixBankTransfer": {"type": "object","required": [@@ -24933,6 +25104,103 @@}}},+ "PixKey": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "cpf"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "cnpj"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "email"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "phone"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ },+ {+ "type": "object",+ "required": [+ "type",+ "value"+ ],+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "evp_token"+ ]+ },+ "value": {+ "type": "string"+ }+ }+ }+ ],+ "discriminator": {+ "propertyName": "type"+ }+ },"PollConfig": {"type": "object","required": [@@ -27572,6 +27840,35 @@"transaction_risk_analysis"]},+ "ScheduledExpirationTime": {+ "type": "object",+ "required": [+ "date"+ ],+ "properties": {+ "date": {+ "type": "string",+ "description": "Expiration time in terms of date, format: YYYY-MM-DD",+ "example": "2026-07-08"+ },+ "validity_after_expiration": {+ "type": "integer",+ "format": "int32",+ "description": "Days after expiration date for which the QR code remains valid",+ "example": 10,+ "nullable": true,+ "minimum": 0+ },+ "pix_key": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PixKey"+ }+ ],+ "nullable": true+ }+ }+ },"SdkDisplayMode": {"type": "string","description": "Display mode options for controlling how messages are shown.",diff --git a/config/config.example.toml b/config/config.example.tomlindex 1d6f36caa9..ce2aae6ef3 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -310,8 +310,8 @@ razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"riskified.base_url = "https://sandbox.riskified.com/api"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -962,6 +962,7 @@ apple_pay = { country = "AU,NZ,CN,HK,JP,SG,MY,KR,TW,VN,GB,IE,FR,DE,IT,ES,PT,NL,B[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]calida = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex ab1ef81995..b3d8844bb5 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -135,8 +135,8 @@ rapyd.base_url = "https://sandboxapi.rapyd.net"razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -852,6 +852,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }diff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 98f2fb7520..e3c3493ef0 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -140,7 +140,7 @@ recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis.redsys.es"riskified.base_url = "https://wh.riskified.com/api/"santander.base_url = "https://trust-pix.santander.com.br/"-santander.secondary_base_url = "https://trust-open.api.santander.com.br/collection_bill_management/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api.silverflow.co/v1"@@ -841,6 +841,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex 49fd108ee3..d2b35e4e74 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -139,8 +139,8 @@ razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"riskified.base_url = "https://sandbox.riskified.com/api"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -853,6 +853,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }diff --git a/config/development.toml b/config/development.tomlindex 33a725336c..d73dee6742 100644--- a/config/development.toml+++ b/config/development.toml@@ -340,8 +340,8 @@ razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"riskified.base_url = "https://sandbox.riskified.com/api"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -1018,6 +1018,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.boku]dana = { country = "ID", currency = "IDR" }diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 98330a99ef..2380db34b9 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -241,8 +241,8 @@ razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"riskified.base_url = "https://sandbox.riskified.com/api"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -985,6 +985,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 027b95e8a9..e517dd12e1 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -294,6 +294,7 @@ pub enum FieldType {UserShippingAddressPincode,UserShippingAddressState,UserShippingAddressCountry { options: Vec<String> },+ UserDocumentType { options: Vec<String> },UserSocialSecurityNumber,UserBlikCode,UserBank,diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 92a7efe2bf..a6807d2e54 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -14,7 +14,9 @@ use common_enums::{GooglePayCardFundingSource, ProductType};use common_types::primitive_wrappers::{ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool,};-use common_types::{payments as common_payments_types, primitive_wrappers};+use common_types::{+ customers::DocumentKind, payments as common_payments_types, primitive_wrappers,+};use common_utils::{consts::default_payments_list_limit,crypto,@@ -4884,6 +4886,29 @@ pub enum BankTransferData {},}+#[derive(+ Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,+)]+#[serde(rename_all = "snake_case")]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct DocumentDetails {+ /// Specifies the type of document - Cpf or Cnpj+ #[schema(value_type = Option<DocumentKind>, example = "cnpj")]+ pub document_type: DocumentKind,+ /// Cpf or Cnpj number+ #[schema(value_type = String, example = "20201210000155")]+ pub document_number: Secret<String>,+}++impl DocumentDetails {+ pub fn get_cpf_cnpj_split(&self) -> (Option<Secret<String>>, Option<Secret<String>>) {+ match self.document_type {+ DocumentKind::Cpf => (Some(self.document_number.clone()), None),+ DocumentKind::Cnpj => (None, Some(self.document_number.clone())),+ }+ }+}+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel,)]@@ -5757,9 +5782,9 @@ pub struct BoletoVoucherData {pub bank_number: Option<Secret<String>>,/// The type of identification document used (e.g., CPF or CNPJ)- #[schema(value_type = Option<DocumentKind>, example = "cpf", default = "cnpj")]+ #[schema(value_type = Option<DocumentKind>, example = "cpf")]#[smithy(value_type = "Option<DocumentKind>")]- pub document_type: Option<common_types::customers::DocumentKind>,+ pub document_type: Option<DocumentKind>,/// The fine percentage charged if payment is overdue#[schema(value_type = Option<String>)]@@ -6807,6 +6832,7 @@ pub enum QrCodeInformation {image_data_url: Url,qr_code_url: Url,display_to_timestamp: Option<i64>,+ expiry_type: Option<common_enums::enums::ExpiryType>,},QrDataUrl {image_data_url: Url,@@ -6870,6 +6896,9 @@ pub struct VoucherNextStepData {/// Voucher expiry date and time#[smithy(value_type = "Option<i64>")]pub expires_at: Option<i64>,+ /// Voucher expiry date and time+ #[smithy(value_type = "Option<String>")]+ pub expiry_date: Option<PrimitiveDateTime>,/// Reference number required for the transaction#[smithy(value_type = "String")]pub reference: String,@@ -6882,6 +6911,13 @@ pub struct VoucherNextStepData {/// Human-readable numeric version of the barcode.#[smithy(value_type = "Option<String>")]pub digitable_line: Option<Secret<String>>,+ /// Machine-readable numeric code used to generate the barcode representation.+ #[smithy(value_type = "Option<String>")]+ pub barcode: Option<Secret<String>>,+ /// The url for Pix Qr code given by the connector associated with the voucher+ #[schema(value_type = Option<String>)]+ #[smithy(value_type = "Option<String>")]+ pub qr_code_url: Option<Url>,}#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]@@ -7436,7 +7472,7 @@ pub struct PaymentsResponse {/// Additional data that might be required by hyperswitch, to enable some specific features.#[schema(value_type = Option<FeatureMetadata>)]#[smithy(value_type = "Option<FeatureMetadata>")]- pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated+ pub feature_metadata: Option<FeatureMetadata>,/// reference(Identifier) to the payment at connector side#[schema(value_type = Option<String>, example = "993672945374576J")]@@ -9463,7 +9499,10 @@ pub struct PaymentsUpdateMetadataRequest {pub payment_id: id_type::PaymentId,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Object, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]- pub metadata: pii::SecretSerdeValue,+ pub metadata: Option<pii::SecretSerdeValue>,+ /// Additional data that might be required by hyperswitch based on the requested features by the merchants.+ #[schema(value_type = Option<FeatureMetadata>)]+ pub feature_metadata: Option<FeatureMetadata>,}#[derive(Debug, serde::Serialize, Clone, ToSchema)]@@ -9474,6 +9513,13 @@ pub struct PaymentsUpdateMetadataResponse {/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]pub metadata: Option<pii::SecretSerdeValue>,+ /// The status of the payment intent after the metadata update+ #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")]+ pub status: api_enums::IntentStatus,+ /// Additional data that might be required by hyperswitch, to enable some specific features.+ #[schema(value_type = Option<FeatureMetadata>)]+ #[schema(value_type = Option<FeatureMetadata>)]+ pub feature_metadata: Option<FeatureMetadata>,}#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]@@ -11274,6 +11320,10 @@ pub struct FeatureMetadata {pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,/// revenue recovery data for payment intentpub revenue_recovery: Option<PaymentRevenueRecoveryMetadata>,+ /// Pix QR Code expiry time for Merchants+ pub pix_additional_details: Option<PixAdditionalDetails>,+ /// Extra information like fine percentage, interest percentage etc required for Pix payment method+ pub boleto_additional_details: Option<BoletoAdditionalDetails>,}#[cfg(feature = "v2")]@@ -11283,7 +11333,12 @@ impl FeatureMetadata {.as_ref().map(|metadata| metadata.total_retry_count)}-+ /// Helper to extract the optional covenant_code from boleto details+ pub fn get_optional_boleto_covenant_code(&self) -> Option<Secret<String>> {+ self.boleto_additional_details+ .as_ref()+ .and_then(|boleto| boleto.covenant_code.clone())+ }pub fn set_payment_revenue_recovery_metadata_using_api(self,payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata,@@ -11293,13 +11348,39 @@ impl FeatureMetadata {search_tags: self.search_tags,apple_pay_recurring_details: self.apple_pay_recurring_details,revenue_recovery: Some(payment_revenue_recovery_metadata),+ pix_additional_details: self.pix_additional_details,+ boleto_additional_details: self.boleto_additional_details,}}+ /// Extracts the Pix key and its secret value specifically from PixAdditionalDetails+ pub fn get_pix_key_and_value(&self) -> (Option<enums::PixKey>, Option<Secret<String>>) {+ let pix_key = self+ .pix_additional_details+ .as_ref()+ .and_then(|pix| match pix {+ PixAdditionalDetails::Immediate(imm) => imm.pix_key.clone(),+ PixAdditionalDetails::Scheduled(sch) => sch.pix_key.clone(),+ });+ let value = pix_key.as_ref().map(|pk| pk.get_inner_value());++ (pix_key, value)+ }+ /// Extracts the Pix key and its secret value specifically from BoletoAdditionalDetails+ pub fn get_boleto_pix_key_and_value(&self) -> (Option<enums::PixKey>, Option<Secret<String>>) {+ let pix_key = self+ .boleto_additional_details+ .as_ref()+ .and_then(|boleto| boleto.pix_key.clone());++ let value = pix_key.as_ref().map(|pk| pk.get_inner_value());++ (pix_key, value)+ }}/// additional data that might be required by hyperswitch#[cfg(feature = "v1")]-#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel)]+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel, PartialEq)]#[smithy(namespace = "com.hyperswitch.smithy.types")]pub struct FeatureMetadata {/// Redirection response coming in request as metadata field only for redirection scenarios@@ -11313,9 +11394,155 @@ pub struct FeatureMetadata {/// Recurring payment details required for apple pay Merchant Token#[smithy(value_type = "Option<ApplePayRecurringDetails>")]pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,+ /// Extra information for Pix Payment Method Type like fine expiry, pix key etc+ #[smithy(value_type = "Option<PixAdditionalDetails>")]+ pub pix_additional_details: Option<PixAdditionalDetails>,+ /// Extra information like fine percentage, interest percentage etc required for Pix payment method+ #[smithy(value_type = "Option<BoletoAdditionalDetails>")]+ pub boleto_additional_details: Option<BoletoAdditionalDetails>,+}+#[cfg(feature = "v1")]+impl FeatureMetadata {+ /// Helper to extract the optional covenant_code from boleto details+ pub fn get_optional_boleto_covenant_code(&self) -> Option<Secret<String>> {+ self.boleto_additional_details+ .as_ref()+ .and_then(|boleto| boleto.covenant_code.clone())+ }+ pub fn merge(self, other: Option<Self>) -> Self {+ if let Some(other) = other {+ Self {+ redirect_response: self.redirect_response.or(other.redirect_response),+ search_tags: self.search_tags.or(other.search_tags),+ apple_pay_recurring_details: self+ .apple_pay_recurring_details+ .or(other.apple_pay_recurring_details),+ pix_additional_details: self+ .pix_additional_details+ .or(other.pix_additional_details),++ boleto_additional_details: BoletoAdditionalDetails::merge_optional(+ self.boleto_additional_details,+ other.boleto_additional_details,+ ),+ }+ } else {+ self+ }+ }+ /// Extracts the Pix key and its secret value specifically from PixAdditionalDetails+ pub fn get_pix_key_and_value(&self) -> (Option<enums::PixKey>, Option<Secret<String>>) {+ let pix_key = self+ .pix_additional_details+ .as_ref()+ .and_then(|pix| match pix {+ PixAdditionalDetails::Immediate(imm) => imm.pix_key.clone(),+ PixAdditionalDetails::Scheduled(sch) => sch.pix_key.clone(),+ });+ let value = pix_key.as_ref().map(|pk| pk.get_inner_value());++ (pix_key, value)+ }+ /// Extracts the Pix key and its secret value specifically from BoletoAdditionalDetails+ pub fn get_boleto_pix_key_and_value(&self) -> (Option<enums::PixKey>, Option<Secret<String>>) {+ let pix_key = self+ .boleto_additional_details+ .as_ref()+ .and_then(|boleto| boleto.pix_key.clone());++ let value = pix_key.as_ref().map(|pk| pk.get_inner_value());++ (pix_key, value)+ }+}++#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]+pub struct BoletoAdditionalDetails {+ /// Due Date for the Boleto+ #[schema(value_type = Option<String>, example="2026-12-31")]+ #[serde(default, with = "common_utils::custom_serde::date_only_optional")]+ pub due_date: Option<PrimitiveDateTime>,+ // It tells the bank what type of commercial document created the boleto. Why does this boleto exist? What kind of transaction or contract caused it?+ #[schema(value_type = Option<BoletoDocumentKind>, example="commercial_invoice")]+ pub document_kind: Option<common_enums::enums::BoletoDocumentKind>,+ // This field tells the bank how the boleto can be paid — whether the payer must pay the exact amount, can pay a different amount, or pay in parts.+ #[schema(value_type = Option<BoletoPaymentType>, example="fixed_amount")]+ pub payment_type: Option<common_enums::enums::BoletoPaymentType>,+ // It is a number which shows a contract between merchant and bank+ #[schema(value_type = Option<String>, example="3568253")]+ pub covenant_code: Option<Secret<String>>,+ /// Pix identification details+ #[schema(+ value_type = Option<PixKey>, example = json!({+ "type": "email",+ "value": "[email protected]"+ })+ )]+ pub pix_key: Option<enums::PixKey>,}-#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel)]+impl BoletoAdditionalDetails {+ pub fn merge(self, other: Self) -> Self {+ Self {+ due_date: self.due_date.or(other.due_date),+ document_kind: self.document_kind.or(other.document_kind),+ payment_type: self.payment_type.or(other.payment_type),+ covenant_code: self.covenant_code.or(other.covenant_code),+ pix_key: self.pix_key.or(other.pix_key),+ }+ }++ pub fn merge_optional(left: Option<Self>, right: Option<Self>) -> Option<Self> {+ match (left, right) {+ (Some(l), Some(r)) => Some(l.merge(r)),+ (l, r) => l.or(r),+ }+ }+}++#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]+pub enum PixAdditionalDetails {+ #[serde(rename = "immediate")]+ Immediate(ImmediateExpirationTime),+ #[serde(rename = "scheduled")]+ Scheduled(ScheduledExpirationTime),+}++#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct ImmediateExpirationTime {+ /// Expiration time in seconds+ #[schema(value_type = u32)]+ pub time: u32,+ /// Pix identification details+ #[schema(+ value_type = Option<PixKey>, example = json!({+ "type": "email",+ "value": "[email protected]"+ })+ )]+ pub pix_key: Option<enums::PixKey>,+}++#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct ScheduledExpirationTime {+ /// Expiration time in terms of date, format: YYYY-MM-DD+ #[schema(value_type = String, example="2026-07-08")]+ #[serde(with = "common_utils::custom_serde::date_only")]+ pub date: PrimitiveDateTime,+ /// Days after expiration date for which the QR code remains valid+ #[schema(value_type = Option<u32>, example=10)]+ pub validity_after_expiration: Option<u32>,+ /// Pix identification details+ #[schema(+ value_type = Option<PixKey>, example = json!({+ "type": "email",+ "value": "[email protected]"+ })+ )]+ pub pix_key: Option<enums::PixKey>,+}++#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel, PartialEq)]#[smithy(namespace = "com.hyperswitch.smithy.types")]pub struct ApplePayRecurringDetails {/// A description of the recurring payment that Apple Pay displays to the user in the payment sheet@@ -11333,7 +11560,7 @@ pub struct ApplePayRecurringDetails {pub management_url: common_utils::types::Url,}-#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel)]+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, SmithyModel, PartialEq)]#[smithy(namespace = "com.hyperswitch.smithy.types")]pub struct ApplePayRegularBillingDetails {/// The label that Apple Pay displays to the user in the payment sheet with the recurring details@@ -12659,3 +12886,22 @@ pub struct CartesBancairesParams {#[schema(value_type = i32)]pub cb_score: i32,}++impl PaymentsUpdateMetadataRequest {+ /// Helper function to validate that at least one of `metadata` or `feature_metadata` is present in the request+ pub fn validate(&self) -> common_utils::errors::CustomResult<(), ValidationError> {+ let Self {+ metadata,+ feature_metadata,+ payment_id: _,+ } = self;++ if metadata.is_none() && feature_metadata.is_none() {+ return Err(ValidationError::MissingRequiredField {+ field_name: "metadata or feature_metadata".to_string(),+ }+ .into());+ }+ Ok(())+ }+}diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rsindex 8ad0a259d2..80ef5f695e 100644--- a/crates/common_enums/src/connector_enums.rs+++ b/crates/common_enums/src/connector_enums.rs@@ -260,6 +260,7 @@ impl Connector {| (Self::Itaubank, _)| (Self::Facilitapay, _)| (Self::Dwolla, _)+ | (Self::Santander, _))}pub fn requires_order_creation_before_payment(self, payment_method: PaymentMethod) -> bool {diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 5aec815aae..fcf7bf85db 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -18,6 +18,7 @@ use diesel::{serialize::{Output, ToSql},sql_types::Text,};+use masking::Secret;pub use payments::ProductType;use serde::{de, Deserialize, Deserializer, Serialize, Serializer};use smithy::SmithyModel;@@ -10587,3 +10588,105 @@ pub enum RoutingRegion {Region1,Region2,}++#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ PartialEq,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum BoletoDocumentKind {+ /// Commercial invoice for goods/products+ CommercialInvoice,+ /// Service invoice+ ServiceInvoice,+ /// Standard promissory note (promise to pay later)+ PromissoryNote,+ /// Promissory note for rural/agricultural operations+ RuralPromissoryNote,+ /// Payment receipt+ Receipt,+ /// Insurance policy payment+ InsurancePolicy,+ /// Credit card statement / invoice payment+ CreditCardInvoice,+ /// Commercial proposal / quotation acceptance+ Proposal,+ /// Deposit or account funding (e.g. wallet top-up)+ DepositOrFunding,+ /// Cheque-based payment+ Cheque,+ /// Direct promissory note between parties+ DirectPromissoryNote,+ /// Any other document type+ Other,+}++#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ PartialEq,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum BoletoPaymentType {+ /// Only the exact nominal amount can be paid.+ FixedAmount,+ /// The payer may pay any amount within an allowed minimum–maximum range.+ FlexibleAmount,+ /// The payer may make up to 99 partial payments.+ Installment,+}++#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ExpiryType {+ Immediate,+ Scheduled,+}++#[derive(+ Debug, Clone, PartialEq, Eq, Deserialize, Serialize, diesel::FromSqlRow, AsExpression, ToSchema,+)]+#[diesel(sql_type = diesel::sql_types::Json)]+#[serde(tag = "type", content = "value", rename_all = "snake_case")]+pub enum PixKey {+ #[schema(value_type = String)]+ Cpf(Secret<String>),+ #[schema(value_type = String)]+ Cnpj(Secret<String>),+ #[schema(value_type = String)]+ Email(Secret<String>),+ #[schema(value_type = String)]+ Phone(Secret<String>),+ #[schema(value_type = String)]+ EvpToken(Secret<String>),+}++/// Helper extension for PixKey to extract the secret value regardless of variant+impl PixKey {+ pub fn get_inner_value(&self) -> Secret<String> {+ match self {+ Self::Cpf(val)+ | Self::Cnpj(val)+ | Self::Email(val)+ | Self::Phone(val)+ | Self::EvpToken(val) => val.clone(),+ }+ }+}diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rsindex 06087f082e..0f52448dec 100644--- a/crates/common_utils/src/custom_serde.rs+++ b/crates/common_utils/src/custom_serde.rs@@ -295,3 +295,75 @@ mod tests {assert!(deser.is_ok())}}++/// Use only the date part of a [`PrimitiveDateTime`] when serializing and deserializing.+pub mod date_only {+ use serde::{de, Deserialize, Deserializer, Serialize, Serializer};+ use time::{Date, PrimitiveDateTime, Time};++ /// Serialize a [`PrimitiveDateTime`] as a YYYY-MM-DD string.+ pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ let date = date_time.date();+ // Format: 2026-09-10+ format!(+ "{}-{:02}-{:02}",+ date.year(),+ u8::from(date.month()),+ date.day()+ )+ .serialize(serializer)+ }++ /// Deserialize a [`PrimitiveDateTime`] from a YYYY-MM-DD string.+ pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>+ where+ D: Deserializer<'a>,+ {+ // 1. Deserialize into a Date object (handles YYYY-MM-DD)+ let date = Date::deserialize(deserializer)+ .map_err(|e| de::Error::custom(format!("Failed to parse Date (YYYY-MM-DD): {e}")))?;++ // 2. Combine with midnight time to create PrimitiveDateTime+ let time = Time::MIDNIGHT;+ Ok(PrimitiveDateTime::new(date, time))+ }+}++/// Use only the date part of an [`Option<PrimitiveDateTime>`] when serializing and deserializing.+pub mod date_only_optional {+ use serde::{Deserialize, Deserializer, Serializer}; // Added Deserialize here+ use time::PrimitiveDateTime;++ use super::date_only;++ /// Serialize an [`Option<PrimitiveDateTime>`] as a YYYY-MM-DD string or null.+ pub fn serialize<S>(+ date_time: &Option<PrimitiveDateTime>,+ serializer: S,+ ) -> Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ match date_time {+ Some(dt) => date_only::serialize(dt, serializer),+ None => serializer.serialize_none(),+ }+ }++ /// Deserialize an [`Option<PrimitiveDateTime>`] from a YYYY-MM-DD string or null.+ pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>+ where+ D: Deserializer<'a>,+ {+ // Use Option's built-in wrapper, but tell it to use our+ // specific date_only logic for the inner value+ #[derive(serde::Deserialize)]+ struct Helper(#[serde(with = "date_only")] PrimitiveDateTime);++ let helper = Option::<Helper>::deserialize(deserializer)?;+ Ok(helper.map(|h| h.0))+ }+}diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rsindex 89c0158ce7..31a732b7d2 100644--- a/crates/connector_configs/src/connector.rs+++ b/crates/connector_configs/src/connector.rs@@ -150,6 +150,8 @@ pub struct ConfigMetadata {pub terminal_id: Option<InputData>,pub google_pay: Option<Vec<InputData>>,pub apple_pay: Option<Vec<InputData>>,+ pub pix: Option<Vec<InputData>>,+ pub boleto: Option<Vec<InputData>>,pub merchant_id: Option<InputData>,pub endpoint_prefix: Option<InputData>,pub mcc: Option<InputData>,diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.tomlindex d251609003..5411db9deb 100644--- a/crates/connector_configs/toml/development.toml+++ b/crates/connector_configs/toml/development.toml@@ -7051,58 +7051,84 @@ type="Select"options=[][santander]-[[santander.voucher]]- payment_method_type = "boleto"[[santander.bank_transfer]]- payment_method_type = "pix"--[santander.connector_auth.BodyKey]-api_key="Client ID"-key1="Client Secret"--[santander.metadata.pix_key]-name="pix_key"-label="Chave Key"-placeholder="Enter your Chave/Pix Key"+payment_method_type = "pix"+[[santander.voucher]]+payment_method_type = "boleto"+[santander.connector_auth.CertificateAuth]+certificate="Base64 encoded PEM formatted certificate chain"+private_key="Base64 encoded PEM formatted private key"++[[santander.metadata.pix]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"required=truetype="Text"--[santander.metadata.expiration_time]-name="expiration_time"-label="Expiration Time"-placeholder="Enter your Pix QR Code Expiration Time"+[[santander.metadata.pix]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"required=true-type="Number"--[santander.metadata.cpf]-name="cpf"-label="Cpf"-placeholder="Enter your cpf number"+type="Text"+[[santander.metadata.pix]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=true+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.pix]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"required=truetype="Text"--[santander.metadata.merchant_city]+[[santander.metadata.pix]]name="merchant_city"label="Merchant City"placeholder="Enter the city the merchant is based in"required=truetype="Text"--[santander.metadata.merchant_name]+[[santander.metadata.pix]]name="merchant_name"label="Merchant Name"placeholder="Enter the merchant name"required=truetype="Text"-[santander.metadata.workspace_id]+[[santander.metadata.boleto]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"+required=true+type="Text"+[[santander.metadata.boleto]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"+required=true+type="Text"+[[santander.metadata.boleto]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=false+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.boleto]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"+required=false+type="Text"+[[santander.metadata.boleto]]name="workspace_id"label="Workspace Id"placeholder="Enter the workspace id"required=truetype="Text"--[santander.metadata.covenant_code]+[[santander.metadata.boleto]]name="covenant_code"label="Covenant Code"placeholder="Enter the covenant code"diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.tomlindex 330da3843d..826ae31f6b 100644--- a/crates/connector_configs/toml/production.toml+++ b/crates/connector_configs/toml/production.toml@@ -5893,59 +5893,85 @@ placeholder = "Enter Acquirer Country Code"required = falsetype = "Text"-[santander]-[[santander.voucher]]- payment_method_type = "boleto"[[santander.bank_transfer]]- payment_method_type = "pix"-[santander.connector_auth.BodyKey]-api_key = "Client ID"-key1 = "Client Secret"--[santander.metadata.pix_key]-name = "pix_key"-label = "Chave Key"-placeholder = "Enter your Chave/Pix Key"-required = true-type = "Text"--[santander.metadata.expiration_time]-name = "expiration_time"-label = "Expiration Time"-placeholder = "Enter your Pix QR Code Expiration Time"-required = true-type = "Number"--[santander.metadata.cpf]-name = "cpf"-label = "Cpf"-placeholder = "Enter your cpf number"-required = true-type = "Text"--[santander.metadata.merchant_city]-name = "merchant_city"-label = "Merchant City"-placeholder = "Enter the city the merchant is based in"-required = true-type = "Text"--[santander.metadata.merchant_name]-name = "merchant_name"-label = "Merchant Name"-placeholder = "Enter the merchant name"-required = true-type = "Text"+payment_method_type = "pix"+[[santander.voucher]]+payment_method_type = "boleto"+[santander.connector_auth.CertificateAuth]+certificate="Base64 encoded PEM formatted certificate chain"+private_key="Base64 encoded PEM formatted private key"++[[santander.metadata.pix]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"+required=true+type="Text"+[[santander.metadata.pix]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"+required=true+type="Text"+[[santander.metadata.pix]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=true+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.pix]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"+required=true+type="Text"+[[santander.metadata.pix]]+name="merchant_city"+label="Merchant City"+placeholder="Enter the city the merchant is based in"+required=true+type="Text"+[[santander.metadata.pix]]+name="merchant_name"+label="Merchant Name"+placeholder="Enter the merchant name"+required=true+type="Text"-[santander.metadata.workspace_id]+[[santander.metadata.boleto]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"+required=true+type="Text"+[[santander.metadata.boleto]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"+required=true+type="Text"+[[santander.metadata.boleto]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=false+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.boleto]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"+required=false+type="Text"+[[santander.metadata.boleto]]name="workspace_id"label="Workspace Id"placeholder="Enter the workspace id"required=truetype="Text"--[santander.metadata.covenant_code]+[[santander.metadata.boleto]]name="covenant_code"label="Covenant Code"placeholder="Enter the covenant code"diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.tomlindex cf6f1cc568..fbef396c13 100644--- a/crates/connector_configs/toml/sandbox.toml+++ b/crates/connector_configs/toml/sandbox.toml@@ -7028,58 +7028,84 @@ type = "Select"options = [][santander]-[[santander.voucher]]- payment_method_type = "boleto"[[santander.bank_transfer]]- payment_method_type = "pix"--[santander.connector_auth.BodyKey]-api_key = "Client ID"-key1 = "Client Secret"--[santander.metadata.pix_key]-name = "pix_key"-label = "Chave Key"-placeholder = "Enter your Chave/Pix Key"-required = true-type = "Text"--[santander.metadata.expiration_time]-name = "expiration_time"-label = "Expiration Time"-placeholder = "Enter your Pix QR Code Expiration Time"-required = true-type = "Number"--[santander.metadata.cpf]-name = "cpf"-label = "Cpf"-placeholder = "Enter your cpf number"-required = true-type = "Text"--[santander.metadata.merchant_city]-name = "merchant_city"-label = "Merchant City"-placeholder = "Enter the city the merchant is based in"-required = true-type = "Text"--[santander.metadata.merchant_name]-name = "merchant_name"-label = "Merchant Name"-placeholder = "Enter the merchant name"-required = true-type = "Text"+payment_method_type = "pix"+[[santander.voucher]]+payment_method_type = "boleto"+[santander.connector_auth.CertificateAuth]+certificate="Base64 encoded PEM formatted certificate chain"+private_key="Base64 encoded PEM formatted private key"++[[santander.metadata.pix]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"+required=true+type="Text"+[[santander.metadata.pix]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"+required=true+type="Text"+[[santander.metadata.pix]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=true+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.pix]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"+required=true+type="Text"+[[santander.metadata.pix]]+name="merchant_city"+label="Merchant City"+placeholder="Enter the city the merchant is based in"+required=true+type="Text"+[[santander.metadata.pix]]+name="merchant_name"+label="Merchant Name"+placeholder="Enter the merchant name"+required=true+type="Text"-[santander.metadata.workspace_id]+[[santander.metadata.boleto]]+name="client_id"+label="Client ID"+placeholder="Enter your Client Id"+required=true+type="Text"+[[santander.metadata.boleto]]+name="client_secret"+label="Client Secret"+placeholder="Enter your Client Secret"+required=true+type="Text"+[[santander.metadata.boleto]]+name="pix_key_type"+label="Chave Key Type"+placeholder="Enter your Chave/Pix Key Type"+required=false+type="Select"+options=["CPF", "CNPJ", "EMAIL", "CELLULAR", "EVP"]+[[santander.metadata.boleto]]+name="pix_key_value"+label="Chave Key"+placeholder="Enter your Chave/Pix Key"+required=false+type="Text"+[[santander.metadata.boleto]]name="workspace_id"label="Workspace Id"placeholder="Enter the workspace id"required=truetype="Text"--[santander.metadata.covenant_code]+[[santander.metadata.boleto]]name="covenant_code"label="Covenant Code"placeholder="Enter the covenant code"diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex 647bd9d919..da3e640255 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -532,8 +532,9 @@ pub enum PaymentIntentUpdate {feature_metadata: Option<masking::Secret<serde_json::Value>>,},MetadataUpdate {- metadata: serde_json::Value,+ metadata: Option<serde_json::Value>,updated_by: String,+ feature_metadata: Option<masking::Secret<serde_json::Value>>,},Update(Box<PaymentIntentUpdateFields>),StateMetadataUpdate {@@ -1048,8 +1049,9 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {PaymentIntentUpdate::MetadataUpdate {metadata,updated_by,+ feature_metadata,} => Self {- metadata: Some(metadata),+ metadata,modified_at: common_utils::date_time::now(),updated_by,amount: None,@@ -1090,7 +1092,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {is_iframe_redirection_enabled: None,extended_return_url: None,payment_channel: None,- feature_metadata: None,+ feature_metadata,tax_status: None,discount_amount: None,order_date: None,diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rsindex b372c2dc23..590db3db0c 100644--- a/crates/diesel_models/src/types.rs+++ b/crates/diesel_models/src/types.rs@@ -71,6 +71,26 @@ pub struct FeatureMetadata {pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,/// revenue recovery data for payment intentpub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>,+ /// Additional information related to pix like expiry time etc for QR Code payments+ pub pix_additional_details: Option<PixAdditionalDetails>,+ /// Extra information like fine percentage, interest percentage etc required for Pix payment method+ pub boleto_additional_details: Option<BoletoAdditionalDetails>,+}++#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]+#[diesel(sql_type = Json)]+pub struct BoletoAdditionalDetails {+ /// Due Date for the Boleto+ #[serde(with = "common_utils::custom_serde::date_only_optional")]+ pub due_date: Option<time::PrimitiveDateTime>,+ // It tells the bank what type of commercial document created the boleto. Why does this boleto exist? What kind of transaction or contract caused it?+ pub document_kind: Option<common_enums::enums::BoletoDocumentKind>,+ // This field tells the bank how the boleto can be paid — whether the payer must pay the exact amount, can pay a different amount, or pay in parts.+ pub payment_type: Option<common_enums::enums::BoletoPaymentType>,+ // It is a number which shows a contract between merchant and bank+ pub covenant_code: Option<Secret<String>>,+ /// Pix identification details+ pub pix_key: Option<common_enums::enums::PixKey>,}#[cfg(feature = "v2")]@@ -112,6 +132,39 @@ pub struct FeatureMetadata {pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,/// The system that the gateway is integrated with, e.g., `Direct`(through hyperswitch), `UnifiedConnectorService`(through ucs), etc.pub gateway_system: Option<common_enums::GatewaySystem>,+ /// Additional information related to pix like expiry time etc for QR Code payments+ pub pix_additional_details: Option<PixAdditionalDetails>,+ /// Extra information like fine percentage, interest percentage etc required for Pix payment method+ pub boleto_additional_details: Option<BoletoAdditionalDetails>,+}++#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]+#[diesel(sql_type = Json)]+pub enum PixAdditionalDetails {+ #[serde(rename = "immediate")]+ Immediate(ImmediateExpirationTime),+ #[serde(rename = "scheduled")]+ Scheduled(ScheduledExpirationTime),+}++#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]+#[diesel(sql_type = Json)]+pub struct ImmediateExpirationTime {+ /// Expiration time in seconds+ pub time: u32,+ /// Pix identification details+ pub pix_key: Option<common_enums::enums::PixKey>,+}++#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]+#[diesel(sql_type = Json)]+pub struct ScheduledExpirationTime {+ /// Expiration time in terms of date, format: YYYY-MM-DD+ pub date: time::PrimitiveDateTime,+ /// Days after expiration date for which the QR code remains valid+ pub validity_after_expiration: Option<u32>,+ /// Pix identification details+ pub pix_key: Option<common_enums::enums::PixKey>,}#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.tomlindex ed65b54b66..2f3a818fd9 100644--- a/crates/hyperswitch_connectors/Cargo.toml+++ b/crates/hyperswitch_connectors/Cargo.toml@@ -57,7 +57,7 @@ serde_with = "3.12.0"sha1 = { version = "0.10.6" }sha2 = "0.10"strum = { version = "0.26", features = ["derive"] }-time = "0.3.41"+time = { version = "0.3.41", features = ["macros"] }unicode-normalization = "0.1.24"utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order", "time"] }url = "2.5.4"diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rsindex 7fa5c7fc4f..fc2bdf4d29 100644--- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs@@ -4976,6 +4976,7 @@ pub fn get_qr_metadata(image_data_url,qr_code_url,display_to_timestamp,+ expiry_type: None,};Some(qr_code_info.encode_to_value()).transpose()@@ -5114,6 +5115,9 @@ pub fn get_present_to_shopper_metadata(instructions_url: response.action.instructions_url.clone(),entry_date: None,digitable_line: None,+ qr_code_url: None,+ barcode: None,+ expiry_date: None,};Some(voucher_data.encode_to_value())diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rsindex fe3d1820da..2055222f8c 100644--- a/crates/hyperswitch_connectors/src/connectors/santander.rs+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs@@ -1,28 +1,29 @@+pub mod requests;+pub mod responses;pub mod transformers;use std::sync::LazyLock;-use base64::Engine;use common_enums::enums;use common_utils::{- crypto,errors::CustomResult,- ext_traits::{ByteSliceExt, BytesExt},+ ext_traits::{BytesExt, ValueExt},request::{Method, Request, RequestBuilder, RequestContent},- types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},};-use error_stack::ResultExt;+use error_stack::{report, ResultExt};use hyperswitch_domain_models::{router_data::{AccessToken, ErrorResponse, RouterData},router_flow_types::{access_token_auth::AccessTokenAuth,payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},refunds::{Execute, RSync},+ UpdateMetadata,},router_request_types::{AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,- RefundsData, SetupMandateRequestData,+ PaymentsUpdateMetadataData, RefundsData, SetupMandateRequestData,},router_response_types::{ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,@@ -30,7 +31,8 @@ use hyperswitch_domain_models::{},types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,- PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,+ PaymentsSyncRouterData, PaymentsUpdateMetadataRouterData, RefundSyncRouterData,+ RefundsRouterData,},};use hyperswitch_interfaces::{@@ -39,19 +41,29 @@ use hyperswitch_interfaces::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,},configs::Connectors,- consts::NO_ERROR_MESSAGE,+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},errors,events::connector_api_logs::ConnectorEvent,types::{self, RefreshTokenType, Response},webhooks,};-use masking::{Mask, Maskable, PeekInterface, Secret};-use transformers as santander;+use masking::{Maskable, PeekInterface};use crate::{+ connectors::santander::{+ requests::{+ SantanderAuthRequest, SantanderAuthType, SantanderMetadataObject,+ SantanderPaymentRequest, SantanderRefundRequest, SantanderRouterData,+ },+ responses::{+ SanatanderAccessTokenResponse, SantanderErrorResponse, SantanderGenericErrorResponse,+ SantanderPaymentsResponse, SantanderPaymentsSyncResponse, SantanderRefundResponse,+ SantanderUpdateMetadataResponse, SantanderVoidResponse,+ },+ },constants::headers,types::{RefreshTokenRouterData, ResponseRouterData},- utils::{self as connector_utils, convert_amount, RefundsRequestData},+ utils::{self as connector_utils, convert_amount},};#[derive(Clone)]@@ -69,6 +81,10 @@ impl Santander {pub mod santander_constants {pub const SANTANDER_VERSION: &str = "v2";+ pub const PIX_MIN_LEN_PAYMENT_ID: usize = 26;+ pub const PIX_MAX_LEN_PAYMENT_ID: usize = 35;+ pub const BOLETO_MIN_LEN_PAYMENT_ID: usize = 13;+ pub const BOLETO_MAX_LEN_PAYMENT_ID: usize = 13;}impl api::Payment for Santander {}@@ -83,6 +99,7 @@ impl api::Refund for Santander {}impl api::RefundExecute for Santander {}impl api::RefundSync for Santander {}impl api::PaymentToken for Santander {}+impl api::PaymentUpdateMetadata for Santander {}impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>for Santander@@ -90,6 +107,153 @@ impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, Pay// Not Implemented (R)}+impl ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>+ for Santander+{+ fn get_headers(+ &self,+ req: &RouterData<UpdateMetadata, PaymentsUpdateMetadataData, 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: &PaymentsUpdateMetadataRouterData,+ connectors: &Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;++ 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),+ req.request.connector_transaction_id+ )),+ enums::ExpiryType::Scheduled => Ok(format!(+ "{}api/v1/cobv/{}",+ self.base_url(connectors),+ req.request.connector_transaction_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 base_url = connectors+ .santander+ .secondary_base_url+ .clone()+ .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;+ let version = santander_constants::SANTANDER_VERSION;+ let boleto_mca_metadata = santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;+ let workspace_id = boleto_mca_metadata.workspace_id.peek();+ Ok(format!("{base_url}collection_bill_management/{version}/workspaces/{workspace_id}/bank_slips"))+ }+ _ => 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()),+ }+ }++ fn get_request_body(+ &self,+ req: &PaymentsUpdateMetadataRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<RequestContent, errors::ConnectorError> {+ let connector_req = SantanderPaymentRequest::try_from(req)?;+ Ok(RequestContent::Json(Box::new(connector_req)))+ }++ fn build_request(+ &self,+ req: &PaymentsUpdateMetadataRouterData,+ connectors: &Connectors,+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {+ let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;+ Ok(Some(+ RequestBuilder::new()+ .method(Method::Patch)+ .url(&types::PaymentsUpdateMetadataType::get_url(+ self, req, connectors,+ )?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret))+ .attach_default_headers()+ .headers(types::PaymentsUpdateMetadataType::get_headers(+ self, req, connectors,+ )?)+ .set_body(types::PaymentsUpdateMetadataType::get_request_body(+ self, req, connectors,+ )?)+ .build(),+ ))+ }++ fn handle_response(+ &self,+ data: &PaymentsUpdateMetadataRouterData,+ event_builder: Option<&mut ConnectorEvent>,+ res: Response,+ ) -> CustomResult<PaymentsUpdateMetadataRouterData, errors::ConnectorError> {+ let response: SantanderUpdateMetadataResponse = res+ .response+ .parse_struct("Santander UpdateMetadataResponse")+ .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,+ })+ }++ 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)+ }+}+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for SantanderwhereSelf: ConnectorIntegration<Flow, Request, Response>,@@ -99,12 +263,51 @@ wherereq: &RouterData<Flow, Request, Response>,_connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let mut header = vec![(- headers::CONTENT_TYPE.to_string(),- self.get_content_type().to_string().into(),- )];- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;- header.append(&mut api_key);+ let access_token =+ req.access_token+ .clone()+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "access_token",+ })?;+ let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;++ let client_id = match req.payment_method_type {+ Some(enums::PaymentMethodType::Pix) => {+ santander_mca_metadata+ .pix+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?+ .client_id+ }+ Some(enums::PaymentMethodType::Boleto) => {+ santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?+ .client_id+ }+ _ => {+ return Err(errors::ConnectorError::NotSupported {+ message: req.payment_method.to_string(),+ connector: "Santander",+ }+ .into());+ }+ };++ let header = vec![+ (+ headers::AUTHORIZATION.to_string(),+ format!("Bearer {}", access_token.token.peek()).into(),+ ),+ (+ headers::CONTENT_TYPE.to_string(),+ self.common_get_content_type().to_string().into(),+ ),+ (+ headers::X_APPLICATION_KEY.to_string(),+ client_id.peek().to_owned().into(),+ ),+ ];+Ok(header)}}@@ -131,7 +334,7 @@ impl ConnectorCommon for Santander {res: Response,event_builder: Option<&mut ConnectorEvent>,) -> CustomResult<ErrorResponse, errors::ConnectorError> {- let response: santander::SantanderErrorResponse = res+ let response: SantanderErrorResponse = res.response.parse_struct("SantanderErrorResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -140,7 +343,7 @@ impl ConnectorCommon for Santander {router_env::logger::info!(connector_response=?response);match response {- santander::SantanderErrorResponse::PixQrCode(response) => {+ SantanderErrorResponse::PixQrCode(response) => {let message = response.detail.as_ref()@@ -151,7 +354,8 @@ impl ConnectorCommon for Santander {status_code: res.status_code,code: response.status.to_string(),message,- reason: response.detail.clone(),+ // reason: response.detail.clone(),+ reason: Some(response.title.clone()),attempt_status: None,connector_transaction_id: None,connector_response_reference_id: None,@@ -161,7 +365,7 @@ impl ConnectorCommon for Santander {connector_metadata: None,})}- santander::SantanderErrorResponse::Boleto(response) => Ok(ErrorResponse {+ SantanderErrorResponse::Boleto(response) => Ok(ErrorResponse {status_code: res.status_code,code: response.error_code.to_string(),message: response.error_message.clone(),@@ -181,6 +385,85 @@ impl ConnectorCommon for Santander {network_error_message: None,connector_metadata: None,}),+ SantanderErrorResponse::Generic(error_response) => match error_response {+ SantanderGenericErrorResponse::Pattern1(response) => {+ let message = response+ .detail+ .clone()+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string());++ Ok(ErrorResponse {+ status_code: res.status_code,+ code: response+ .status+ .as_str()+ .unwrap_or(NO_ERROR_CODE)+ .to_string(),+ message,+ reason: response.detail.clone(),+ attempt_status: None,+ connector_transaction_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ })+ }+ SantanderGenericErrorResponse::Pattern2(response) => {+ let message = response+ .details+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string());++ Ok(ErrorResponse {+ status_code: res.status_code,+ code: NO_ERROR_CODE.to_string(),+ message: message.clone(),+ reason: Some(message),+ attempt_status: None,+ connector_transaction_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ })+ }+ SantanderGenericErrorResponse::Pattern3(response) => {+ let detail = response.fault.detail.error_code;++ Ok(ErrorResponse {+ status_code: res.status_code,+ code: detail.clone(),+ message: response.fault.fault_string,+ reason: Some(detail),+ attempt_status: None,+ connector_transaction_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ })+ }+ SantanderGenericErrorResponse::Pattern4(response) => {+ let detail = response.detail;++ Ok(ErrorResponse {+ status_code: res.status_code,+ code: detail.clone().unwrap_or(NO_ERROR_CODE.to_string()),+ message: detail.unwrap_or(NO_ERROR_MESSAGE.to_string()),+ reason: None,+ attempt_status: None,+ connector_transaction_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ })+ }+ },}}}@@ -196,31 +479,10 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> foimpl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Santander {fn get_headers(&self,- req: &RefreshTokenRouterData,+ _req: &RefreshTokenRouterData,_connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- let client_id = req.request.app_id.clone();-- let client_secret = req.request.id.clone();-- let creds = format!(- "{}:{}",- client_id.peek(),- client_secret.unwrap_or_default().peek()- );- let encoded_creds = common_utils::consts::BASE64_ENGINE.encode(creds);-- let auth_string = format!("Basic {encoded_creds}");- Ok(vec![- (- headers::CONTENT_TYPE.to_string(),- RefreshTokenType::get_content_type(self).to_string().into(),- ),- (- headers::AUTHORIZATION.to_string(),- auth_string.into_masked(),- ),- ])+ Ok(vec![])}fn get_content_type(&self) -> &'static str {@@ -229,13 +491,39 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>fn get_url(&self,- _req: &RefreshTokenRouterData,+ req: &RefreshTokenRouterData,connectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {- Ok(format!(- "{}/oauth/token?grant_type=client_credentials",- connectors.santander.base_url- ))+ match req.payment_method {+ enums::PaymentMethod::BankTransfer => Ok(format!(+ "{}oauth/token?grant_type=client_credentials",+ connectors.santander.base_url+ )),+ enums::PaymentMethod::Voucher => {+ let secondary_base_url = connectors.santander.secondary_base_url.clone().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "secondary_base_url for Santander",+ },+ )?;+ Ok(format!("{}auth/oauth/v2/token", secondary_base_url))+ }+ _ => Err(errors::ConnectorError::NotSupported {+ message: req.payment_method.to_string(),+ connector: "Santander",+ }+ .into()),+ }+ }++ fn get_request_body(+ &self,+ req: &RefreshTokenRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<RequestContent, errors::ConnectorError> {+ let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;+ let connector_req = SantanderAuthRequest::try_from((req, &santander_mca_metadata))?;++ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))}fn build_request(@@ -243,12 +531,16 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>req: &RefreshTokenRouterData,connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {+ let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;let req = Some(RequestBuilder::new().method(Method::Post).attach_default_headers().headers(RefreshTokenType::get_headers(self, req, connectors)?).url(&RefreshTokenType::get_url(self, req, connectors)?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret))+ .set_body(RefreshTokenType::get_request_body(self, req, connectors)?).build(),);Ok(req)@@ -260,13 +552,14 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>event_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {- let response: santander::SantanderAuthUpdateResponse = res+ let response: SanatanderAccessTokenResponse = res.response- .parse_struct("santander SantanderAuthUpdateResponse")+ .parse_struct("santander SanatanderAccessTokenResponse").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(),@@ -309,16 +602,37 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDatareq: &PaymentsAuthorizeRouterData,connectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {- let santander_mca_metadata =- santander::SantanderMetadataObject::try_from(&req.connector_meta_data)?;+ let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;match req.payment_method {enums::PaymentMethod::BankTransfer => match req.request.payment_method_type {- Some(enums::PaymentMethodType::Pix) => Ok(format!(- "{}cob/{}",- self.base_url(connectors),- req.payment_id- )),+ Some(enums::PaymentMethodType::Pix) => {+ match &req+ .request+ .feature_metadata+ .as_ref()+ .and_then(|f| f.pix_additional_details.as_ref())+ {+ Some(api_models::payments::PixAdditionalDetails::Immediate(_immediate)) => {+ Ok(format!(+ "{}api/v1/cob/{}",+ self.base_url(connectors),+ req.connector_request_reference_id+ ))+ }+ Some(api_models::payments::PixAdditionalDetails::Scheduled(_scheduled)) => {+ Ok(format!(+ "{}api/v1/cobv/{}",+ self.base_url(connectors),+ req.connector_request_reference_id+ ))+ }+ None => Err(errors::ConnectorError::MissingRequiredField {+ field_name: "pix_additional_details",+ }+ .into()),+ }+ }_ => Err(errors::ConnectorError::NotSupported {message: req.payment_method.to_string(),connector: "Santander",@@ -326,12 +640,23 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData.into()),},enums::PaymentMethod::Voucher => match req.request.payment_method_type {- Some(enums::PaymentMethodType::Boleto) => Ok(format!(- "{:?}{}/workspaces/{}/bank_slips",- connectors.santander.secondary_base_url.clone(),- santander_constants::SANTANDER_VERSION,- santander_mca_metadata.workspace_id- )),+ Some(enums::PaymentMethodType::Boleto) => {+ let boleto_mca_metadata = santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;+ let secondary_base_url =+ connectors.santander.secondary_base_url.clone().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "secondary_base_url for Santander",+ },+ )?;+ Ok(format!(+ "{}collection_bill_management/{}/workspaces/{}/bank_slips",+ secondary_base_url,+ santander_constants::SANTANDER_VERSION,+ boleto_mca_metadata.workspace_id.peek(),+ ))+ }_ => Err(errors::ConnectorError::NotSupported {message: req.payment_method.to_string(),connector: "Santander",@@ -357,8 +682,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDatareq.request.currency,)?;- let connector_router_data = santander::SantanderRouterData::from((amount, req));- let connector_req = santander::SantanderPaymentRequest::try_from(&connector_router_data)?;+ let connector_router_data = SantanderRouterData::from((amount, req));+ let connector_req = SantanderPaymentRequest::try_from(&connector_router_data)?;Ok(RequestContent::Json(Box::new(connector_req)))}@@ -367,12 +692,25 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDatareq: &PaymentsAuthorizeRouterData,connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {+ 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::Boleto) => Ok(Method::Post),+ _ => Err(errors::ConnectorError::NotSupported {+ message: req.payment_method.to_string(),+ connector: "Santander",+ }+ .into()),+ };Ok(Some(RequestBuilder::new()- .method(Method::Put)+ .method(method?).url(&types::PaymentsAuthorizeType::get_url(self, req, connectors,)?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret)).attach_default_headers().headers(types::PaymentsAuthorizeType::get_headers(self, req, connectors,@@ -390,23 +728,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDataevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {- let response: santander::SantanderPaymentsResponse = res+ let response: SantanderPaymentsResponse = res.response.parse_struct("Santander PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;let original_amount = match response {- santander::SantanderPaymentsResponse::PixQRCode(ref pix_data) => {- pix_data.value.original.clone()- }- santander::SantanderPaymentsResponse::Boleto(_) => {- convert_amount(- self.amount_converter,- MinorUnit::new(data.request.amount),- data.request.currency,- )?- // no amount field in the boleto response- }+ SantanderPaymentsResponse::PixQRCode(ref pix_data) => pix_data.valor.original.clone(),+ SantanderPaymentsResponse::Boleto(ref boleto_data) => boleto_data.nominal_value.clone(),};event_builder.map(|i| i.set_response_body(&response));@@ -439,6 +768,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData) -> 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<PSync, PaymentsSyncData, PaymentsResponseData> for Santander {@@ -459,92 +796,128 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Sanreq: &PaymentsSyncRouterData,connectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {- match req.request.payment_method_type {- Some(enums::PaymentMethodType::Pix) => {- let connector_payment_id = req- .request- .connector_transaction_id- .get_connector_transaction_id()- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;-- Ok(format!(- "{}{}{}",- self.base_url(connectors),- "cob/",- connector_payment_id- ))- }- Some(enums::PaymentMethodType::Boleto) => {- let bill_id = req- .request- .connector_meta- .clone()- .and_then(|val| val.as_str().map(|s| s.to_string()))- .ok_or_else(|| errors::ConnectorError::MissingRequiredField {- field_name: "bill_id",- })?;-- Ok(format!(- "{:?}/{}/bills/{}/bank_slips",- connectors.santander.secondary_base_url.clone(),- santander_constants::SANTANDER_VERSION,- bill_id- ))- }- _ => Err(errors::ConnectorError::MissingRequiredField {- field_name: "payment_method_type",+ let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;++ let connector_transaction_id = match req.request.connector_transaction_id {+ hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(+ ref id,+ ) => Some(id.clone()),+ _ => 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/{}",+ self.base_url(connectors),+ connector_transaction_id.ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "connector_transaction_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!(+ "{boleto_base_url}collection_bill_management/{version}/workspaces/{workspace_id}/bank_slips?\+ paymentDateFinal={due_date}&\+ paymentDateInitial={issue_date}&\+ status=LIQUIDADO&\+ bankNumber={connector_transaction_id}",+ boleto_base_url = boleto_base_url,+ version = version,+ workspace_id = workspace_id,+ due_date = expiry_date,+ 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()),}}- fn get_request_body(- &self,- req: &PaymentsSyncRouterData,- _connectors: &Connectors,- ) -> CustomResult<RequestContent, errors::ConnectorError> {- let amount = convert_amount(- self.amount_converter,- req.request.amount,- req.request.currency,- )?;-- let connector_router_data = santander::SantanderRouterData::from((amount, req));- let connector_req =- santander::SantanderPSyncBoletoRequest::try_from(&connector_router_data)?;- Ok(RequestContent::Json(Box::new(connector_req)))- }-fn build_request(&self,req: &PaymentsSyncRouterData,connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {- match req.request.payment_method_type {- Some(enums::PaymentMethodType::Pix) => Ok(Some(- RequestBuilder::new()- .method(Method::Get)- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)- .attach_default_headers()- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)- .build(),- )),- Some(enums::PaymentMethodType::Boleto) => Ok(Some(- RequestBuilder::new()- .method(Method::Post)- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)- .attach_default_headers()- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)- .set_body(types::PaymentsSyncType::get_request_body(- self, req, connectors,- )?)- .build(),- )),- _ => Err(errors::ConnectorError::MissingRequiredField {- field_name: "payment_method_type",- }- .into()),- }+ let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;++ Ok(Some(+ RequestBuilder::new()+ .method(Method::Get)+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret))+ .attach_default_headers()+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)+ .build(),+ ))}fn handle_response(@@ -553,16 +926,16 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Sanevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {- let response: santander::SantanderPaymentsSyncResponse = res+ let response: SantanderPaymentsSyncResponse = res.response.parse_struct("santander SantanderPaymentsSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;let original_amount = match response {- santander::SantanderPaymentsSyncResponse::PixQRCode(ref pix_data) => {- pix_data.base.value.original.clone()+ SantanderPaymentsSyncResponse::PixQRCode(ref pix_data) => {+ pix_data.valor.original.clone()}- santander::SantanderPaymentsSyncResponse::Boleto(_) => convert_amount(+ SantanderPaymentsSyncResponse::Boleto(_) => convert_amount(self.amount_converter,data.request.amount,data.request.currency,@@ -599,6 +972,14 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for San) -> 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<Capture, PaymentsCaptureData, PaymentsResponseData> for Santander {@@ -664,7 +1045,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> foevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {- let response: santander::SantanderPaymentsResponse = res+ let response: SantanderPaymentsResponse = res.response.parse_struct("Santander PaymentsCaptureResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -701,51 +1082,100 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Safn get_url(&self,- req: &PaymentsCancelRouterData,- connectors: &Connectors,+ _req: &PaymentsCancelRouterData,+ _connectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {- match req.payment_method {- enums::PaymentMethod::BankTransfer => {- let connector_payment_id = req.request.connector_transaction_id.clone();- Ok(format!(- "{}cob/{}",- self.base_url(connectors),- connector_payment_id- ))- }- _ => Err(errors::ConnectorError::NotSupported {- message: req.payment_method.to_string(),- connector: "Santander",- }- .into()),- }+ Err(errors::ConnectorError::NotImplemented("Santander".to_string()).into())+ // let santander_mca_metadata = SantanderMetadataObject::try_from(&req.connector_meta_data)?;++ // 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 {+ // ExpiryType::Immediate => Ok(format!(+ // "{}api/v1/cob/{}",+ // self.base_url(connectors),+ // req.request.connector_transaction_id+ // )),+ // ExpiryType::Scheduled => Ok(format!(+ // "{}api/v1/cobv/{}",+ // self.base_url(connectors),+ // req.request.connector_transaction_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 base_url = connectors+ // .santander+ // .secondary_base_url+ // .clone()+ // .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;++ // let version = santander_constants::SANTANDER_VERSION;++ // let boleto_mca_metadata = santander_mca_metadata+ // .boleto+ // .ok_or(errors::ConnectorError::NoConnectorMetaData)?;++ // Ok(format!(+ // "{base_url}collection_bill_management/{version}/workspaces/{}/bank_slips",+ // boleto_mca_metadata.workspace_id.peek(),+ // ))+ // }+ // _ => 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()),+ // }}fn get_request_body(&self,- req: &PaymentsCancelRouterData,+ _req: &PaymentsCancelRouterData,_connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> {- let connector_req = santander::SantanderPaymentsCancelRequest::try_from(req)?;- Ok(RequestContent::Json(Box::new(connector_req)))+ Err(errors::ConnectorError::NotImplemented("Santander".to_string()).into())+ // let connector_req = SantanderPaymentsCancelRequest::try_from(req)?;+ // Ok(RequestContent::Json(Box::new(connector_req)))}fn build_request(&self,- req: &PaymentsCancelRouterData,- connectors: &Connectors,+ _req: &PaymentsCancelRouterData,+ _connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {- Ok(Some(- RequestBuilder::new()- .method(Method::Patch)- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)- .attach_default_headers()- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)- .set_body(types::PaymentsVoidType::get_request_body(- self, req, connectors,- )?)- .build(),- ))+ Err(errors::ConnectorError::NotImplemented("Santander".to_string()).into())+ // let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;+ // Ok(Some(+ // RequestBuilder::new()+ // .method(Method::Patch)+ // .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)+ // .add_certificate(Some(auth_details.client_id))+ // .add_certificate_key(Some(auth_details.client_secret))+ // .attach_default_headers()+ // .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)+ // .set_body(types::PaymentsVoidType::get_request_body(+ // self, req, connectors,+ // )?)+ // .build(),+ // ))}fn handle_response(@@ -754,10 +1184,10 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Saevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {- let response: santander::SantanderPixVoidResponse = res- .response- .parse_struct("Santander PaymentsResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let response: SantanderVoidResponse =+ res.response+ .parse_struct("Santander VoidResponse")+ .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 {@@ -774,6 +1204,14 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Sa) -> 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<Execute, RefundsData, RefundsResponseData> for Santander {@@ -795,27 +1233,29 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Santandconnectors: &Connectors,) -> CustomResult<String, errors::ConnectorError> {match req.payment_method {- enums::PaymentMethod::BankTransfer => {- let end_to_end_id = req- .request- .connector_metadata- .as_ref()- .and_then(|metadata| metadata.get("end_to_end_id"))- .and_then(|val| val.as_str().map(|id| id.to_string()))- .ok_or_else(|| errors::ConnectorError::MissingRequiredField {- field_name: "end_to_end_id",- })?;-- let refund_id = req.request.connector_refund_id.clone();- Ok(format!(- "{}{}{}{}{:?}",- self.base_url(connectors),- "pix/",- end_to_end_id,- "/refund/",- refund_id- ))- }+ enums::PaymentMethod::BankTransfer => match req.payment_method_type {+ Some(enums::PaymentMethodType::Pix) => {+ let end_to_end_id = req+ .request+ .connector_metadata+ .as_ref()+ .and_then(|metadata| metadata.get("end_to_end_id"))+ .and_then(|val| val.as_str().map(|id| id.to_string()))+ .ok_or_else(|| errors::ConnectorError::MissingRequiredField {+ field_name: "end_to_end_id",+ })?;+ let refund_id = req.request.refund_id.clone();+ let base_url = self.base_url(connectors);+ Ok(format!(+ "{base_url}api/v1/pix/{end_to_end_id}/devolucao/{refund_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",@@ -835,8 +1275,8 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Santandreq.request.currency,)?;- let connector_router_data = santander::SantanderRouterData::from((refund_amount, req));- let connector_req = santander::SantanderRefundRequest::try_from(&connector_router_data)?;+ let connector_router_data = SantanderRouterData::from((refund_amount, req));+ let connector_req = SantanderRefundRequest::try_from(&connector_router_data)?;Ok(RequestContent::Json(Box::new(connector_req)))}@@ -845,9 +1285,21 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Santandreq: &RefundsRouterData<Execute>,connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {+ 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),+ _ => Err(errors::ConnectorError::NotSupported {+ message: req.payment_method.to_string(),+ connector: "Santander",+ }+ .into()),+ };let request = RequestBuilder::new()- .method(Method::Put)+ .method(method?).url(&types::RefundExecuteType::get_url(self, req, connectors)?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret)).attach_default_headers().headers(types::RefundExecuteType::get_headers(self, req, connectors,@@ -865,12 +1317,12 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Santandevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {- let response: santander::SantanderRefundResponse = res+ let response: SantanderRefundResponse = res.response.parse_struct("santander RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;- let original_amount = response.value.clone();+ let original_amount = response.valor.clone();event_builder.map(|i| i.set_response_body(&response));router_env::logger::info!(connector_response=?response);@@ -902,6 +1354,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Santand) -> 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<RSync, RefundsData, RefundsResponseData> for Santander {@@ -933,13 +1393,11 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Santander.ok_or_else(|| errors::ConnectorError::MissingRequiredField {field_name: "end_to_end_id",})?;+ let base_url = self.base_url(connectors);+ let refund_id = &req.request.refund_id;+Ok(format!(- "{}{}{}{}{}",- self.base_url(connectors),- "pix/",- end_to_end_id,- "/return/",- req.request.get_connector_refund_id()?+ "{base_url}api/v1/pix/{end_to_end_id}/devolucao/{refund_id}"))}@@ -948,10 +1406,13 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Santanderreq: &RefundSyncRouterData,connectors: &Connectors,) -> CustomResult<Option<Request>, errors::ConnectorError> {+ let auth_details = SantanderAuthType::try_from(&req.connector_auth_type)?;Ok(Some(RequestBuilder::new().method(Method::Get).url(&types::RefundSyncType::get_url(self, req, connectors)?)+ .add_certificate(Some(auth_details.client_id))+ .add_certificate_key(Some(auth_details.client_secret)).attach_default_headers().headers(types::RefundSyncType::get_headers(self, req, connectors)?).set_body(types::RefundSyncType::get_request_body(@@ -967,7 +1428,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Santanderevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {- let response: santander::SantanderRefundResponse = res+ let response: SantanderRefundResponse = res.response.parse_struct("santander RefundSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -987,62 +1448,38 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Santander) -> CustomResult<ErrorResponse, errors::ConnectorError> {self.build_error_response(res, event_builder)}-}--fn get_webhook_object_from_body(- body: &[u8],-) -> CustomResult<santander::SantanderWebhookBody, common_utils::errors::ParsingError> {- let webhook: santander::SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?;- Ok(webhook)+ fn get_5xx_error_response(+ &self,+ res: Response,+ event_builder: Option<&mut ConnectorEvent>,+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res, event_builder)+ }}#[async_trait::async_trait]impl webhooks::IncomingWebhook for Santander {- async fn verify_webhook_source(- &self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,- _merchant_id: &common_utils::id_type::MerchantId,- _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,- _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,- _connector_name: &str,- ) -> CustomResult<bool, errors::ConnectorError> {- Ok(true) // Hardcoded to true as the source verification algorithm for Santander remains to be unknown (in docs it is mentioned as MTLS)- }-fn get_webhook_object_reference_id(&self,- request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- let webhook_body = transformers::get_webhook_object_from_body(request.body)- .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;-- Ok(api_models::webhooks::ObjectReferenceId::PaymentId(- api_models::payments::PaymentIdType::ConnectorTransactionId(- webhook_body.participant_code,- ),- ))+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))}fn get_webhook_event_type(&self,- request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,_context: Option<&webhooks::WebhookContext>,) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {- let body = get_webhook_object_from_body(request.body)- .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;-- Ok(transformers::get_santander_webhook_event(body.function))+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))}fn get_webhook_resource_object(&self,- request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {- let webhook_body = transformers::get_webhook_object_from_body(request.body)- .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;-- Ok(Box::new(webhook_body))+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))}}@@ -1081,12 +1518,11 @@ static SANTANDER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {display_name: "Santander",description:"Santander is a leading private bank in Brazil, offering a wide range of financial services across retail and corporate segments. It is part of the global Santander Group, one of Europe’s largest financial institutions.",- connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,+ connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,integration_status: enums::ConnectorIntegrationStatus::Alpha,};-static SANTANDER_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =- [enums::EventClass::Payments, enums::EventClass::Refunds];+static SANTANDER_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];impl ConnectorSpecifications for Santander {fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {@@ -1100,6 +1536,42 @@ impl ConnectorSpecifications for Santander {fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {Some(&SANTANDER_SUPPORTED_WEBHOOK_FLOWS)}++ #[cfg(feature = "v1")]+ fn generate_connector_request_reference_id(+ &self,+ payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,+ payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,+ is_config_enabled_to_send_payment_id_as_connector_request_id: bool,+ ) -> String {+ match payment_attempt.payment_method_type {+ Some(enums::PaymentMethodType::Pix) => {+ if is_config_enabled_to_send_payment_id_as_connector_request_id+ && payment_intent.is_payment_id_from_merchant.unwrap_or(false)+ {+ payment_attempt.payment_id.get_string_repr().to_owned()+ } else {+ connector_utils::generate_alphanumeric_code(+ santander_constants::PIX_MIN_LEN_PAYMENT_ID,+ santander_constants::PIX_MAX_LEN_PAYMENT_ID,+ )+ }+ }+ Some(enums::PaymentMethodType::Boleto) => {+ if is_config_enabled_to_send_payment_id_as_connector_request_id+ && payment_intent.is_payment_id_from_merchant.unwrap_or(false)+ {+ payment_attempt.payment_id.get_string_repr().to_owned()+ } else {+ connector_utils::generate_random_string_containing_digits(+ santander_constants::BOLETO_MIN_LEN_PAYMENT_ID,+ santander_constants::BOLETO_MAX_LEN_PAYMENT_ID,+ )+ }+ }+ _ => payment_attempt.payment_id.get_string_repr().to_owned(),+ }+ }}impl ConnectorAccessTokenSuffix for Santander {diff --git a/crates/hyperswitch_connectors/src/connectors/santander/requests.rs b/crates/hyperswitch_connectors/src/connectors/santander/requests.rsnew file mode 100644index 0000000000..877b5d60ee--- /dev/null+++ b/crates/hyperswitch_connectors/src/connectors/santander/requests.rs@@ -0,0 +1,338 @@+use common_utils::types::{FloatMajorUnit, StringMajorUnit};+use masking::Secret;+use serde::{Deserialize, Serialize};++use crate::connectors::santander::responses;++#[derive(Default, Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+// Only due date is updatable as of now. Will add other fields when required.+pub struct SantanderBoletoUpdateRequest {+ #[serde(skip_deserializing)]+ pub covenant_code: Secret<String>,+ #[serde(skip_deserializing)]+ pub bank_number: String,+ pub due_date: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct InterestPercentage {+ pub interest_percentage: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Discount {+ #[serde(rename = "type")]+ pub discount_type: DiscountType,+ pub discount_one: Option<DiscountObject>,+ pub discount_two: Option<DiscountObject>,+ pub discount_three: Option<DiscountObject>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub struct DiscountObject {+ pub value: f64,+ pub limit_date: String, // YYYY-MM-DD+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum DiscountType {+ // No discount+ Isento,+ // If the payer pays before a certain date, they get a fixed discount amount+ ValorDataFixa,+ // This gives a discount per day of early payment, counting every day(weekends included). Example : $1.50 discount for each day before due date.+ ValorDiaCorrido,+ // Same as above, but only counts business days (Mon–Fri, excluding holidays). Example : $2 off per business day of early payment.+ ValorDiaUtil,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct SantanderMetadataObject {+ pub pix: Option<PixMetadataObject>,+ pub boleto: Option<BoletoMetadataObject>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct BoletoMetadataObject {+ pub client_id: Secret<String>,+ pub client_secret: Secret<String>,+ pub workspace_id: Secret<String>,+ pub covenant_code: Secret<String>,+ pub pix_key_value: Option<Secret<String>>,+ pub pix_key_type: Option<responses::SantanderPixKeyType>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct PixMetadataObject {+ pub client_id: Secret<String>,+ pub client_secret: Secret<String>,+ pub pix_key_value: Secret<String>,+ pub pix_key_type: responses::SantanderPixKeyType,+ pub merchant_name: String,+ pub merchant_city: String,+}++pub struct SantanderRouterData<T> {+ pub amount: StringMajorUnit,+ pub router_data: T,+}++#[derive(Debug, Serialize)]+pub struct SantanderAuthType {+ pub(super) client_id: Secret<String>,+ pub(super) client_secret: Secret<String>,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum SantanderGrantType {+ ClientCredentials,+}++#[derive(Debug, Serialize)]+pub struct SantanderAuthRequest {+ pub client_id: Secret<String>,+ pub client_secret: Secret<String>,+ pub grant_type: SantanderGrantType,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum ProtestType {+ // No protest+ SemProtesto,+ // Protest after X calendar days+ DiasCorridos,+ // Protest after X business days+ DiasUteis,+ // No need to provide days, uses bank’s pre-registered setting+ CadastroConvenio,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderDebtor {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cnpj: Option<Secret<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cpf: Option<Secret<String>>,+ // Name+ pub nome: Secret<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // Street+ pub logradouro: Option<Secret<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // City+ pub cidade: Option<Secret<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // State+ pub uf: Option<Secret<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // Zip Code+ pub cep: Option<Secret<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct SantanderValue {+ pub original: StringMajorUnit,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderPixRequestCalendar {+ Immediate(SantanderPixImmediateCalendarRequest),+ Scheduled(SantanderPixDueDateCalendarRequest),+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct SantanderPixImmediateCalendarRequest {+ #[serde(rename = "expiracao")]+ // expiration time in seconds+ pub expiracao: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPixDueDateCalendarRequest {+ // Expiration Date+ pub data_de_vencimento: String,+ // Validity After Expiration+ #[serde(skip_serializing_if = "Option::is_none")]+ pub validade_apos_vencimento: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPixCancelRequest {+ pub status: Option<responses::SantanderVoidStatus>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderPaymentsCancelRequest {+ PixQR(SantanderPixCancelRequest),+ Boleto(SantanderBoletoCancelRequest),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoCancelRequest {+ pub covenant_code: Secret<String>,+ pub bank_number: String,+ pub operation: SantanderBoletoCancelOperation,+}++#[derive(Default, Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderBoletoCancelOperation {+ // Protest+ Protestar,+ // Cancel Protest+ CancelarProtesto,+ #[default]+ // Write Off+ Baixar,+}++#[derive(Default, Debug, Serialize)]+pub struct SantanderRefundRequest {+ // value+ pub valor: StringMajorUnit,+}++#[derive(Debug, Serialize)]+#[serde(untagged)]+pub enum SantanderPaymentRequest {+ PixQR(Box<SantanderPixQRPaymentRequest>),+ Boleto(Box<SantanderBoletoPaymentRequest>),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename = "camelCase")]+pub struct SantanderPixQRPaymentRequest {+ #[serde(skip_serializing_if = "Option::is_none")]+ // calendar+ pub calendario: Option<SantanderPixRequestCalendar>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // debtor+ pub devedor: Option<SantanderDebtor>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // value+ pub valor: Option<SantanderValue>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // A unique identifier that links a user’s bank account and allows others to send money without needing bank details. Instead of sharing: Bank name/Branch/Account number, one can just share the chave Pix, and the Central Bank of Brazil resolves it to the correct account.+ pub chave: Option<Secret<String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // request_payer+ pub solicitacao_pagador: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ // additional_info+ pub info_adicionais: Option<Vec<responses::SantanderAdditionalInfo>>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoPaymentRequest {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub environment: Option<Environment>,+ // This is a unique identifier for the boleto registration request.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub nsu_code: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub nsu_date: Option<String>,+ // It is a number which shows a contract between merchant and bank+ #[serde(skip_serializing_if = "Option::is_none")]+ pub covenant_code: Option<Secret<String>>,+ // It is a unique ID which the merchant makes to identify each txn and the bank uses this to identify unique txn's+ #[serde(skip_serializing_if = "Option::is_none")]+ pub bank_number: Option<String>,+ // It is a unique ID which the merchant uses internally to identify each order+ #[serde(skip_serializing_if = "Option::is_none")]+ pub client_number: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub due_date: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub issue_date: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub nominal_value: Option<StringMajorUnit>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub participant_code: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payer: Option<responses::Payer>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub beneficiary: Option<responses::Beneficiary>,+ // It tells the bank what type of commercial document created the boleto. Why does this boleto exist? What kind of transaction or contract caused it?+ #[serde(skip_serializing_if = "Option::is_none")]+ pub document_kind: Option<responses::SantanderBoletoDocumentKind>,+ // The discount field indicates if the boleto gives the payer a discount for paying early+ #[serde(skip_serializing_if = "Option::is_none")]+ pub discount: Option<Discount>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub fine_percentage: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub fine_quantity_days: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub interest_percentage: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub deduction_value: Option<FloatMajorUnit>,+ // Protest is a formal step a bank or notary office takes to claim unpaid boletos after the due date+ #[serde(skip_serializing_if = "Option::is_none")]+ pub protest_type: Option<ProtestType>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub protest_quantity_days: Option<i64>,+ // This field tells the bank after how many days past the due date the boleto should be automatically “written off”+ #[serde(skip_serializing_if = "Option::is_none")]+ pub write_off_quantity_days: Option<String>,+ // This field tells the bank how the boleto can be paid — whether the payer must pay the exact amount, can pay a different amount, or pay in parts.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payment_type: Option<responses::SantanderBoletoPaymentType>,+ // This becomes a required field if payment_type is Parcial. This field indicates the number of payments allowed for the same payment slip, with a maximum of 99.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub parcels_quantity: Option<i64>,+ // The valueType field defines how the min/max limits are expressed for boletos that allow flexible payments. Only used if paymentType is DIVERGENTE or PARCIAL.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub value_type: Option<ValueType>,+ // This field defines the minimum amount or minimum percentage the payer can pay for a boleto that allows DIVERGENTE or PARCIAL payments.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub min_value_or_percentage: Option<f64>,+ // This field defines the max amount or max percentage the payer can pay for a boleto that allows DIVERGENTE or PARCIAL payments.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub max_value_or_percentage: Option<f64>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub iof_percentage: Option<f64>,+ // This feature allows the merchant (beneficiário) to split the funds received from a boleto into up to four Santander accounts that they own.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sharing: Option<Vec<responses::Sharing>>,+ // This field indicates the type of PIX key that the beneficiary (merchant) has registered in Santander.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub key: Option<responses::Key>,+ // The transaction id of the QR Code payment request+ #[serde(skip_serializing_if = "Option::is_none")]+ pub tx_id: Option<String>,+ // Messages to be printed on the payment slip or the payer's receipt. They should be sent in list format with up to 45 texts of 100 characters each.+ // Example : ["Payable at any bank until the due date.", "After the due date, only at Santander branches."]+ #[serde(skip_serializing_if = "Option::is_none")]+ pub messages: Option<Vec<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum ValueType {+ // Percentage+ Percentual,+ // Value terms+ Valor,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum Environment {+ // Sandbox+ Teste,+ // Production+ Producao,+}diff --git a/crates/hyperswitch_connectors/src/connectors/santander/responses.rs b/crates/hyperswitch_connectors/src/connectors/santander/responses.rsnew file mode 100644index 0000000000..d00ea707ee--- /dev/null+++ b/crates/hyperswitch_connectors/src/connectors/santander/responses.rs@@ -0,0 +1,739 @@+use common_utils::types::StringMajorUnit;+use masking::Secret;+use serde::{Deserialize, Serialize};+use time::PrimitiveDateTime;++use crate::connectors::santander::requests;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Payer {+ pub name: Secret<String>,+ pub document_type: SantanderDocumentKind,+ pub document_number: Option<Secret<String>>,+ pub address: Option<Secret<String>>,+ pub neighborhood: Option<Secret<String>>,+ pub city: Option<Secret<String>>,+ pub state: Option<Secret<String>>,+ pub zip_code: Option<Secret<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum SantanderDocumentKind {+ Cnpj,+ Cpf,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Beneficiary {+ pub name: Option<Secret<String>>,+ pub document_type: Option<String>,+ pub document_number: Option<Secret<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderBoletoDocumentKind {+ // Used when selling goods/products (commercial invoice).+ DuplicataMercantil,+ // Used when selling services (service invoice).+ DuplicataServico,+ // A standard promissory note — customer promises to pay later.+ NotaPromissoria,+ // Promissory note related to rural/agricultural operations.+ NotaPromissoriaRural,+ // A receipt, usually when the boleto is tied to a receipt-type transaction.+ Recibo,+ // Related to insurance policy payments.+ ApoliceSeguro,+ // Used when the boleto is tied to credit card operations (e.g., card invoice).+ BoletoCartaoCredito,+ // For payments related to commercial proposals/quotes.+ BoletoProposta,+ // For deposit or funding (aporte) into an account (e.g., prepaid wallet top-up).+ BoletoDepositoAporte,+ // Payment related to a cheque transaction.+ Cheque,+ // A direct promissory note (often between borrower and lender directly).+ NotaPromissoriaDireta,+ // Anything that doesn't fit the above categories+ Outros,+}++#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct SantanderAdditionalInfo {+ // Name+ pub nome: Secret<String>,+ // Value+ pub valor: String,+}++#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderPaymentStatus {+ // Active+ Ativa,+ // Completed+ Concluida,+ // Removed By Receiving User+ RemovidaPeloUsuarioRecebedor,+ // Removed By Psp+ RemovidaPeloPsp,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderVoidStatus {+ // RemovedByReceivingUser+ RemovidaPeloUsuarioRecebedor,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderPaymentsResponse {+ PixQRCode(Box<SantanderPixQRCodePaymentsResponse>),+ Boleto(Box<SantanderBoletoPaymentsResponse>),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct SantanderPixQRCodePaymentsResponse {+ pub status: SantanderPaymentStatus,+ // Calendar+ pub calendario: SantanderCalendarResponse,+ // Transaction Id+ pub txid: String,+ // revision+ pub revisao: serde_json::Value,+ // Debtor+ pub devedor: requests::SantanderDebtor,+ pub location: Option<String>,+ // Recipient+ pub recebedor: Option<Recipient>,+ // Value+ pub valor: requests::SantanderValue,+ // Key+ pub chave: Secret<String>,+ // Request Payer+ pub solicitacao_pagador: Option<String>,+ // Additional Info+ pub info_adicionais: Option<Vec<SantanderAdditionalInfo>>,+ pub pix: Option<Vec<SantanderPix>>,+ // pix_qr_code_data+ pub pix_copia_e_cola: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoPaymentsResponse {+ pub environment: requests::Environment,+ pub nsu_code: String,+ pub nsu_date: String,+ pub covenant_code: Secret<String>,+ pub bank_number: String,+ pub client_number: Option<String>,+ #[serde(with = "common_utils::custom_serde::date_only")]+ pub due_date: PrimitiveDateTime,+ pub issue_date: String,+ pub participant_code: Option<String>,+ pub nominal_value: StringMajorUnit,+ pub payer: Payer,+ pub beneficiary: Option<Beneficiary>,+ pub document_kind: SantanderBoletoDocumentKind,+ pub discount: Option<requests::Discount>,+ pub fine_percentage: Option<String>,+ pub fine_quantity_days: Option<String>,+ pub interest_percentage: Option<String>,+ pub deduction_value: Option<String>,+ pub protest_type: Option<requests::ProtestType>,+ pub protest_quantity_days: Option<String>,+ pub write_off_quantity_days: Option<String>,+ pub payment_type: SantanderBoletoPaymentType,+ pub parcels_quantity: Option<String>,+ pub value_type: Option<String>,+ pub min_value_or_percentage: Option<String>,+ pub max_value_or_percentage: Option<String>,+ pub iof_percentage: Option<String>,+ pub sharing: Option<Vec<Sharing>>,+ pub key: Option<Key>,+ pub tx_id: Option<String>,+ pub messages: Option<Vec<String>>,+ pub barcode: Option<Secret<String>>,+ pub digitable_line: Option<Secret<String>>,+ pub entry_date: Option<String>,+ pub qr_code_pix: Option<String>,+ pub qr_code_url: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPixQRCodeSyncResponse {+ pub status: SantanderPaymentStatus,+ // Calendar+ pub calendario: SantanderCalendarResponse,+ // Transaction Id+ pub txid: String,+ // Revision+ pub revisao: Option<serde_json::Value>,+ // Debtor+ pub devedor: Option<requests::SantanderDebtor>,+ pub location: Option<String>,+ // Value+ pub valor: requests::SantanderValue,+ // Key+ pub chave: Secret<String>,+ // Request Payer+ pub solicitacao_pagador: Option<String>,+ // Additional Info+ pub info_adicionais: Option<Vec<SantanderAdditionalInfo>>,+ pub pix: Option<Vec<SantanderPix>>,+ // Pix QR Code Data+ pub pix_copia_e_cola: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPixVoidResponse {+ // Calendar+ pub calendario: SantanderCalendarResponse,+ // Transaction Id+ pub txid: String,+ // Revision+ pub revisao: Option<serde_json::Value>,+ // Debtor+ pub devedor: Option<requests::SantanderDebtor>,+ // Recipient+ pub recebedor: Recipient,+ // Status+ pub status: SantanderPaymentStatus,+ // Value+ pub valor: ValueResponse,+ // Pix QR Code Data+ pub pix_copia_e_cola: Option<Secret<String>>,+ // Key+ pub chave: Secret<String>,+ // Request Payer+ pub solicitacao_pagador: Option<String>,+ // Additional Info+ pub info_adicionais: Option<Vec<SantanderAdditionalInfo>>,+ pub pix: Option<Vec<SantanderPix>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderVoidResponse {+ Pix(Box<SantanderPixVoidResponse>),+ Boleto(Box<SantanderBoletoVoidResponse>),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoVoidResponse {+ pub covenant_code: String,+ pub bank_number: String,+ pub message: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ValueResponse {+ // Original payment amount+ pub original: String,+ // Fine (penalty) details+ pub multa: Option<Fine>,+ // Interest details+ pub juros: Option<Interest>,+ // Discount details+ pub desconto: Option<DiscountResponse>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Fine {+ // Type or mode of fine (e.g., percentage or fixed amount)+ pub modalidade: String,+ // Fine value or percentage applied+ pub valor_perc: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Interest {+ // Type or mode of interest (e.g., daily rate or fixed)+ pub modalidade: String,+ // Interest value or percentage applied+ pub valor_perc: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DiscountResponse {+ // Type or mode of discount (e.g., fixed date or percentage)+ pub modalidade: String,+ // List of discounts applicable on specific fixed dates+ pub desconto_data_fixa: Vec<FixedDateDiscount>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FixedDateDiscount {+ // Date on which the discount is valid+ pub data: String,+ // Discount value or percentage applied+ pub valor_perc: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Recipient {+ // Recipient’s CNPJ (business tax ID)+ pub cnpj: Option<Secret<String>>,+ // Recipient’s legal name+ pub nome: Option<Secret<String>>,+ // Recipient’s business or trade name+ pub nome_fantasia: Option<Secret<String>>,+ // Street address of the recipient+ pub logradouro: Option<Secret<String>>,+ // City where the recipient is located+ pub cidade: Option<Secret<String>>,+ // State (federal unit) of the recipient+ pub uf: Option<Secret<String>>,+ // Postal code (ZIP code) of the recipient+ pub cep: Option<Secret<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct SantanderCalendarResponse {+ // Date and time when the payment was created+ pub criacao: String,+ // Expiration time of the payment (if applicable)+ pub expiracao: Option<String>,+ // Due date for the payment+ pub data_de_vencimento: Option<String>,+ // Validity period after the due date+ pub validade_apos_vencimento: Option<serde_json::Value>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderPaymentsSyncResponse {+ PixQRCode(Box<SantanderPixQRCodeSyncResponse>),+ Boleto(Box<SantanderBoletoPSyncResponse>),+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPix {+ // Unique PIX transaction identifier+ pub end_to_end_id: Secret<String>,+ // Transaction ID associated with the payment+ pub txid: Secret<String>,+ // Transaction amount+ pub valor: String,+ // Timestamp when the transaction occurred+ pub horario: String,+ // Optional information provided by the payer+ pub info_pagador: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderUpdateBoletoResponse {+ pub covenant_code: Option<String>,+ pub bank_number: Option<String>,+ pub message: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderRefundStatus {+ /// The refund is currently being processed and not yet completed+ EmProcessamento,+ /// The refund has been successfully completed and the amount was returned+ Devolvido,+ /// The refund was not carried out+ NaoRealizado,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderRefundResponse {+ // Hyperswitch Refund Id+ pub id: Secret<String>,+ // Connector Refund Id+ pub rtr_id: Secret<String>, // Need to confirm with Santander on what this id is+ // Refund amount+ pub valor: StringMajorUnit,+ // Time information related to the refund+ pub horario: SantanderTime,+ // Refund status+ pub status: SantanderRefundStatus,+ // Reason for the refund+ pub motivo: String,+}++#[derive(Default, Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderTime {+ // Time when the refund was requested+ pub solicitacao: Option<String>,+ // Time when the refund was completed (settled)+ pub liquidacao: Option<String>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderErrorResponse {+ PixQrCode(SantanderPixQRCodeErrorResponse),+ Boleto(SantanderBoletoErrorResponse),+ Generic(SantanderGenericErrorResponse),+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderGenericErrorResponse {+ Pattern1(SantanderPattern1ErrorResponse),+ // Validation Errors or when wrong access token is passed+ Pattern2(SantanderPattern2ErrorResponse),+ // When JWT is expired+ Pattern3(SantanderPattern3ErrorResponse),+ // On Refund Failures+ Pattern4(SantanderPattern4ErrorResponse),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SantanderPattern4ErrorResponse {+ pub timestamp: Option<String>,+ #[serde(rename = "httpStatusCode")]+ pub http_status_code: Option<String>,+ pub detail: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SantanderPattern3ErrorResponse {+ pub fault: FaultError,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FaultError {+ #[serde(rename = "faultstring")]+ pub fault_string: String,+ pub detail: DetailError,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DetailError {+ #[serde(rename = "errorcode")]+ pub error_code: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SantanderBoletoErrorResponse {+ #[serde(rename = "_errorCode")]+ pub error_code: i64,+ #[serde(rename = "_message")]+ pub error_message: String,+ #[serde(rename = "_details")]+ pub issuer_error_message: Option<String>,+ #[serde(rename = "_timestamp")]+ pub timestamp: String,+ #[serde(rename = "_traceId")]+ pub trace_id: String,+ #[serde(rename = "_errors")]+ pub errors: Option<Vec<ErrorObject>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SantanderPattern1ErrorResponse {+ #[serde(rename = "type")]+ pub card_type: String,+ pub title: String,+ pub status: serde_json::Value,+ pub detail: Option<String>,+ #[serde(rename = "correlationId")]+ pub correlation_id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPattern2ErrorResponse {+ pub timestamp: String,+ pub http_status: String,+ pub details: Option<String>,+ pub error_code: Option<serde_json::Value>,+ pub tracking_id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ErrorObject {+ #[serde(rename = "_code")]+ pub code: Option<String>,+ #[serde(rename = "_field")]+ pub field: Option<String>,+ #[serde(rename = "_message")]+ pub message: String,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPixQRCodeErrorResponse {+ #[serde(rename = "type")]+ pub field_type: Secret<String>,+ pub title: String,+ pub status: String,+ pub detail: Option<String>,+ pub correlation_id: Option<String>,+ // Violations+ pub violacoes: Option<Vec<SantanderViolations>>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderViolations {+ // Description or reason for the violation+ pub razao: Option<String>,+ // Name of the property or field that caused the violation+ pub propriedade: Option<String>,+ // Value associated with the violation+ pub valor: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+/// Represents the channel through which a boleto payment was made.+pub enum PaymentChannel {+ /// Payment made at a bank branch or ATM (self-service).+ AgenciasAutoAtendimento,+ /// Payment made through online banking.+ InternetBanking,+ /// Payment made at a physical correspondent agent (e.g., convenience stores, partner outlets).+ CorrespondenteBancarioFisico,+ /// Payment made via Santander’s call center.+ CentralDeAtendimento,+ /// Payment made via electronic file, typically for bulk company payments.+ ArquivoEletronico,+ /// Payment made via DDA (Débito Direto Autorizado) / electronic bill presentment system.+ Dda,+ /// Payment made via digital correspondent channels (apps, kiosks, digital partners).+ CorrespondenteBancarioDigital,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+/// Represents the type of payment instrument used to pay a boleto.+pub enum PaymentKind {+ /// Payment made in cash or physical form (not via account or card).+ Especie,+ /// Payment made via direct debit from a bank account.+ DebitoEmConta,+ /// Payment made via credit card.+ CartaoDeCredito,+ /// Payment made via check.+ Cheque,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+/// Represents the type of boleto payment or registration action.+pub enum SantanderBoletoPaymentType {+ /// Only the exact nominal value can be paid+ Registro,+ /// Payer can pay any amount within a range, min to max value+ Divergente,+ /// Payer can make up to 99 partial payments+ Parcial,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Sharing {+ // A 2-digit identifier for a split rule+ pub code: String,+ // Exact monetary amount assigned to that split+ pub value: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Key {+ #[serde(rename = "type")]+ pub key_type: Option<SantanderPixKeyType>,+ pub dict_key: Option<Secret<String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "UPPERCASE")]+pub enum SantanderPixKeyType {+ Cpf,+ Cnpj,+ Email,+ Cellular,+ Evp,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SanatanderAccessTokenResponse {+ Response(SanatanderTokenResponse),+ Error(SantanderTokenErrorResponse),+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SanatanderTokenResponse {+ Pix(SanatanderPixAccessTokenResponse),+ Boleto(SanatanderBoletoAccessTokenResponse),+}++#[derive(Debug, Serialize, Deserialize)]+pub struct SanatanderPixAccessTokenResponse {+ #[serde(rename = "refreshUrl")]+ pub refresh_url: String,+ pub token_type: String,+ pub client_id: Secret<String>,+ pub access_token: Secret<String>,+ pub scopes: String,+ pub expires_in: String,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct SanatanderBoletoAccessTokenResponse {+ pub access_token: Secret<String>,+ pub expires_in: i64,+ pub token_type: String,+ #[serde(rename = "not-before-policy")]+ pub not_before_policy: i64,+ pub session_state: String,+ pub scope: String,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct SantanderTokenErrorResponse {+ #[serde(rename = "type")]+ pub error_type: String,+ pub title: String,+ pub status: u16,+ pub detail: String,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct QrDataUrlSantander {+ pub qr_code_url: url::Url,+ pub display_to_timestamp: Option<i64>,+ pub variant: Option<common_enums::enums::ExpiryType>,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum SantanderUpdateMetadataResponse {+ Pix(Box<SantanderPixQRCodePaymentsResponse>),+ Boleto(Box<SantanderUpdateBoletoResponse>),+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NsuComposite {+ pub nsu_code: String,+ pub nsu_date: String,+ pub environment: String,+ pub covenant_code: String,+ pub bank_number: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoPSyncResponse {+ #[serde(rename = "_content")]+ pub content: Vec<SantanderBoletoContent>,+ #[serde(rename = "_pageable")]+ pub pageable: SantanderPaginationMetadata,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPaginationMetadata {+ #[serde(rename = "_limit")]+ pub limit: Option<i32>,++ #[serde(rename = "_offset")]+ pub offset: Option<i32>,++ #[serde(rename = "_pageNumber")]+ pub page_number: Option<i32>,++ #[serde(rename = "_pageElements")]+ pub page_elements: Option<i32>,++ #[serde(rename = "_totalPages")]+ pub total_pages: Option<i32>,++ #[serde(rename = "_totalElements")]+ pub total_elements: Option<i32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderBoletoContent {+ pub nsu_code: Option<String>,+ pub nsu_date: Option<String>,+ pub covenant_code: Secret<String>,+ pub bank_number: String,+ pub client_number: Option<String>,+ pub status: SantanderBoletoStatus,+ pub status_complement: Option<String>,+ pub due_date: String,+ pub issue_date: String,+ pub nominal_value: StringMajorUnit,+ pub payer: Payer,+ pub beneficiary: Beneficiary,+ pub fine_percentage: Option<String>,+ pub fine_quantity_days: Option<String>,+ pub interest_percentage: Option<String>,+ pub discount: Option<requests::Discount>,+ pub deduction_value: Option<String>,+ pub protest_type: Option<String>,+ pub protest_quantity_days: Option<String>,+ pub payment_type: Option<String>,+ pub parcels_quantity: Option<String>,+ pub min_value_or_percentage: Option<String>,+ pub max_value_or_percentage: Option<String>,+ pub iof_percentage: Option<String>,+ pub payment: SantanderPaymentDetails,+ pub barcode: Option<Secret<String>>,+ pub digitable_line: Option<Secret<String>>,+ pub entry_date: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SantanderPaymentDetails {+ pub paid_value: Option<StringMajorUnit>,+ pub interest_value: Option<StringMajorUnit>,+ pub fine_value: Option<StringMajorUnit>,+ pub deduction_value: Option<StringMajorUnit>,+ pub rebate_value: Option<StringMajorUnit>,+ pub iof_value: Option<StringMajorUnit>,+ pub date: Option<String>,+ #[serde(rename = "type")]+ pub bank_type: Option<String>,+ pub bank_code: Option<String>,+ pub channel: Option<String>,+ pub kind: Option<String>,+ pub credit_date: Option<String>,+ pub tx_id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum SantanderBoletoStatus {+ /// The boleto is registered and waiting for payment.+ /// It is currently valid and within its expiration period.+ Ativo,+ /// The boleto has been cancelled or removed from the bank's+ Baixado,+ /// The boleto has been paid in full. The funds have been cleared and settled.+ Liquidado,+ /// A partial payment was made+ LiquidadoParcialmente,+}diff --git a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rsindex 821c932269..d09b072eb0 100644--- a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs@@ -1,58 +1,61 @@-use std::collections::HashMap;-use api_models::payments::{QrCodeInformation, VoucherNextStepData};-use common_enums::{enums, AttemptStatus};+use common_enums::{+ enums, AttemptStatus, BoletoDocumentKind, BoletoPaymentType, ExpiryType, PixKey,+};use common_utils::{errors::CustomResult,- ext_traits::{ByteSliceExt, Encode},- id_type,- request::Method,- types::{AmountConvertor, FloatMajorUnit, StringMajorUnit, StringMajorUnitForConnector},+ ext_traits::{Encode, ValueExt},+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},};use crc::{Algorithm, Crc};use error_stack::ResultExt;use hyperswitch_domain_models::{- payment_method_data::{BankTransferData, PaymentMethodData, VoucherData},+ payment_method_data::{BankTransferData, BoletoVoucherData, PaymentMethodData, VoucherData},router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},- router_request_types::ResponseId,- router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},+ router_request_types::{PaymentsUpdateMetadataData, ResponseId},+ router_response_types::{PaymentsResponseData, RefundsResponseData},types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,- RefundsRouterData,+ PaymentsUpdateMetadataRouterData, RefundsRouterData,},};use hyperswitch_interfaces::{consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},- errors,+ errors::{self},};-use masking::{ExposeInterface, PeekInterface, Secret};+use masking::{ExposeInterface, Secret};use serde::{Deserialize, Serialize};use serde_json::Value;-use time::OffsetDateTime;use url::Url;use crate::{- types::{RefundsResponseRouterData, ResponseRouterData},+ connectors::santander::{+ requests::{+ Environment, SantanderAuthRequest, SantanderAuthType, SantanderBoletoCancelOperation,+ SantanderBoletoCancelRequest, SantanderBoletoPaymentRequest,+ SantanderBoletoUpdateRequest, SantanderDebtor, SantanderGrantType,+ SantanderMetadataObject, SantanderPaymentRequest, SantanderPaymentsCancelRequest,+ SantanderPixCancelRequest, SantanderPixDueDateCalendarRequest,+ SantanderPixImmediateCalendarRequest, SantanderPixQRPaymentRequest,+ SantanderPixRequestCalendar, SantanderRefundRequest, SantanderRouterData,+ SantanderValue,+ },+ responses::{+ Key, NsuComposite, Payer, SanatanderAccessTokenResponse, SanatanderTokenResponse,+ SantanderAdditionalInfo, SantanderBoletoDocumentKind, SantanderBoletoPaymentType,+ SantanderBoletoStatus, SantanderDocumentKind, SantanderPaymentStatus,+ SantanderPaymentsResponse, SantanderPaymentsSyncResponse, SantanderPixKeyType,+ SantanderPixQRCodePaymentsResponse, SantanderPixQRCodeSyncResponse,+ SantanderRefundResponse, SantanderRefundStatus, SantanderUpdateMetadataResponse,+ SantanderVoidResponse, SantanderVoidStatus,+ },+ },+ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},utils::{self as connector_utils, QrImage, RouterData as _},};-const CRC_16_CCITT_FALSE: Algorithm<u16> = Algorithm {- width: 16,- poly: 0x1021,- init: 0xFFFF,- refin: false,- refout: false,- xorout: 0x0000,- check: 0x29B1,- residue: 0x0000,-};type Error = error_stack::Report<errors::ConnectorError>;-pub struct SantanderRouterData<T> {- pub amount: StringMajorUnit,- pub router_data: T,-}-impl<T> From<(StringMajorUnit, T)> for SantanderRouterData<T> {fn from((amount, item): (StringMajorUnit, T)) -> Self {Self {@@ -61,17 +64,6 @@ impl<T> From<(StringMajorUnit, T)> for SantanderRouterData<T> {}}}-#[derive(Debug, Default, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderMetadataObject {- pub pix_key: Secret<String>,- pub expiration_time: i32,- pub cpf: Secret<String>,- pub merchant_city: String,- pub merchant_name: String,- pub workspace_id: String,- pub covenant_code: String, // max_size : 9-}impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for SantanderMetadataObject {type Error = error_stack::Report<errors::ConnectorError>;@@ -86,82 +78,107 @@ impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for SantanderMetadata}}+impl TryFrom<&PaymentsUpdateMetadataRouterData> for SantanderBoletoUpdateRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {+ let santander_mca_metadata = SantanderMetadataObject::try_from(&item.connector_meta_data)?;++ let boleto_mca_metadata = santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;++ let boleto_components = extract_boleto_components(&item.request.connector_transaction_id)?;++ let due_date = Some(format_as_date_only(+ item.request+ .feature_metadata+ .clone()+ .and_then(|data| data.boleto_additional_details)+ .and_then(|boleto_details| boleto_details.due_date),+ )?);++ Ok(Self {+ covenant_code: boleto_mca_metadata.covenant_code,+ bank_number: boleto_components.bank_number,+ due_date,+ })+ }+}+pub fn format_emv_field(id: &str, value: &str) -> String {format!("{id}{:02}{value}", value.len())}+fn format_field(id: &str, value: &str) -> String {+ format!("{}{:02}{}", id, value.len(), value)+}+pub fn generate_emv_string(- payload_url: &str,+ cidade: &str,+ amount: &str,+ country: enums::CountryAlpha2,merchant_name: &str,- merchant_city: &str,- amount: Option<&str>,- txid: Option<&str>,-) -> String {- let mut emv = String::new();-- // 00: Payload Format Indicator- emv += &format_emv_field("00", "01");- // 01: Point of Initiation Method (dynamic)- emv += &format_emv_field("01", "12");-- // 26: Merchant Account Info- let gui = format_emv_field("00", "br.gov.bcb.pix");- let url = format_emv_field("25", payload_url);- let merchant_account_info = format_emv_field("26", &(gui + &url));- emv += &merchant_account_info;-- // 52: Merchant Category Code (0000)- emv += &format_emv_field("52", "0000");- // 53: Currency Code (986 for BRL)- emv += &format_emv_field("53", "986");-- // 54: Amount (optional)- if let Some(amount) = amount {- emv += &format_emv_field("54", amount);- }+ transaction_id: String,+ location: String,+) -> Result<String, errors::ConnectorError> {+ // ID 00: Payload Format Indicator+ let payload_format_indicator = format_field("00", "01");- // 58: Country Code (BR)- emv += &format_emv_field("58", "BR");- // 59: Merchant Name- emv += &format_emv_field("59", merchant_name);- // 60: Merchant City- emv += &format_emv_field("60", merchant_city);-- // 62: Additional Data Field Template (optional TXID)- if let Some(txid) = txid {- let reference = format_emv_field("05", txid);- emv += &format_emv_field("62", &reference);- }+ // ID 01: Point of Initiation Method+ let point_of_initiation_method = format_field("01", "12");- // Placeholder for CRC (we need to calculate this last)- emv += "6304";+ // ID 26: Merchant Account Information+ let gui = format_field("00", "br.gov.bcb.pix");+ let loc = format_field("25", &location);+ let merchant_account_information = format_field("26", &format!("{}{}", gui, loc));- // Compute CRC16-CCITT (False) checksum- let crc = Crc::<u16>::new(&CRC_16_CCITT_FALSE);- let checksum = crc.checksum(emv.as_bytes());- emv += &format!("{checksum:04X}");+ // ID 52: Merchant Category Code+ let merchant_category_code = format_field("52", "0000");- emv-}+ // ID 53: Transaction Currency+ let transaction_currency = format_field("53", "986");-#[derive(Debug, Serialize, Deserialize)]-pub struct SantanderAuthUpdateResponse {- #[serde(rename = "camelCase")]- pub refresh_url: String,- pub token_type: String,- pub client_id: String,- pub access_token: Secret<String>,- pub scopes: String,- pub expires_in: i64,-}+ // ID 54: Transaction Amount+ let transaction_amount = format_field("54", amount);++ // ID 58: Country Code+ let country_code = format_field("58", &country.to_string());++ // ID 59: Merchant Name+ let merchant_name = format_field("59", merchant_name);++ // ID 60: Merchant City+ let merchant_city = format_field("60", cidade); // to consume from req-#[derive(Default, Debug, Serialize, Eq, PartialEq)]-pub struct SantanderCard {- number: cards::CardNumber,- expiry_month: Secret<String>,- expiry_year: Secret<String>,- cvc: Secret<String>,- complete: bool,+ // Format subfield 05 with the actual TXID+ // This is an optional field to be sent while creating the copy-and-paste data for Pix QR Code+ // If sent, pass the first 25 or last 25 letters, if not passed then pass 3 astericks+ let reference_label = format_field("05", &transaction_id.chars().take(25).collect::<String>());++ // Wrap it inside ID 62+ let additional_data = format_field("62", &reference_label);++ let emv_without_crc = format!(+ "{payload_format_indicator}{point_of_initiation_method}{merchant_account_information}{merchant_category_code}{transaction_currency}{transaction_amount}{country_code}{merchant_name}{merchant_city}{additional_data}",+ );+ // CRC16-CCITT-FALSE constant+ const CRC16_CCITT_FALSE: Algorithm<u16> = Algorithm {+ width: 16,+ poly: 0x1021,+ init: 0xFFFF,+ refin: false,+ refout: false,+ xorout: 0x0000,+ check: 0x29B1,+ residue: 0x0000,+ };++ // ID 63: CRC16+ let crc_payload = format!("{}6304", emv_without_crc);+ let crc_value = Crc::<u16>::new(&CRC16_CCITT_FALSE).checksum(crc_payload.as_bytes());+ let crc_hex = format!("{:04X}", crc_value);++ Ok(format!("{}{}", crc_payload, crc_hex))}#[derive(Debug, Serialize, Deserialize)]@@ -170,38 +187,123 @@ pub struct SantanderPSyncBoletoRequest {payer_document_number: Secret<i64>,}-pub struct SantanderAuthType {- pub(super) _api_key: Secret<String>,- pub(super) _key1: Secret<String>,-}-impl TryFrom<&ConnectorAuthType> for SantanderAuthType {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {match auth_type {- ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {- _api_key: api_key.to_owned(),- _key1: key1.to_owned(),+ ConnectorAuthType::CertificateAuth {+ certificate,+ private_key,+ } => Ok(Self {+ client_id: certificate.to_owned(),+ client_secret: private_key.to_owned(),}),_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),}}}-impl<F, T> TryFrom<ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>>+impl TryFrom<(&RefreshTokenRouterData, &SantanderMetadataObject)> for SantanderAuthRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ item: (&RefreshTokenRouterData, &SantanderMetadataObject),+ ) -> Result<Self, Self::Error> {+ let (client_id, client_secret) = match item.0.payment_method_type {+ Some(enums::PaymentMethodType::Pix) => {+ let pix_mca_metadata = item+ .1+ .pix+ .as_ref()+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;+ Ok((+ pix_mca_metadata.client_id.clone(),+ pix_mca_metadata.client_secret.clone(),+ ))+ }+ Some(enums::PaymentMethodType::Boleto) => {+ let boleto_mca_metadata = item+ .1+ .boleto+ .as_ref()+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;+ Ok((+ boleto_mca_metadata.client_id.clone(),+ boleto_mca_metadata.client_secret.clone(),+ ))+ }+ _ => Err(error_stack::report!(errors::ConnectorError::NotSupported {+ message: item.0.payment_method.to_string(),+ connector: "Santander",+ })),+ }?;++ Ok(Self {+ client_id,+ client_secret,+ grant_type: SantanderGrantType::ClientCredentials,+ })+ }+}++impl TryFrom<&ConnectorAuthType> for SantanderAuthRequest {+ type Error = error_stack::Report<errors::ConnectorError>;++ fn try_from(connector_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {+ let auth_details = SantanderAuthType::try_from(connector_auth_type)?;++ Ok(Self {+ client_id: auth_details.client_id,+ client_secret: auth_details.client_secret,+ grant_type: SantanderGrantType::ClientCredentials,+ })+ }+}++impl<F, T> TryFrom<ResponseRouterData<F, SanatanderAccessTokenResponse, T, AccessToken>>for RouterData<F, T, AccessToken>{type Error = error_stack::Report<errors::ConnectorError>;+fn try_from(- item: ResponseRouterData<F, SantanderAuthUpdateResponse, T, AccessToken>,+ item: ResponseRouterData<F, SanatanderAccessTokenResponse, T, AccessToken>,) -> Result<Self, Self::Error> {- Ok(Self {- response: Ok(AccessToken {- token: item.response.access_token,- expires: item.response.expires_in,+ match item.response {+ SanatanderAccessTokenResponse::Response(res) => match res {+ SanatanderTokenResponse::Pix(pix_response) => Ok(Self {+ response: Ok(AccessToken {+ token: pix_response.access_token,+ expires: pix_response+ .expires_in+ .parse::<i64>()+ .change_context(errors::ConnectorError::ParsingFailed)?,+ }),+ ..item.data+ }),+ SanatanderTokenResponse::Boleto(boleto_response) => Ok(Self {+ response: Ok(AccessToken {+ token: boleto_response.access_token,+ expires: boleto_response.expires_in,+ }),+ ..item.data+ }),+ },+ SanatanderAccessTokenResponse::Error(error) => Ok(Self {+ response: Err(ErrorResponse {+ code: error.error_type,+ message: error.title,+ reason: Some(error.detail),+ status_code: error.status,+ attempt_status: None,+ connector_transaction_id: None,+ network_decline_code: None,+ network_advice_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ }),+ ..item.data}),- ..item.data- })+ }}}@@ -221,7 +323,13 @@ impl TryFrom<&SantanderRouterData<&PaymentsAuthorizeRouterData>> for SantanderPaPaymentMethodData::BankTransfer(ref bank_transfer_data) => {Self::try_from((value, bank_transfer_data.as_ref()))}- PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((value, voucher_data)),+ PaymentMethodData::Voucher(ref voucher_data) => match voucher_data {+ VoucherData::Boleto(boleto_data) => Self::try_from((value, boleto_data.as_ref())),+ _ => Err(errors::ConnectorError::NotImplemented(+ crate::utils::get_unimplemented_payment_method_error_message("Santander"),+ )+ .into()),+ },_ => Err(errors::ConnectorError::NotImplemented(crate::utils::get_unimplemented_payment_method_error_message("Santander"),))?,@@ -247,124 +355,194 @@ impl TryFrom<&SantanderRouterData<&PaymentsSyncRouterData>> for SantanderPSyncBoimplTryFrom<(&SantanderRouterData<&PaymentsAuthorizeRouterData>,- &VoucherData,+ &BoletoVoucherData,)> for SantanderPaymentRequest{type Error = Error;fn try_from(value: (&SantanderRouterData<&PaymentsAuthorizeRouterData>,- &VoucherData,+ &BoletoVoucherData,),) -> Result<Self, Self::Error> {let santander_mca_metadata =SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;- let voucher_data = match &value.0.router_data.request.payment_method_data {- PaymentMethodData::Voucher(VoucherData::Boleto(boleto_data)) => boleto_data,- _ => {- return Err(errors::ConnectorError::NotImplemented(- crate::utils::get_unimplemented_payment_method_error_message("Santander"),- )- .into());- }- };+ let boleto_mca_metadata = santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;- let nsu_code = if value- .0- .router_data- .is_payment_id_from_merchant- .unwrap_or(false)- && value.0.router_data.payment_id.len() > 20- {- return Err(errors::ConnectorError::MaxFieldLengthViolated {- connector: "Santander".to_string(),- field_name: "payment_id".to_string(),- max_length: 20,- received_length: value.0.router_data.payment_id.len(),- }- .into());- } else {- value.0.router_data.payment_id.clone()- };+ let nsu_code = Some(value.0.router_data.connector_request_reference_id.clone());- Ok(Self::Boleto(Box::new(SantanderBoletoPaymentRequest {- environment: Environment::from(router_env::env::which()),- nsu_code,- nsu_date: OffsetDateTime::now_utc()- .date()- .format(&time::macros::format_description!("[year]-[month]-[day]"))- .change_context(errors::ConnectorError::DateFormattingFailed)?,- covenant_code: santander_mca_metadata.covenant_code.clone(),- bank_number: voucher_data.bank_number.clone().ok_or_else(|| {- errors::ConnectorError::MissingRequiredField {- field_name: "document_type",- }- })?, // size: 13- client_number: Some(value.0.router_data.get_customer_id()?),- due_date: voucher_data.due_date.clone().ok_or(- errors::ConnectorError::MissingRequiredField {- field_name: "due_date",- },- )?,- issue_date: OffsetDateTime::now_utc()- .date()- .format(&time::macros::format_description!("[year]-[month]-[day]"))- .change_context(errors::ConnectorError::DateFormattingFailed)?,- currency: Some(value.0.router_data.request.currency),- nominal_value: value.0.amount.to_owned(),- participant_code: value+ let bank_number = nsu_code.clone();++ let (due_date, payment_type, document_kind) = {+ let details = value.0.router_data.request- .merchant_order_reference_id- .clone(),- payer: Payer {- name: value.0.router_data.get_billing_full_name()?,- document_type: voucher_data.document_type.ok_or_else(|| {+ .feature_metadata+ .as_ref()+ .and_then(|fm| fm.boleto_additional_details.as_ref())+ .ok_or_else(|| errors::ConnectorError::MissingRequiredField {+ field_name: "feature_metadata.boleto_additional_details",+ })?;++ (+ Some(details.due_date.as_ref().copied().ok_or_else(|| {errors::ConnectorError::MissingRequiredField {- field_name: "document_type",+ field_name: "feature_metadata.boleto_additional_details.due_date",}- })?,- document_number: voucher_data.social_security_number.clone(),- address: Secret::new(- [- value.0.router_data.get_billing_line1()?,- value.0.router_data.get_billing_line2()?,+ })?),+ Some(details.payment_type.as_ref().copied().ok_or_else(|| {+ errors::ConnectorError::MissingRequiredField {+ field_name: "feature_metadata.boleto_additional_details.payment_type",+ }+ })?),+ Some(details.document_kind.as_ref().copied().ok_or_else(|| {+ errors::ConnectorError::MissingRequiredField {+ field_name: "feature_metadata.boleto_additional_details.document_kind",+ }+ })?),+ )+ };++ let covenant_code = value+ .0+ .router_data+ .request+ .feature_metadata+ .clone()+ .and_then(|data| {+ data.get_optional_boleto_covenant_code()+ .or(Some(boleto_mca_metadata.covenant_code.clone()))+ });++ let key = Some(Key {+ key_type: value+ .0+ .router_data+ .request+ .feature_metadata+ .as_ref()+ .and_then(|data| {+ data.get_boleto_pix_key_and_value()+ .0+ .map(SantanderPixKeyType::from)+ })+ .or(boleto_mca_metadata.pix_key_type),+ dict_key: value+ .0+ .router_data+ .request+ .feature_metadata+ .as_ref()+ .and_then(|data| data.get_boleto_pix_key_and_value().1)+ .or(boleto_mca_metadata.pix_key_value.clone()),+ });++ let messages = value+ .0+ .router_data+ .request+ .billing_descriptor+ .clone()+ .and_then(|data| {+ data.statement_descriptor.map(|s| {+ vec![+ s,+ value.0.router_data.description.clone().unwrap_or_default(),]- .map(|s| s.expose())- .join(" "),- ),- neighborhood: value.0.router_data.get_billing_line1()?,- city: value.0.router_data.get_billing_city()?,- state: value.0.router_data.get_billing_state()?,- zipcode: value.0.router_data.get_billing_zip()?,- },+ })+ });++ let customer_document_details = value+ .0+ .router_data+ .customer_document_details+ .clone()+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "customer.document_details",+ })?;++ let (document_type, document_number) = match customer_document_details.document_type {+ common_types::customers::DocumentKind::Cpf => (+ SantanderDocumentKind::Cpf,+ Some(customer_document_details.document_number),+ ),+ common_types::customers::DocumentKind::Cnpj => (+ SantanderDocumentKind::Cnpj,+ Some(customer_document_details.document_number),+ ),+ };++ let order_id = value+ .0+ .router_data+ .request+ .merchant_order_reference_id+ .clone();++ let payer = Some(Payer {+ name: value.0.router_data.get_billing_full_name()?,+ document_type,+ document_number,+ address: Some(Secret::new(+ [+ value.0.router_data.get_billing_line1()?,+ value.0.router_data.get_billing_line2()?,+ ]+ .map(|s| s.expose())+ .join(" "),+ )),+ neighborhood: Some(value.0.router_data.get_billing_line1()?),+ city: Some(Secret::new(value.0.router_data.get_billing_city()?)),+ state: Some(value.0.router_data.get_billing_state()?),+ zip_code: Some(value.0.router_data.get_billing_zip()?),+ });++ Ok(Self::Boleto(Box::new(SantanderBoletoPaymentRequest {+ environment: Some(Environment::Producao),+ nsu_code,+ nsu_date: Some(+ time::OffsetDateTime::now_utc()+ .date()+ .format(&time::macros::format_description!("[year]-[month]-[day]"))+ .change_context(errors::ConnectorError::DateFormattingFailed)?,+ ),+ covenant_code,+ bank_number,+ client_number: order_id.clone(),+ due_date: Some(format_as_date_only(due_date)?),+ issue_date: Some(+ time::OffsetDateTime::now_utc()+ .date()+ .format(&time::macros::format_description!("[year]-[month]-[day]"))+ .change_context(errors::ConnectorError::DateFormattingFailed)?,+ ),+ nominal_value: Some(value.0.amount.to_owned()),+ participant_code: order_id,+ payer,beneficiary: None,- document_kind: BoletoDocumentKind::BillProposal, // to change- discount: Some(Discount {- discount_type: DiscountType::Free,- discount_one: None,- discount_two: None,- discount_three: None,- }),- fine_percentage: voucher_data.fine_percentage.clone(),- fine_quantity_days: voucher_data.fine_quantity_days.clone(),- interest_percentage: voucher_data.interest_percentage.clone(),+ document_kind: document_kind.map(SantanderBoletoDocumentKind::from),+ discount: None,+ fine_percentage: None,+ fine_quantity_days: None,+ interest_percentage: None,deduction_value: None,protest_type: None,protest_quantity_days: None,- write_off_quantity_days: voucher_data.write_off_quantity_days.clone(),- payment_type: PaymentType::Registration,+ write_off_quantity_days: None,+ payment_type: payment_type.map(SantanderBoletoPaymentType::from),parcels_quantity: None,value_type: None,min_value_or_percentage: None,max_value_or_percentage: None,iof_percentage: None,sharing: None,- key: None,tx_id: None,- messages: voucher_data.messages.clone(),+ key,+ messages,})))}}@@ -385,295 +563,203 @@ impllet santander_mca_metadata =SantanderMetadataObject::try_from(&value.0.router_data.connector_meta_data)?;- let debtor = Some(SantanderDebtor {- cpf: santander_mca_metadata.cpf.clone(),- name: value.0.router_data.get_billing_full_name()?,- });+ let pix_mca_metadata = santander_mca_metadata+ .pix+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;++ let customer_document_details = value+ .0+ .router_data+ .customer_document_details+ .clone()+ .ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "customer.document_details",+ })?;+ let (cpf, cnpj) = match customer_document_details.document_type {+ common_types::customers::DocumentKind::Cpf => {+ (Some(customer_document_details.document_number), None)+ }+ common_types::customers::DocumentKind::Cnpj => {+ (None, Some(customer_document_details.document_number))+ }+ };++ let (calendar, debtor) = match &value+ .0+ .router_data+ .request+ .feature_metadata+ .as_ref()+ .and_then(|f| f.pix_additional_details.as_ref())+ {+ Some(api_models::payments::PixAdditionalDetails::Immediate(val)) => {+ let cal =+ SantanderPixRequestCalendar::Immediate(SantanderPixImmediateCalendarRequest {+ expiracao: val.time,+ });+ let debt = Some(SantanderDebtor {+ cnpj,+ nome: value.0.router_data.get_billing_full_name()?,+ logradouro: None,+ cidade: None,+ uf: None,+ cep: None,+ cpf,+ });++ (Some(cal), debt)+ }+ Some(api_models::payments::PixAdditionalDetails::Scheduled(val)) => {+ let cal =+ SantanderPixRequestCalendar::Scheduled(SantanderPixDueDateCalendarRequest {+ data_de_vencimento: format_as_date_only(Some(val.date))?,+ validade_apos_vencimento: val.validity_after_expiration,+ });++ let debt = Some(SantanderDebtor {+ cpf,+ nome: value.0.router_data.get_billing_full_name()?,+ logradouro: None,+ cidade: None,+ uf: None,+ cep: None,+ cnpj,+ });++ (Some(cal), debt)+ }+ None => {+ let cal =+ SantanderPixRequestCalendar::Immediate(SantanderPixImmediateCalendarRequest {+ expiracao: 3600, // default 1 hour+ });++ let debt = Some(SantanderDebtor {+ cnpj,+ nome: value.0.router_data.get_billing_full_name()?,+ logradouro: None,+ cidade: None,+ uf: None,+ cep: None,+ cpf,+ });++ (Some(cal), debt)+ }+ };++ let info_adicionais = value+ .0+ .router_data+ .request+ .metadata+ .as_ref()+ .and_then(|m| m.as_object())+ .map(|m| {+ m.iter()+ .map(|(k, v)| SantanderAdditionalInfo {+ nome: k.clone().into(),+ valor: v.as_str().unwrap_or_default().to_string(),+ })+ .collect::<Vec<_>>()+ });++ let chave = value+ .0+ .router_data+ .request+ .feature_metadata+ .clone()+ .and_then(|data| data.get_pix_key_and_value().1)+ .or(Some(pix_mca_metadata.pix_key_value.clone()));Ok(Self::PixQR(Box::new(SantanderPixQRPaymentRequest {- calender: SantanderCalendar {- creation: OffsetDateTime::now_utc()- .date()- .format(&time::macros::format_description!("[year]-[month]-[day]"))- .change_context(errors::ConnectorError::DateFormattingFailed)?,- expiration: santander_mca_metadata.expiration_time,- },- debtor,- value: SantanderValue {+ calendario: calendar,+ devedor: debtor,+ valor: Some(SantanderValue {original: value.0.amount.to_owned(),- },- key: santander_mca_metadata.pix_key.clone(),- request_payer: value+ }),+ chave,+ solicitacao_pagador: value.0.router_data.request.billing_descriptor- .as_ref()- .and_then(|descriptor| descriptor.statement_descriptor.clone()),- additional_info: None,+ .clone()+ .and_then(|data| data.statement_descriptor),+ info_adicionais,})))}}-#[derive(Debug, Serialize)]-pub enum SantanderPaymentRequest {- PixQR(Box<SantanderPixQRPaymentRequest>),- Boleto(Box<SantanderBoletoPaymentRequest>),-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Discount {- #[serde(rename = "type")]- pub discount_type: DiscountType,- pub discount_one: Option<DiscountObject>,- pub discount_two: Option<DiscountObject>,- pub discount_three: Option<DiscountObject>,-}--#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderBoletoPaymentRequest {- pub environment: Environment,- pub nsu_code: String,- pub nsu_date: String,- pub covenant_code: String,- pub bank_number: Secret<String>,- pub client_number: Option<id_type::CustomerId>,- pub due_date: String,- pub issue_date: String,- pub currency: Option<enums::Currency>,- pub nominal_value: StringMajorUnit,- pub participant_code: Option<String>,- pub payer: Payer,- pub beneficiary: Option<Beneficiary>,- pub document_kind: BoletoDocumentKind,- pub discount: Option<Discount>,- pub fine_percentage: Option<String>,- pub fine_quantity_days: Option<String>,- pub interest_percentage: Option<String>,- pub deduction_value: Option<FloatMajorUnit>,- pub protest_type: Option<ProtestType>,- pub protest_quantity_days: Option<i64>,- pub write_off_quantity_days: Option<String>,- pub payment_type: PaymentType,- pub parcels_quantity: Option<i64>,- pub value_type: Option<String>,- pub min_value_or_percentage: Option<f64>,- pub max_value_or_percentage: Option<f64>,- pub iof_percentage: Option<f64>,- pub sharing: Option<Sharing>,- pub key: Option<Key>,- pub tx_id: Option<String>,- pub messages: Option<Vec<String>>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Payer {- pub name: Secret<String>,- pub document_type: common_types::customers::DocumentKind,- pub document_number: Option<Secret<String>>,- pub address: Secret<String>,- pub neighborhood: Secret<String>,- pub city: String,- pub state: Secret<String>,- pub zipcode: Secret<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Beneficiary {- pub name: Option<Secret<String>>,- pub document_type: Option<common_types::customers::DocumentKind>,- pub document_number: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "UPPERCASE")]-pub enum Environment {- #[serde(rename = "Teste")]- Sandbox,- #[serde(rename = "Producao")]- Production,-}--#[derive(Debug, Serialize, Deserialize)]-#[serde(rename_all = "UPPERCASE")]-pub enum SantanderDocumentKind {- Cpf,- Cnpj,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum BoletoDocumentKind {- #[serde(rename = "DUPLICATA_MERCANTIL")]- DuplicateMercantil,- #[serde(rename = "DUPLICATA_SERVICO")]- DuplicateService,- #[serde(rename = "NOTA_PROMISSORIA")]- PromissoryNote,- #[serde(rename = "NOTA_PROMISSORIA_RURAL")]- RuralPromissoryNote,- #[serde(rename = "RECIBO")]- Receipt,- #[serde(rename = "APOLICE_SEGURO")]- InsurancePolicy,- #[serde(rename = "BOLETO_CARTAO_CREDITO")]- BillCreditCard,- #[serde(rename = "BOLETO_PROPOSTA")]- BillProposal,- #[serde(rename = "BOLETO_DEPOSITO_APORTE")]- BoletoDepositoAponte,- #[serde(rename = "CHEQUE")]- Check,- #[serde(rename = "NOTA_PROMISSORIA_DIRETA")]- DirectPromissoryNote,- #[serde(rename = "OUTROS")]- Others,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum DiscountType {- #[serde(rename = "ISENTO")]- Free,- #[serde(rename = "VALOR_DATA_FIXA")]- FixedDateValue,- #[serde(rename = "VALOR_DIA_CORRIDO")]- ValueDayConductor,- #[serde(rename = "VALOR_DIA_UTIL")]- ValueWorthDay,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub struct DiscountObject {- pub value: f64,- pub limit_date: String, // YYYY-MM-DD-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum ProtestType {- #[serde(rename = "SEM_PROTESTO")]- WithoutProtest,-- #[serde(rename = "DIAS_CORRIDOS")]- DaysConducted,-- #[serde(rename = "DIAS_UTEIS")]- WorkingDays,-- #[serde(rename = "CADASTRO_CONVENIO")]- RegistrationAgreement,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "UPPERCASE")]-pub enum PaymentType {- #[serde(rename = "REGISTRO")]- Registration,-- #[serde(rename = "DIVERGENTE")]- Divergent,-- #[serde(rename = "PARCIAL")]- Partial,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Sharing {- pub code: String,- pub value: f64,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Key {- #[serde(rename = "type")]- pub key_type: Option<String>,- pub dict_key: Option<String>,-}--#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPixQRCodeRequest {- #[serde(rename = "calendario")]- pub calender: SantanderCalendar,- #[serde(rename = "devedor")]- pub debtor: SantanderDebtor,- #[serde(rename = "valor")]- pub value: SantanderValue,- #[serde(rename = "chave")]- pub key: Secret<String>,- #[serde(rename = "solicitacaoPagador")]- pub request_payer: Option<String>,- #[serde(rename = "infoAdicionais")]- pub additional_info: Option<Vec<SantanderAdditionalInfo>>,-}--#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPixQRPaymentRequest {- #[serde(rename = "calendario")]- pub calender: SantanderCalendar,- #[serde(rename = "devedor")]- pub debtor: Option<SantanderDebtor>,- #[serde(rename = "valor")]- pub value: SantanderValue,- #[serde(rename = "chave")]- pub key: Secret<String>,- #[serde(rename = "solicitacaoPagador")]- pub request_payer: Option<String>,- #[serde(rename = "infoAdicionais")]- pub additional_info: Option<Vec<SantanderAdditionalInfo>>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderDebtor {- pub cpf: Secret<String>,- #[serde(rename = "nome")]- pub name: Secret<String>,+impl From<SantanderPaymentStatus> for AttemptStatus {+ fn from(item: SantanderPaymentStatus) -> Self {+ match item {+ SantanderPaymentStatus::Ativa => Self::AuthenticationPending,+ SantanderPaymentStatus::Concluida => Self::Charged,+ SantanderPaymentStatus::RemovidaPeloUsuarioRecebedor => Self::Voided,+ SantanderPaymentStatus::RemovidaPeloPsp => Self::Failure,+ }+ }}-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderValue {- pub original: StringMajorUnit,+impl From<SantanderBoletoStatus> for AttemptStatus {+ fn from(item: SantanderBoletoStatus) -> Self {+ match item {+ SantanderBoletoStatus::Ativo => Self::AuthenticationPending,+ SantanderBoletoStatus::Baixado => Self::Voided,+ SantanderBoletoStatus::Liquidado => Self::Charged,+ SantanderBoletoStatus::LiquidadoParcialmente => Self::PartialChargedAndChargeable,+ }+ }}-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderAdditionalInfo {- #[serde(rename = "nome")]- pub name: String,- #[serde(rename = "valor")]- pub value: String,+impl From<common_types::customers::DocumentKind> for SantanderDocumentKind {+ fn from(item: common_types::customers::DocumentKind) -> Self {+ match item {+ common_types::customers::DocumentKind::Cnpj => Self::Cnpj,+ common_types::customers::DocumentKind::Cpf => Self::Cpf,+ }+ }}-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum SantanderPaymentStatus {- Active,- Completed,- RemovedByReceivingUser,- RemovedByPSP,+impl From<PixKey> for SantanderPixKeyType {+ fn from(item: PixKey) -> Self {+ match item {+ PixKey::Cpf(_) => Self::Cpf,+ PixKey::Cnpj(_) => Self::Cnpj,+ PixKey::Email(_) => Self::Email,+ PixKey::Phone(_) => Self::Cellular,+ PixKey::EvpToken(_) => Self::Evp,+ }+ }}-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum SantanderVoidStatus {- RemovedByReceivingUser,+impl From<BoletoDocumentKind> for SantanderBoletoDocumentKind {+ fn from(item: BoletoDocumentKind) -> Self {+ match item {+ BoletoDocumentKind::CommercialInvoice => Self::DuplicataMercantil,+ BoletoDocumentKind::ServiceInvoice => Self::DuplicataServico,+ BoletoDocumentKind::PromissoryNote => Self::NotaPromissoria,+ BoletoDocumentKind::RuralPromissoryNote => Self::NotaPromissoriaRural,+ BoletoDocumentKind::Receipt => Self::Recibo,+ BoletoDocumentKind::InsurancePolicy => Self::ApoliceSeguro,+ BoletoDocumentKind::CreditCardInvoice => Self::BoletoCartaoCredito,+ BoletoDocumentKind::Proposal => Self::BoletoProposta,+ BoletoDocumentKind::DepositOrFunding => Self::BoletoDepositoAporte,+ BoletoDocumentKind::Cheque => Self::Cheque,+ BoletoDocumentKind::DirectPromissoryNote => Self::NotaPromissoriaDireta,+ BoletoDocumentKind::Other => Self::Outros,+ }+ }}-impl From<SantanderPaymentStatus> for AttemptStatus {- fn from(item: SantanderPaymentStatus) -> Self {+impl From<BoletoPaymentType> for SantanderBoletoPaymentType {+ fn from(item: BoletoPaymentType) -> Self {match item {- SantanderPaymentStatus::Active => Self::Authorizing,- SantanderPaymentStatus::Completed => Self::Charged,- SantanderPaymentStatus::RemovedByReceivingUser => Self::Voided,- SantanderPaymentStatus::RemovedByPSP => Self::Failure,+ BoletoPaymentType::FixedAmount => Self::Registro,+ BoletoPaymentType::FlexibleAmount => Self::Divergente,+ BoletoPaymentType::Installment => Self::Parcial,}}}@@ -683,149 +769,12 @@ impl From<router_env::env::Env> for Environment {match item {router_env::env::Env::Sandbox| router_env::env::Env::Development- | router_env::env::Env::Integ => Self::Sandbox,- router_env::env::Env::Production => Self::Production,+ | router_env::env::Env::Integ => Self::Teste,+ router_env::env::Env::Production => Self::Producao,}}}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub enum SantanderPaymentsResponse {- PixQRCode(Box<SantanderPixQRCodePaymentsResponse>),- Boleto(Box<SantanderBoletoPaymentsResponse>),-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SantanderBoletoPaymentsResponse {- pub environment: Environment,- pub nsu_code: String,- pub nsu_date: String,- pub covenant_code: String,- pub bank_number: String,- pub client_number: Option<id_type::CustomerId>,- pub due_date: String,- pub issue_date: String,- pub participant_code: Option<String>,- pub nominal_value: StringMajorUnit,- pub payer: Payer,- pub beneficiary: Option<Beneficiary>,- pub document_kind: BoletoDocumentKind,- pub discount: Option<Discount>,- pub fine_percentage: Option<String>,- pub fine_quantity_days: Option<String>,- pub interest_percentage: Option<String>,- pub deduction_value: Option<FloatMajorUnit>,- pub protest_type: Option<ProtestType>,- pub protest_quantity_days: Option<i64>,- pub write_off_quantity_days: Option<String>,- pub payment_type: PaymentType,- pub parcels_quantity: Option<i64>,- pub value_type: Option<String>,- pub min_value_or_percentage: Option<f64>,- pub max_value_or_percentage: Option<f64>,- pub iof_percentage: Option<f64>,- pub sharing: Option<Sharing>,- pub key: Option<Key>,- pub tx_id: Option<String>,- pub messages: Option<Vec<String>>,- pub barcode: Option<String>,- pub digitable_line: Option<Secret<String>>,- pub entry_date: Option<String>,- pub qr_code_pix: Option<String>,- pub qr_code_url: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SantanderPixQRCodePaymentsResponse {- pub status: SantanderPaymentStatus,- #[serde(rename = "calendario")]- pub calendar: SantanderCalendar,- #[serde(rename = "txid")]- pub transaction_id: String,- #[serde(rename = "revisao")]- pub revision: i32,- #[serde(rename = "devedor")]- pub debtor: Option<SantanderDebtor>,- pub location: Option<String>,- #[serde(rename = "valor")]- pub value: SantanderValue,- #[serde(rename = "chave")]- pub key: Secret<String>,- #[serde(rename = "solicitacaoPagador")]- pub request_payer: Option<String>,- #[serde(rename = "infoAdicionais")]- pub additional_info: Option<Vec<SantanderAdditionalInfo>>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPixVoidResponse {- #[serde(rename = "calendario")]- pub calendar: SantanderCalendar,- #[serde(rename = "txid")]- pub transaction_id: String,- #[serde(rename = "revisao")]- pub revision: i32,- #[serde(rename = "devedor")]- pub debtor: Option<SantanderDebtor>,- pub location: Option<String>,- pub status: SantanderPaymentStatus,- #[serde(rename = "valor")]- pub value: SantanderValue,- #[serde(rename = "chave")]- pub key: Secret<String>,- #[serde(rename = "solicitacaoPagador")]- pub request_payer: Option<String>,- #[serde(rename = "infoAdicionais")]- pub additional_info: Option<Vec<SantanderAdditionalInfo>>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct SantanderCalendar {- #[serde(rename = "calendario")]- pub creation: String,- #[serde(rename = "expiracao")]- pub expiration: i32,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub enum SantanderPaymentsSyncResponse {- PixQRCode(Box<SantanderPixPSyncResponse>),- Boleto(Box<SantanderBoletoPSyncResponse>),-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SantanderBoletoPSyncResponse {- pub link: Option<Url>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SantanderPixPSyncResponse {- #[serde(flatten)]- pub base: SantanderPixQRCodePaymentsResponse,- pub pix: Vec<SantanderPix>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPix {- pub end_to_end_id: Secret<String>,- #[serde(rename = "txid")]- pub transaction_id: Secret<String>,- #[serde(rename = "valor")]- pub value: String,- #[serde(rename = "horario")]- pub time: String,- #[serde(rename = "infoPagador")]- pub info_payer: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPaymentsCancelRequest {- pub status: Option<SantanderVoidStatus>,-}-impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, PaymentsResponseData>>for RouterData<F, T, PaymentsResponseData>{@@ -837,11 +786,11 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Paymematch response {SantanderPaymentsSyncResponse::PixQRCode(pix_data) => {- let attempt_status = AttemptStatus::from(pix_data.base.status.clone());+ let attempt_status = AttemptStatus::from(pix_data.status.clone());match attempt_status {AttemptStatus::Failure => {- let response = Err(get_error_response(- Box::new(pix_data.base),+ let response = Err(get_sync_error_response(+ Box::new(*pix_data),item.http_code,attempt_status,));@@ -851,16 +800,20 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme})}_ => {- let connector_metadata = pix_data.pix.first().map(|pix| {- serde_json::json!({- "end_to_end_id": pix.end_to_end_id.clone().expose()- })- });+ let connector_metadata = pix_data+ .pix+ .ok_or_else(|| errors::ConnectorError::ParsingFailed)?+ .first()+ .map(|pix| {+ serde_json::json!({+ "end_to_end_id": pix.end_to_end_id.clone().expose()+ })+ });Ok(Self {- status: AttemptStatus::from(pix_data.base.status),+ status: AttemptStatus::from(pix_data.status),response: Ok(PaymentsResponseData::TransactionResponse {resource_id: ResponseId::ConnectorTransactionId(- pix_data.base.transaction_id.clone(),+ pix_data.txid.clone(),),redirection_data: Box::new(None),mandate_reference: Box::new(None),@@ -876,26 +829,15 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsSyncResponse, T, Payme}}}- SantanderPaymentsSyncResponse::Boleto(boleto_data) => {- let redirection_data = boleto_data.link.clone().map(|url| RedirectForm::Form {- endpoint: url.to_string(),- method: Method::Get,- form_fields: HashMap::new(),- });-+ SantanderPaymentsSyncResponse::Boleto(res) => {+ let status = res.content.first().map(|data| data.status.clone()).ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "status",+ },+ )?;Ok(Self {- status: AttemptStatus::AuthenticationPending,- response: Ok(PaymentsResponseData::TransactionResponse {- resource_id: ResponseId::NoResponseId,- redirection_data: Box::new(redirection_data),- mandate_reference: Box::new(None),- connector_metadata: None,- network_txn_id: None,- connector_response_reference_id: None,- incremental_authorization_allowed: None,- authentication_data: None,- charges: None,- }),+ status: AttemptStatus::from(status),+ response: item.data.response,..item.data})}@@ -914,7 +856,27 @@ pub fn get_error_response(reason: None,status_code,attempt_status: Some(attempt_status),- connector_transaction_id: Some(pix_data.transaction_id.clone()),+ connector_transaction_id: Some(pix_data.txid.clone()),+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ }+}++pub fn get_sync_error_response(+ pix_data: Box<SantanderPixQRCodeSyncResponse>,+ status_code: u16,+ attempt_status: AttemptStatus,+) -> ErrorResponse {+ ErrorResponse {+ code: NO_ERROR_CODE.to_string(),+ message: NO_ERROR_MESSAGE.to_string(),+ reason: None,+ status_code,+ attempt_status: Some(attempt_status),+ connector_transaction_id: Some(pix_data.txid.clone()),connector_response_reference_id: None,network_advice_code: None,network_decline_code: None,@@ -931,7 +893,6 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsRitem: ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>,) -> Result<Self, Self::Error> {let response = item.response.clone();-match response {SantanderPaymentsResponse::PixQRCode(pix_data) => {let attempt_status = AttemptStatus::from(pix_data.status.clone());@@ -950,9 +911,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsR_ => Ok(Self {status: AttemptStatus::from(pix_data.status.clone()),response: Ok(PaymentsResponseData::TransactionResponse {- resource_id: ResponseId::ConnectorTransactionId(- pix_data.transaction_id.clone(),- ),+ resource_id: ResponseId::ConnectorTransactionId(pix_data.txid.clone()),redirection_data: Box::new(None),mandate_reference: Box::new(None),connector_metadata: get_qr_code_data(&item, &pix_data)?,@@ -967,57 +926,46 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsR}}SantanderPaymentsResponse::Boleto(boleto_data) => {+ let qr_code_url = if let Some(data) = boleto_data.qr_code_pix.clone() {+ router_env::logger::debug!("Data to be converted into QR code: {}", data);+ let qr_image = QrImage::new_from_data(data)+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?;+ let url_str = &qr_image.data;+ Some(+ Url::parse(url_str)+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,+ )+ } else {+ None+ };+let voucher_data = VoucherNextStepData {- expires_at: None,digitable_line: boleto_data.digitable_line.clone(),- reference: boleto_data.barcode.ok_or(- errors::ConnectorError::MissingConnectorRedirectionPayload {- field_name: "barcode",- },- )?,- entry_date: boleto_data.entry_date,+ barcode: boleto_data.barcode.clone(),+ expires_at: None,+ expiry_date: Some(boleto_data.due_date),+ reference: boleto_data.nsu_code.clone(),+ entry_date: boleto_data.entry_date.clone(),download_url: None,instructions_url: None,+ qr_code_url,};let connector_metadata = Some(voucher_data.encode_to_value()).transpose().change_context(errors::ConnectorError::ResponseHandlingFailed)?;- let resource_id = match boleto_data.tx_id {- Some(tx_id) => ResponseId::ConnectorTransactionId(tx_id),- None => ResponseId::NoResponseId,- };-- let connector_response_reference_id = Some(- boleto_data- .digitable_line- .as_ref()- .map(|s| s.peek().to_owned())- .clone()- .or_else(|| {- boleto_data.beneficiary.as_ref().map(|beneficiary| {- format!(- "{}.{:?}",- boleto_data.bank_number,- beneficiary.document_number.clone()- )- })- })- .ok_or(errors::ConnectorError::MissingRequiredField {- field_name: "beneficiary.document_number",- })?,- );-Ok(Self {status: AttemptStatus::AuthenticationPending,response: Ok(PaymentsResponseData::TransactionResponse {- resource_id,+ resource_id: ResponseId::ConnectorTransactionId(+ boleto_data.bank_number.clone(),+ ),redirection_data: Box::new(None),mandate_reference: Box::new(None),connector_metadata,network_txn_id: None,- connector_response_reference_id,+ connector_response_reference_id: None,incremental_authorization_allowed: None,authentication_data: None,charges: None,@@ -1029,99 +977,182 @@ impl<F, T> TryFrom<ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsR}}-impl<F, T> TryFrom<ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>>+impl<F, T> TryFrom<ResponseRouterData<F, SantanderVoidResponse, T, PaymentsResponseData>>for RouterData<F, T, PaymentsResponseData>{type Error = error_stack::Report<errors::ConnectorError>;+fn try_from(- item: ResponseRouterData<F, SantanderPixVoidResponse, T, PaymentsResponseData>,+ item: ResponseRouterData<F, SantanderVoidResponse, T, PaymentsResponseData>,) -> Result<Self, Self::Error> {- let response = item.response.clone();- Ok(Self {- status: AttemptStatus::from(item.response.status),- response: Ok(PaymentsResponseData::TransactionResponse {- resource_id: ResponseId::ConnectorTransactionId(response.transaction_id.clone()),- redirection_data: Box::new(None),- mandate_reference: Box::new(None),- connector_metadata: *Box::new(None),- network_txn_id: None,- connector_response_reference_id: None,- incremental_authorization_allowed: None,- authentication_data: None,- charges: None,+ match item.response.clone() {+ SantanderVoidResponse::Pix(res) => Ok(Self {+ status: AttemptStatus::from(res.status),+ response: Ok(PaymentsResponseData::TransactionResponse {+ resource_id: ResponseId::ConnectorTransactionId(res.txid.clone()),+ redirection_data: Box::new(None),+ mandate_reference: Box::new(None),+ connector_metadata: None,+ network_txn_id: None,+ connector_response_reference_id: None,+ incremental_authorization_allowed: None,+ charges: None,+ authentication_data: None,+ }),+ ..item.data}),- ..item.data- })+ SantanderVoidResponse::Boleto(_) => Ok(Self {+ status: AttemptStatus::Voided,+ response: item.data.response,+ ..item.data+ }),+ }}}impl TryFrom<&PaymentsCancelRouterData> for SantanderPaymentsCancelRequest {type Error = Error;- fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {++ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {+ let santander_mca_metadata = SantanderMetadataObject::try_from(&item.connector_meta_data)?;++ match item.payment_method {+ enums::PaymentMethod::BankTransfer => {+ let pix_req = SantanderPixCancelRequest::try_from(item)?;+ Ok(Self::PixQR(pix_req))+ }+ enums::PaymentMethod::Voucher => {+ let boleto_req =+ SantanderBoletoCancelRequest::try_from((item, santander_mca_metadata))?;+ Ok(Self::Boleto(boleto_req))+ }+ _ => Err(errors::ConnectorError::MissingRequiredField {+ field_name: "payment_method",+ }+ .into()),+ }+ }+}++impl TryFrom<(&PaymentsCancelRouterData, SantanderMetadataObject)>+ for SantanderBoletoCancelRequest+{+ type Error = Error;+ fn try_from(+ value: (&PaymentsCancelRouterData, SantanderMetadataObject),+ ) -> Result<Self, Self::Error> {+ let boleto_mca_metadata = value+ .1+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;Ok(Self {- status: Some(SantanderVoidStatus::RemovedByReceivingUser),+ operation: SantanderBoletoCancelOperation::Baixar,+ covenant_code: boleto_mca_metadata.covenant_code.clone(),+ bank_number: extract_bank_number(value.0.request.connector_meta.clone())?,})}}+impl TryFrom<&PaymentsCancelRouterData> for SantanderPixCancelRequest {+ type Error = Error;+ fn try_from(_value: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {+ Ok(Self {+ status: Some(SantanderVoidStatus::RemovidaPeloUsuarioRecebedor),+ })+ }+}++fn extract_bank_number(value: Option<Value>) -> Result<String, errors::ConnectorError> {+ let value = value.ok_or_else(|| errors::ConnectorError::NoConnectorMetaData)?;++ let map = value+ .as_object()+ .ok_or_else(|| errors::ConnectorError::NoConnectorMetaData)?;++ let bank_number = map+ .get("bank_number")+ .ok_or_else(|| errors::ConnectorError::NoConnectorMetaData)?;++ let bank_number_str = bank_number+ .as_str()+ .ok_or_else(|| errors::ConnectorError::NoConnectorMetaData)?+ .to_string();+ Ok(bank_number_str)+}+fn get_qr_code_data<F, T>(item: &ResponseRouterData<F, SantanderPaymentsResponse, T, PaymentsResponseData>,pix_data: &SantanderPixQRCodePaymentsResponse,) -> CustomResult<Option<Value>, errors::ConnectorError> {- let santander_mca_metadata = SantanderMetadataObject::try_from(&item.data.connector_meta_data)?;-- let response = pix_data.clone();- let expiration_time = response.calendar.expiration;-- let expiration_i64 = i64::from(expiration_time);+ // Scheduled type Pix QR Code Response already has a formed emv string data for QR Code+ // HS doesnt need to create it+ if let Some(data) = pix_data.pix_copia_e_cola.clone() {+ return convert_pix_data_to_value(data, Some(ExpiryType::Scheduled));+ }- let rfc3339_expiry = (OffsetDateTime::now_utc() + time::Duration::seconds(expiration_i64))- .format(&time::format_description::well_known::Rfc3339)- .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?;+ let santander_mca_metadata = SantanderMetadataObject::try_from(&item.data.connector_meta_data)?;- let qr_expiration_duration = OffsetDateTime::parse(- rfc3339_expiry.as_str(),- &time::format_description::well_known::Rfc3339,- )- .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?- .unix_timestamp()- * 1000;+ let pix_mca_metadata = santander_mca_metadata+ .pix+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;- let merchant_city = santander_mca_metadata.merchant_city.as_str();+ let response = pix_data.clone();- let merchant_name = santander_mca_metadata.merchant_name.as_str();+ let merchant_city = pix_mca_metadata.merchant_city.as_str();- let payload_url = if let Some(location) = response.location {- location- } else {- return Err(errors::ConnectorError::ResponseHandlingFailed)?;- };+ let merchant_name = pix_mca_metadata.merchant_name.as_str();let amount_i64 = StringMajorUnitForConnector- .convert_back(response.value.original, enums::Currency::BRL)+ .convert_back(response.valor.original, enums::Currency::BRL).change_context(errors::ConnectorError::ResponseHandlingFailed)?.get_amount_as_i64();let amount_string = amount_i64.to_string();let amount = amount_string.as_str();+ let location = pix_data+ .location+ .clone()+ .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;+let dynamic_pix_code = generate_emv_string(- payload_url.as_str(),- merchant_name,merchant_city,- Some(amount),- Some(response.transaction_id.as_str()),- );+ amount,+ item.data.get_billing_country()?,+ merchant_name,+ pix_data.txid.clone(),+ location,+ )?;++ let variant = if pix_data.pix_copia_e_cola.is_some() {+ Some(ExpiryType::Scheduled)+ } else {+ Some(ExpiryType::Immediate)+ };- let image_data = QrImage::new_from_data(dynamic_pix_code.clone())+ convert_pix_data_to_value(dynamic_pix_code, variant)+}++fn convert_pix_data_to_value(+ data: String,+ variant: Option<ExpiryType>,+) -> CustomResult<Option<Value>, errors::ConnectorError> {+ if router_env::which() != router_env::env::Env::Production {+ // The data string is the EMV string which is used to generate the QR code. We are generating the QR code and then converting it to a data URL to be sent to the client. This is because the client can directly use the data URL to display the QR code without needing to generate it on their end.+ // We are logging it because in dev env, we won't be able to scan this QR and complete the payment. We would need to send this EMV to the Santander Support Team to finish the payment on their end so that we can test other flows like PSync/Refund/RSync etc+ router_env::logger::debug!("Data to be converted into QR code: {}", data);+ }+ let image_data = QrImage::new_from_data(data.clone()).change_context(errors::ConnectorError::ResponseHandlingFailed)?;let image_data_url = Url::parse(image_data.data.clone().as_str()).change_context(errors::ConnectorError::ResponseHandlingFailed)?;- let qr_code_info = QrCodeInformation::QrDataUrl {- image_data_url,- display_to_timestamp: Some(qr_expiration_duration),+ let qr_code_info = QrCodeInformation::QrCodeUrl {+ image_data_url: image_data_url.clone(),+ qr_code_url: image_data_url,+ display_to_timestamp: None,+ expiry_type: variant,};Some(qr_code_info.encode_to_value())@@ -1129,62 +1160,25 @@ fn get_qr_code_data<F, T>(.change_context(errors::ConnectorError::ResponseHandlingFailed)}-#[derive(Default, Debug, Serialize)]-pub struct SantanderRefundRequest {- #[serde(rename = "valor")]- pub value: StringMajorUnit,-}-impl<F> TryFrom<&SantanderRouterData<&RefundsRouterData<F>>> for SantanderRefundRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &SantanderRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {Ok(Self {- value: item.amount.to_owned(),+ valor: item.amount.to_owned(),})}}-#[derive(Debug, Serialize, Deserialize, Clone)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum SantanderRefundStatus {- InProcessing,- Returned,- NotDone,-}-impl From<SantanderRefundStatus> for enums::RefundStatus {fn from(item: SantanderRefundStatus) -> Self {match item {- SantanderRefundStatus::Returned => Self::Success,- SantanderRefundStatus::NotDone => Self::Failure,- SantanderRefundStatus::InProcessing => Self::Pending,+ SantanderRefundStatus::Devolvido => Self::Success,+ SantanderRefundStatus::NaoRealizado => Self::Failure,+ SantanderRefundStatus::EmProcessamento => Self::Pending,}}}-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderRefundResponse {- pub id: Secret<String>,- pub rtr_id: Secret<String>,- #[serde(rename = "valor")]- pub value: StringMajorUnit,- #[serde(rename = "horario")]- pub time: SantanderTime,- pub status: SantanderRefundStatus,- #[serde(rename = "motivo")]- pub reason: String,-}--#[derive(Default, Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderTime {- #[serde(rename = "solicitacao")]- pub request: Option<String>,- #[serde(rename = "liquidacao")]- pub liquidation: Option<String>,-}-impl<F> TryFrom<RefundsResponseRouterData<F, SantanderRefundResponse>> for RefundsRouterData<F> {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(@@ -1200,180 +1194,236 @@ impl<F> TryFrom<RefundsResponseRouterData<F, SantanderRefundResponse>> for Refun}}-#[derive(Debug, Serialize, Deserialize)]-pub enum SantanderErrorResponse {- PixQrCode(SantanderPixQRCodeErrorResponse),- Boleto(SantanderBoletoErrorResponse),+impl TryFrom<&PaymentsUpdateMetadataRouterData> for SantanderPaymentRequest {+ type Error = Error;+ fn try_from(value: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {+ match value.request.payment_method_type {+ Some(common_enums::PaymentMethodType::Pix) => {+ let pix_qr = SantanderPixQRPaymentRequest::try_from(value)?;+ Ok(Self::PixQR(Box::new(pix_qr)))+ }+ Some(common_enums::PaymentMethodType::Boleto) => {+ let boleto = SantanderBoletoPaymentRequest::try_from(value)?;+ Ok(Self::Boleto(Box::new(boleto)))+ }+ _ => Err(errors::ConnectorError::NotImplemented(+ crate::utils::get_unimplemented_payment_method_error_message("Santander"),+ ))?,+ }+ }}-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SantanderBoletoErrorResponse {- #[serde(rename = "_errorCode")]- pub error_code: i64,-- #[serde(rename = "_message")]- pub error_message: String,-- #[serde(rename = "_details")]- pub issuer_error_message: String,-- #[serde(rename = "_timestamp")]- pub timestamp: String,+impl TryFrom<&PaymentsUpdateMetadataRouterData> for SantanderBoletoPaymentRequest {+ type Error = Error;- #[serde(rename = "_traceId")]- pub trace_id: String,+ fn try_from(value: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {+ let santander_mca_metadata = SantanderMetadataObject::try_from(&value.connector_meta_data)?;- #[serde(rename = "_errors")]- pub errors: Option<Vec<ErrorObject>>,-}+ let boleto_mca_metadata = santander_mca_metadata+ .boleto+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ErrorObject {- #[serde(rename = "_code")]- pub code: Option<i64>,+ let due_date = Some(+ value+ .request+ .feature_metadata+ .as_ref()+ .and_then(|fm| fm.boleto_additional_details.as_ref())+ .and_then(|details| details.due_date)+ .ok_or_else(|| errors::ConnectorError::MissingRequiredField {+ field_name: "feature_metadata.boleto_additional_details.due_date",+ })?,+ );- #[serde(rename = "_field")]- pub field: Option<String>,+ let covenant_code = value.request.feature_metadata.clone().and_then(|data| {+ data.get_optional_boleto_covenant_code()+ .or(Some(boleto_mca_metadata.covenant_code.clone()))+ });- #[serde(rename = "_message")]- pub message: String,+ Ok(Self {+ bank_number: Some(value.connector_request_reference_id.clone()),+ covenant_code,+ environment: None,+ due_date: Some(format_as_date_only(due_date)?),+ nsu_code: None,+ nsu_date: None,+ client_number: None,+ issue_date: None,+ nominal_value: None,+ participant_code: None,+ payer: None,+ beneficiary: None,+ document_kind: None,+ discount: None,+ fine_percentage: None,+ fine_quantity_days: None,+ interest_percentage: None,+ deduction_value: None,+ protest_type: None,+ protest_quantity_days: None,+ write_off_quantity_days: None,+ payment_type: None,+ parcels_quantity: None,+ value_type: None,+ min_value_or_percentage: None,+ max_value_or_percentage: None,+ iof_percentage: None,+ sharing: None,+ key: None,+ tx_id: None,+ messages: None,+ })+ }}-#[derive(Debug, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderPixQRCodeErrorResponse {- #[serde(rename = "type")]- pub field_type: Secret<String>,- pub title: String,- pub status: i64,- pub detail: Option<String>,- pub correlation_id: Option<String>,- #[serde(rename = "violacoes")]- pub violations: Option<Vec<SantanderViolations>>,-}+impl TryFrom<&PaymentsUpdateMetadataRouterData> for SantanderPixQRPaymentRequest {+ type Error = Error;-#[derive(Debug, Serialize, Deserialize)]-pub struct SantanderViolations {- #[serde(rename = "razao")]- pub reason: Option<String>,- #[serde(rename = "propriedade")]- pub property: Option<String>,- #[serde(rename = "valor")]- pub value: Option<String>,-}+ fn try_from(value: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {+ match value.request.payment_method_type {+ Some(common_enums::PaymentMethodType::Pix) => {+ let santander_mca_metadata =+ SantanderMetadataObject::try_from(&value.connector_meta_data)?;+ let pix_mca_metadata = santander_mca_metadata+ .pix+ .ok_or(errors::ConnectorError::NoConnectorMetaData)?;+ let calendar = match &value+ .request+ .feature_metadata+ .as_ref()+ .and_then(|f| f.pix_additional_details.as_ref())+ {+ Some(api_models::payments::PixAdditionalDetails::Immediate(val)) => {+ let cal = SantanderPixRequestCalendar::Immediate(+ SantanderPixImmediateCalendarRequest {+ expiracao: val.time,+ },+ );+ Some(cal)+ }+ Some(api_models::payments::PixAdditionalDetails::Scheduled(val)) => {+ let cal = SantanderPixRequestCalendar::Scheduled(+ SantanderPixDueDateCalendarRequest {+ data_de_vencimento: format_as_date_only(Some(val.date))?,+ validade_apos_vencimento: val.validity_after_expiration,+ },+ );+ Some(cal)+ }+ None => {+ let cal = SantanderPixRequestCalendar::Immediate(+ SantanderPixImmediateCalendarRequest { expiracao: 3600 },+ );-#[derive(Debug, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SantanderWebhookBody {- pub message: MessageCode, // meaning of this enum variant is not clear- pub function: FunctionType, // event type of the webhook- pub payment_type: WebhookPaymentType,- pub issue_date: String,- pub payment_date: String,- pub bank_code: String,- pub payment_channel: PaymentChannel,- pub payment_kind: PaymentKind,- pub covenant: String,- pub type_of_person_agreement: common_types::customers::DocumentKind,- pub agreement_document: String,- pub bank_number: String,- pub client_number: String,- pub participant_code: String,- pub tx_id: String,- pub payer_document_type: common_types::customers::DocumentKind,- pub payer_document_number: String,- pub payer_name: String,- pub final_beneficiary_document_type: common_types::customers::DocumentKind,- pub final_beneficiary_document_number: String,- pub final_beneficiary_name: String,- pub due_date: String,- pub nominal_value: StringMajorUnit,- pub payed_value: String,- pub interest_value: String,- pub fine: String,- pub deduction_value: String,- pub rebate_value: String,- pub iof_value: String,-}+ Some(cal)+ }+ };-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum MessageCode {- Wbhkpagest,-}+ let chave = value+ .request+ .feature_metadata+ .clone()+ .and_then(|data| data.get_pix_key_and_value().1)+ .or(Some(pix_mca_metadata.pix_key_value.clone()));-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum FunctionType {- Pagamento, // Payment- Estorno, // Refund+ Ok(Self {+ calendario: calendar,+ devedor: None,+ valor: None,+ chave,+ solicitacao_pagador: None,+ info_adicionais: None,+ })+ }+ _ => Err(errors::ConnectorError::NotImplemented(+ crate::utils::get_unimplemented_payment_method_error_message("Santander"),+ ))?,+ }+ }}-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-pub enum WebhookPaymentType {- Santander,- OutrosBancos,- Pix,+impl<F>+ TryFrom<+ ResponseRouterData<+ F,+ SantanderUpdateMetadataResponse,+ PaymentsUpdateMetadataData,+ PaymentsResponseData,+ >,+ > for RouterData<F, PaymentsUpdateMetadataData, PaymentsResponseData>+where+ F: Clone,+{+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ item: ResponseRouterData<+ F,+ SantanderUpdateMetadataResponse,+ PaymentsUpdateMetadataData,+ PaymentsResponseData,+ >,+ ) -> Result<Self, Self::Error> {+ let status = if item.http_code == 200 {+ common_enums::PaymentResourceUpdateStatus::Success+ } else {+ common_enums::PaymentResourceUpdateStatus::Failure+ };+ match item.response {+ SantanderUpdateMetadataResponse::Pix(_) => Ok(Self {+ response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }),+ ..item.data+ }),+ SantanderUpdateMetadataResponse::Boleto(_) => Ok(Self {+ response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }),+ ..item.data+ }),+ }+ }}-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-/// Represents the channel through which a boleto payment was made.-pub enum PaymentChannel {- /// Payment made at a bank branch or ATM (self-service).- AgenciasAutoAtendimento,-- /// Payment made through online banking.- InternetBanking,-- /// Payment made at a physical correspondent agent (e.g., convenience stores, partner outlets).- CorrespondenteBancarioFisico,-- /// Payment made via Santander’s call center.- CentralDeAtendimento,-- /// Payment made via electronic file, typically for bulk company payments.- ArquivoEletronico,-- /// Payment made via DDA (Débito Direto Autorizado) / electronic bill presentment system.- Dda,+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)?;- /// Payment made via digital correspondent channels (apps, kiosks, digital partners).- CorrespondenteBancarioDigital,+ let santander_variant = 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)?)}-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]-/// Represents the type of payment instrument used to pay a boleto.-pub enum PaymentKind {- /// Payment made in cash or physical form (not via account or card).- Especie,-- /// Payment made via direct debit from a bank account.- DebitoEmConta,+fn extract_boleto_components(input: &str) -> Result<NsuComposite, errors::ConnectorError> {+ let parts: Vec<&str> = input.split('.').collect();- /// Payment made via credit card.- CartaoDeCredito,+ let [nsu_code, nsu_date, environment, covenant_code, bank_number] = parts+ .as_slice()+ .try_into()+ .map_err(|_| errors::ConnectorError::ParsingFailed)?;- /// Payment made via check.- Cheque,+ Ok(NsuComposite {+ nsu_code: nsu_code.to_string(),+ nsu_date: nsu_date.to_string(),+ environment: environment.to_string(),+ covenant_code: covenant_code.to_string(),+ bank_number: bank_number.to_string(),+ })}-pub(crate) fn get_webhook_object_from_body(- body: &[u8],-) -> CustomResult<SantanderWebhookBody, common_utils::errors::ParsingError> {- let webhook: SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?;+pub fn format_as_date_only(+ date_time: Option<time::PrimitiveDateTime>,+) -> Result<String, errors::ConnectorError> {+ let dt = date_time.ok_or(errors::ConnectorError::MissingRequiredField {+ field_name: "due_date",+ })?;- Ok(webhook)-}--pub(crate) fn get_santander_webhook_event(- event_type: FunctionType,-) -> api_models::webhooks::IncomingWebhookEvent {- // need to confirm about the other possible webhook event statues, as of now only two known- match event_type {- FunctionType::Pagamento => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess,- FunctionType::Estorno => api_models::webhooks::IncomingWebhookEvent::RefundSuccess,- }+ let format = time::macros::format_description!("[year]-[month]-[day]");+ dt.format(&format)+ .map_err(|_| errors::ConnectorError::ParsingFailed)}diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rsindex 77c4f582b3..7886073d5b 100644--- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs@@ -4065,14 +4065,19 @@ impl TryFrom<&PaymentsCancelRouterData> for CancelRequest {#[derive(Debug, Serialize)]pub struct UpdateMetadataRequest {#[serde(flatten)]- pub metadata: HashMap<String, String>,+ pub metadata: Option<HashMap<String, String>>,}impl TryFrom<&PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest {type Error = error_stack::Report<ConnectorError>;fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {- let metadata = format_metadata_for_request(item.request.metadata.clone());- Ok(Self { metadata })+ Ok(Self {+ metadata: item+ .request+ .metadata+ .as_ref()+ .map(|data| format_metadata_for_request(data.clone())),+ })}}diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rsindex d32e5b6a10..72d154737b 100644--- a/crates/hyperswitch_connectors/src/constants.rs+++ b/crates/hyperswitch_connectors/src/constants.rs@@ -36,6 +36,7 @@ pub(crate) mod headers {pub(crate) const X_SIGNATURE: &str = "X-Signature";pub(crate) const SOAP_ACTION: &str = "SOAPAction";pub(crate) const X_PROFILE_ID: &str = "X-Profile-Id";+ pub(crate) const X_APPLICATION_KEY: &str = "X-Application-Key";}/// Unsupported response type error messagediff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex cbe593fa7b..881cd1e153 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -1163,7 +1163,6 @@ default_imp_for_update_metadata!(connectors::Razorpay,connectors::Recurly,connectors::Redsys,- connectors::Santander,connectors::Shift4,connectors::Sift,connectors::Silverflow,diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rsindex 773664c3bc..ff24a8d4ea 100644--- a/crates/hyperswitch_connectors/src/utils.rs+++ b/crates/hyperswitch_connectors/src/utils.rs@@ -6340,7 +6340,7 @@ pub trait ForeignTryFrom<F>: Sized {fn foreign_try_from(from: F) -> Result<Self, Self::Error>;}-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct QrImage {pub data: String,}@@ -7450,6 +7450,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(.request.partner_merchant_identifier_details.clone(),+ feature_metadata: None,}}@@ -7523,6 +7524,25 @@ pub fn generate_12_digit_number() -> u64 {rng.gen_range(100_000_000_000..=999_999_999_999)}+pub fn generate_random_string_containing_digits(min_len: usize, max_len: usize) -> String {+ let mut rng = rand::thread_rng();+ let len = rng.gen_range(min_len..=max_len);++ (0..len)+ .map(|_| char::from(rng.gen_range(b'0'..=b'9')))+ .collect()+}++pub fn generate_alphanumeric_code(min_len: usize, max_len: usize) -> String {+ let mut rng = rand::thread_rng();+ let len = rng.gen_range(min_len..=max_len);++ rng.sample_iter(&rand::distributions::Alphanumeric)+ .take(len)+ .map(char::from)+ .collect()+}+/// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces.pub fn normalize_string(value: String) -> Result<String, regex::Error> {let nfkd_value = value.nfkd().collect::<String>();diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rsindex 9e1a34d04d..be50bd2c9b 100644--- a/crates/hyperswitch_domain_models/src/lib.rs+++ b/crates/hyperswitch_domain_models/src/lib.rs@@ -118,6 +118,9 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {redirect_response,search_tags,apple_pay_recurring_details,+ pix_additional_details,+ boleto_additional_details,+ ..} = from;Self {@@ -126,6 +129,10 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {apple_pay_recurring_details: apple_pay_recurring_details.map(ApplePayRecurringDetails::convert_from),gateway_system: None,+ pix_additional_details: pix_additional_details+ .map(diesel_models::types::PixAdditionalDetails::convert_from),+ boleto_additional_details: boleto_additional_details+ .map(diesel_models::types::BoletoAdditionalDetails::convert_from),}}@@ -134,15 +141,81 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {redirect_response,search_tags,apple_pay_recurring_details,+ pix_additional_details,+ boleto_additional_details,..} = self;ApiFeatureMetadata {- redirect_response: redirect_response- .map(|redirect_response| redirect_response.convert_back()),+ redirect_response: redirect_response.map(|v| v.convert_back()),search_tags,- apple_pay_recurring_details: apple_pay_recurring_details- .map(|value| value.convert_back()),+ apple_pay_recurring_details: apple_pay_recurring_details.map(|v| v.convert_back()),+ pix_additional_details: pix_additional_details.map(|v| v.convert_back()),+ boleto_additional_details: boleto_additional_details.map(|v| v.convert_back()),+ }+ }+}++impl ApiModelToDieselModelConvertor<api_models::payments::BoletoAdditionalDetails>+ for diesel_models::types::BoletoAdditionalDetails+{+ fn convert_from(from: api_models::payments::BoletoAdditionalDetails) -> Self {+ Self {+ due_date: from.due_date,+ document_kind: from.document_kind,+ payment_type: from.payment_type,+ covenant_code: from.covenant_code,+ pix_key: from.pix_key,+ }+ }++ fn convert_back(self) -> api_models::payments::BoletoAdditionalDetails {+ api_models::payments::BoletoAdditionalDetails {+ due_date: self.due_date,+ document_kind: self.document_kind,+ payment_type: self.payment_type,+ covenant_code: self.covenant_code,+ pix_key: self.pix_key,+ }+ }+}++impl ApiModelToDieselModelConvertor<api_models::payments::PixAdditionalDetails>+ for diesel_models::types::PixAdditionalDetails+{+ fn convert_from(from: api_models::payments::PixAdditionalDetails) -> Self {+ match from {+ api_models::payments::PixAdditionalDetails::Immediate(v) => {+ Self::Immediate(diesel_models::types::ImmediateExpirationTime {+ time: v.time,+ pix_key: v.pix_key,+ })+ }+ api_models::payments::PixAdditionalDetails::Scheduled(v) => {+ Self::Scheduled(diesel_models::types::ScheduledExpirationTime {+ date: v.date,+ validity_after_expiration: v.validity_after_expiration,+ pix_key: v.pix_key,+ })+ }+ }+ }++ fn convert_back(self) -> api_models::payments::PixAdditionalDetails {+ match self {+ Self::Immediate(v) => api_models::payments::PixAdditionalDetails::Immediate(+ api_models::payments::ImmediateExpirationTime {+ time: v.time,+ pix_key: v.pix_key,+ },+ ),+ Self::Scheduled(v) => api_models::payments::PixAdditionalDetails::Scheduled(+ api_models::payments::ScheduledExpirationTime {+ date: v.date,+ validity_after_expiration: v.validity_after_expiration,+ pix_key: v.pix_key,+ },+ ),}}}@@ -155,6 +228,8 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {search_tags,apple_pay_recurring_details,revenue_recovery: payment_revenue_recovery_metadata,+ pix_additional_details,+ boleto_additional_details,} = from;Self {@@ -164,6 +239,10 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {.map(ApplePayRecurringDetails::convert_from),payment_revenue_recovery_metadata: payment_revenue_recovery_metadata.map(PaymentRevenueRecoveryMetadata::convert_from),+ pix_additional_details: pix_additional_details+ .map(diesel_models::types::PixAdditionalDetails::convert_from),+ boleto_additional_details: boleto_additional_details+ .map(diesel_models::types::BoletoAdditionalDetails::convert_from),}}@@ -173,6 +252,8 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {search_tags,apple_pay_recurring_details,payment_revenue_recovery_metadata,+ pix_additional_details,+ boleto_additional_details,} = self;ApiFeatureMetadata {@@ -182,6 +263,8 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {apple_pay_recurring_details: apple_pay_recurring_details.map(|value| value.convert_back()),revenue_recovery: payment_revenue_recovery_metadata.map(|value| value.convert_back()),+ pix_additional_details: pix_additional_details.map(|v| v.convert_back()),+ boleto_additional_details: boleto_additional_details.map(|v| v.convert_back()),}}}diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex 963de4d97a..593c723139 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -396,6 +396,23 @@ impl PaymentIntent {.map(|opt| opt.flatten()).map_err(|report| (*report.current_context()).clone())}+ #[cfg(feature = "v1")]+ pub fn get_optional_feature_metadata(+ &self,+ ) -> CustomResult<+ Option<api_models::payments::FeatureMetadata>,+ common_utils::errors::ParsingError,+ > {+ self.feature_metadata+ .as_ref()+ .map(|details| {+ ValueExt::parse_value::<api_models::payments::FeatureMetadata>(+ details.clone(),+ "FeatureMetadata",+ )+ })+ .transpose()+ }}#[cfg(feature = "v2")]@@ -1375,6 +1392,12 @@ where.as_ref().and_then(|data| data.apple_pay_recurring_details.clone()),payment_revenue_recovery_metadata,+ pix_additional_details: payment_intent_feature_metadata+ .as_ref()+ .and_then(|data| data.pix_additional_details.clone()),+ boleto_additional_details: payment_intent_feature_metadata+ .as_ref()+ .and_then(|data| data.boleto_additional_details.clone()),}))}}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex c0cab4f17e..c9442d2656 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -280,8 +280,9 @@ pub enum PaymentIntentUpdate {feature_metadata: Option<Secret<serde_json::Value>>,},MetadataUpdate {- metadata: serde_json::Value,+ metadata: Option<serde_json::Value>,updated_by: String,+ feature_metadata: Option<Secret<serde_json::Value>>,},Update(Box<PaymentIntentUpdateFields>),PaymentCreateUpdate {@@ -1016,10 +1017,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {PaymentIntentUpdate::MetadataUpdate {metadata,updated_by,+ feature_metadata,} => Self {- metadata: Some(metadata),+ metadata,modified_at: Some(common_utils::date_time::now()),updated_by,+ feature_metadata,..Default::default()},PaymentIntentUpdate::Update(value) => Self {@@ -1311,9 +1314,11 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {PaymentIntentUpdate::MetadataUpdate {metadata,updated_by,+ feature_metadata,} => Self::MetadataUpdate {metadata,updated_by,+ feature_metadata,},PaymentIntentUpdate::StateMetadataUpdate {state_metadata,diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 7ce6cc7cc4..ad8e9d128d 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -101,6 +101,7 @@ pub struct PaymentsAuthorizeData {pub tokenization: Option<common_enums::Tokenization>,pub partner_merchant_identifier_details:Option<common_types::payments::PartnerMerchantIdentifierDetails>,+ pub feature_metadata: Option<api_models::payments::FeatureMetadata>,}#[derive(Debug, Clone, Serialize)]@@ -223,8 +224,12 @@ pub struct PaymentsPostSessionTokensData {#[derive(Debug, Clone, Serialize)]pub struct PaymentsUpdateMetadataData {- pub metadata: pii::SecretSerdeValue,+ pub metadata: Option<pii::SecretSerdeValue>,pub connector_transaction_id: String,+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,+ pub connector_meta: Option<serde_json::Value>,+ pub feature_metadata: Option<api_models::payments::FeatureMetadata>,+ pub payment_method_data: Option<PaymentMethodData>,}#[derive(Debug, Clone, PartialEq, Serialize)]@@ -1008,6 +1013,7 @@ pub struct PaymentsSyncData {pub integrity_object: Option<SyncIntegrityObject>,pub connector_reference_id: Option<String>,pub setup_future_usage: Option<storage_enums::FutureUsage>,+ pub feature_metadata: Option<api_models::payments::FeatureMetadata>,}#[derive(Debug, Default, Clone, Serialize)]@@ -1034,6 +1040,8 @@ pub struct PaymentsCancelData {pub capture_method: Option<storage_enums::CaptureMethod>,pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,pub merchant_order_reference_id: Option<String>,+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,+ pub feature_metadata: Option<api_models::payments::FeatureMetadata>,}#[derive(Debug, Default, Clone, Serialize)]@@ -1383,6 +1391,15 @@ impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData {id: Some(key1),authentication_token: None,}),+ router_data::ConnectorAuthType::CertificateAuth {+ certificate,+ private_key,+ ..+ } => Ok(Self {+ app_id: certificate,+ id: Some(private_key),+ authentication_token: None,+ }),_ => Err(ApiErrorResponse::InvalidDataValue {field_name: "connector_account_details",diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 57ddc29d26..0467f86e80 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -309,6 +309,9 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::CartesBancairesParams,api_models::payments::NetworkParams,api_models::payments::Cryptogram,+ api_models::payments::DocumentDetails,+ api_models::enums::BoletoDocumentKind,+ api_models::enums::BoletoPaymentType,api_models::payments::ExternalThreeDsData,api_models::payments::PaymentMethodTokenizationDetails,api_models::refunds::RefundRequest,@@ -367,6 +370,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::admin::AcceptedCountries,api_models::admin::AcceptedCurrencies,api_models::enums::AdyenSplitType,+ api_models::enums::PixKey,api_models::enums::PaymentType,api_models::enums::MitCategory,api_models::enums::ScaExemptionType,@@ -509,6 +513,10 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::FeatureMetadata,api_models::payments::ApplepayConnectorMetadataRequest,api_models::payments::SessionTokenInfo,+ api_models::payments::PixAdditionalDetails,+ api_models::payments::ImmediateExpirationTime,+ api_models::payments::ScheduledExpirationTime,+ api_models::payments::BoletoAdditionalDetails,api_models::payments::PaymentProcessingDetailsAt,api_models::payments::ApplepayInitiative,api_models::payments::PaymentProcessingDetails,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 0ca091a894..2f40b44378 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -186,6 +186,10 @@ Never share your secret api keys. Keep them guarded and secure.routes::tokenization::delete_tokenized_data_api,),components(schemas(+ api_models::payments::DocumentDetails,+ api_models::enums::PixKey,+ api_models::enums::BoletoDocumentKind,+ api_models::enums::BoletoPaymentType,common_utils::types::MinorUnit,common_utils::types::StringMinorUnit,common_utils::types::TimeRange,@@ -467,6 +471,10 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::SdkType,api_models::payments::ApplepayConnectorMetadataRequest,api_models::payments::SessionTokenInfo,+ api_models::payments::PixAdditionalDetails,+ api_models::payments::ImmediateExpirationTime,+ api_models::payments::ScheduledExpirationTime,+ api_models::payments::BoletoAdditionalDetails,api_models::payments::PaymentProcessingDetailsAt,api_models::payments::ApplepayInitiative,api_models::payments::PaymentProcessingDetails,diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rsindex 43eb46154d..6e566de719 100644--- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs+++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs@@ -180,6 +180,8 @@ enum RequiredField {MifinityLanguagePreference(Vec<&'static str>),CryptoNetwork,CyptoPayCurrency(Vec<&'static str>),+ PixDocumentType(Vec<&'static str>),+ PixDocumentNumber,BoletoSocialSecurityNumber,UpiCollectVpaId,AchBankDebitAccountNumber,@@ -193,8 +195,6 @@ enum RequiredField {BecsBankDebitBsbNumber,BecsBankDebitSortCode,PixKey,- PixCnpj,- PixCpf,PixSourceBankAccountId,GiftCardNumber,GiftCardCvc,@@ -685,6 +685,26 @@ impl RequiredField {value: None,},),+ Self::PixDocumentNumber => (+ "customer.document_details.document_number".to_string(),+ RequiredFieldInfo {+ required_field: "customer.document_details.document_number".to_string(),+ display_name: "document_number".to_string(),+ field_type: FieldType::UserSocialSecurityNumber,+ value: None,+ },+ ),+ Self::PixDocumentType(document_type) => (+ "customer.document_details.document_type".to_string(),+ RequiredFieldInfo {+ required_field: "customer.document_details.document_type".to_string(),+ display_name: "document_type".to_string(),+ field_type: FieldType::UserDocumentType {+ options: document_type.iter().map(|d| d.to_string()).collect(),+ },+ value: None,+ },+ ),Self::UpiCollectVpaId => ("payment_method_data.upi.upi_collect.vpa_id".to_string(),RequiredFieldInfo {@@ -807,24 +827,6 @@ impl RequiredField {value: None,},),- Self::PixCnpj => (- "payment_method_data.bank_transfer.pix.cnpj".to_string(),- RequiredFieldInfo {- required_field: "payment_method_data.bank_transfer.pix.cnpj".to_string(),- display_name: "cnpj".to_string(),- field_type: FieldType::UserCnpj,- value: None,- },- ),- Self::PixCpf => (- "payment_method_data.bank_transfer.pix.cpf".to_string(),- RequiredFieldInfo {- required_field: "payment_method_data.bank_transfer.pix.cpf".to_string(),- display_name: "cpf".to_string(),- field_type: FieldType::UserCpf,- value: None,- },- ),Self::PixSourceBankAccountId => ("payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(),RequiredFieldInfo {@@ -3246,6 +3248,25 @@ fn get_voucher_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFcommon: HashMap::new(),},),+ (+ Connector::Santander,+ RequiredFieldFinal {+ mandate: HashMap::new(),+ non_mandate: HashMap::from([+ RequiredField::PixDocumentType(vec!["cpf", "cnpj"]).to_tuple(),+ RequiredField::PixDocumentNumber.to_tuple(),+ RequiredField::BillingUserFirstName.to_tuple(),+ RequiredField::BillingUserLastName.to_tuple(),+ RequiredField::BillingAddressCity.to_tuple(),+ RequiredField::BillingAddressState.to_tuple(),+ RequiredField::BillingAddressZip.to_tuple(),+ RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(),+ RequiredField::BillingAddressLine1.to_tuple(),+ RequiredField::BillingAddressLine2.to_tuple(),+ ]),+ common: HashMap::new(),+ },+ ),(Connector::Zen, fields(vec![], vec![], vec![])),]),),@@ -3655,8 +3676,8 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Connnon_mandate: HashMap::new(),common: HashMap::from([RequiredField::PixKey.to_tuple(),- RequiredField::PixCnpj.to_tuple(),- RequiredField::PixCpf.to_tuple(),+ RequiredField::PixDocumentType(vec!["CPF", "CNPJ"]).to_tuple(),+ RequiredField::PixDocumentNumber.to_tuple(),RequiredField::BillingUserFirstName.to_tuple(),RequiredField::BillingUserLastName.to_tuple(),]),@@ -3669,8 +3690,16 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Connmandate: HashMap::new(),non_mandate: HashMap::new(),common: HashMap::from([+ RequiredField::PixDocumentType(vec!["cpf", "cnpj"]).to_tuple(),+ RequiredField::PixDocumentNumber.to_tuple(),RequiredField::BillingUserFirstName.to_tuple(),RequiredField::BillingUserLastName.to_tuple(),+ RequiredField::BillingAddressCity.to_tuple(),+ RequiredField::BillingAddressState.to_tuple(),+ RequiredField::BillingAddressZip.to_tuple(),+ RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(),+ RequiredField::BillingAddressLine1.to_tuple(),+ RequiredField::BillingAddressLine2.to_tuple(),]),},),@@ -3704,7 +3733,8 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, ConnRequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(),RequiredField::BillingUserFirstName.to_tuple(),RequiredField::BillingUserLastName.to_tuple(),- RequiredField::PixCpf.to_tuple(),+ RequiredField::PixDocumentType(vec!["CPF", "CNPJ"]).to_tuple(),+ RequiredField::PixDocumentNumber.to_tuple(),]),},),diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rsindex 281b1bb2a0..de44e1761b 100644--- a/crates/router/src/core/connector_validation.rs+++ b/crates/router/src/core/connector_validation.rs@@ -482,10 +482,8 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {Ok(())}api_enums::Connector::Santander => {- santander::transformers::SantanderAuthType::try_from(self.auth_type)?;- santander::transformers::SantanderMetadataObject::try_from(- self.connector_meta_data,- )?;+ santander::requests::SantanderAuthType::try_from(self.auth_type)?;+ santander::requests::SantanderMetadataObject::try_from(self.connector_meta_data)?;Ok(())}api_enums::Connector::Shift4 => {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex dfdcd80289..2cf70132f6 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3502,6 +3502,8 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {}),search_tags: None,apple_pay_recurring_details: None,+ pix_additional_details: None,+ boleto_additional_details: None,}),..Default::default()};@@ -4009,6 +4011,8 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {}),search_tags: None,apple_pay_recurring_details: None,+ pix_additional_details: None,+ boleto_additional_details: None,}),..Default::default()};diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 8f6f8c3b84..eaea5fba86 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -1250,15 +1250,13 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsUpdateMetadatif status.is_success() {let m_db = db.clone().store;let payment_intent = payment_data.payment_intent.clone();-let payment_intent_update =hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::MetadataUpdate {metadata: payment_data.payment_intent.metadata- .clone()- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("payment_intent.metadata not found")?,+ .clone(),+ feature_metadata: payment_intent.feature_metadata.clone().map(masking::Secret::new),updated_by: payment_data.payment_intent.updated_by.clone(),};diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex 30c641cdb6..6958aafb52 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -262,14 +262,20 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequelet key_store = processor.get_key_store();let metadata = payment_data.payment_intent.metadata.clone();+ let feature_metadata = payment_data+ .payment_intent+ .feature_metadata+ .clone()+ .map(masking::Secret::new);payment_data.payment_intent = match metadata {Some(metadata) => state.store.update_payment_intent(payment_data.payment_intent,storage::PaymentIntentUpdate::MetadataUpdate {- metadata,+ metadata: Some(metadata),updated_by: storage_scheme.to_string(),+ feature_metadata,},key_store,storage_scheme,diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex 31342128be..591f8733b2 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -2,6 +2,7 @@ use std::marker::PhantomData;use api_models::enums::FrmSuggestion;use async_trait::async_trait;+use common_utils::ext_traits::ValueExt;use error_stack::ResultExt;use masking::ExposeInterface;use router_derive::PaymentOperation;@@ -72,6 +73,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMestorage_enums::IntentStatus::PartiallyCaptured,storage_enums::IntentStatus::PartiallyCapturedAndCapturable,storage_enums::IntentStatus::RequiresCapture,+ storage_enums::IntentStatus::RequiresCustomerAction,],"update_metadata",)?;@@ -105,13 +107,37 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMeid: profile_id.get_string_repr().to_owned(),})?;- let merged_metadata = payment_intent- .merge_metadata(request.metadata.clone().expose())- .change_context(errors::ApiErrorResponse::InvalidRequestData {- message: "Metadata should be an object and contain at least 1 key".to_owned(),- })?;+ if let Some(metadata) = request.metadata.as_ref().map(|data| data.clone().expose()) {+ let merged_metadata = payment_intent.merge_metadata(metadata).change_context(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "Metadata should be an object and contain at least 1 key".to_owned(),+ },+ )?;++ payment_intent.metadata = Some(merged_metadata);+ }++ if let Some(feature_metadata) = request.feature_metadata.clone() {+ let existing_feature_metadata = payment_intent+ .feature_metadata+ .as_ref()+ .map(|value| {+ value+ .clone()+ .parse_value::<api_models::payments::FeatureMetadata>("FeatureMetadata")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata from payment intent")+ })+ .transpose()?;- payment_intent.metadata = Some(merged_metadata);+ let merged_feature_metadata = feature_metadata.clone().merge(existing_feature_metadata);++ payment_intent.feature_metadata = Some(+ serde_json::to_value(merged_feature_metadata)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize feature metadata")?,+ );+ }let payment_data = PaymentData {flow: PhantomData,@@ -241,16 +267,40 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsUpdateMetada#[instrument(skip_all)]async fn update_trackers<'b>(&'b self,- _state: &'b SessionState,+ state: &'b SessionState,_req_state: ReqState,- _processor: &domain::Processor,- payment_data: PaymentData<F>,+ processor: &domain::Processor,+ mut payment_data: PaymentData<F>,_frm_suggestion: Option<FrmSuggestion>,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,) -> RouterResult<(PaymentUpdateMetadataOperation<'b, F>, PaymentData<F>)>whereF: 'b + Send,{+ let storage_scheme = processor.get_account().storage_scheme;+ let key_store = processor.get_key_store();+ let metadata = payment_data.payment_intent.metadata.clone();+ let feature_metadata = payment_data+ .payment_intent+ .feature_metadata+ .clone()+ .map(masking::Secret::new);++ payment_data.payment_intent = state+ .store+ .update_payment_intent(+ payment_data.payment_intent,+ storage::PaymentIntentUpdate::MetadataUpdate {+ metadata,+ feature_metadata,+ updated_by: storage_scheme.to_string(),+ },+ key_store,+ storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Failed to Update Payment Intent In Update Metadata Flow")?;Ok((Box::new(self), payment_data))}}@@ -267,6 +317,11 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsUpdateMetadataRequePaymentUpdateMetadataOperation<'b, F>,operations::ValidateResult,)> {+ request.validate().change_context(+ payment_methods::errors::ApiErrorResponse::MissingRequiredField {+ field_name: "metadata/feature_metadata",+ },+ )?;//payment id is already generated and should be sent in the requestlet given_payment_id = request.payment_id.clone();diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex dc43161510..7c026e9647 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -485,6 +485,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(is_stored_credential: None,billing_descriptor: None,partner_merchant_identifier_details: None,+ feature_metadata: None,};let connector_mandate_request_reference_id = payment_data.payment_attempt@@ -984,6 +985,7 @@ pub async fn construct_router_data_for_psync<'a>(payment_experience: None,connector_reference_id: attempt.connector_response_reference_id.clone(),setup_future_usage: Some(payment_intent.setup_future_usage),+ feature_metadata: None,};// TODO: evaluate the fields in router data, if they are required or not@@ -1196,6 +1198,8 @@ pub async fn construct_router_data_for_cancel<'a>(capture_method: Some(payment_intent.capture_method),split_payments: None,merchant_order_reference_id: None,+ feature_metadata: None,+ payment_method_type: None,};// Construct RouterDataV2 for cancel operation@@ -3278,6 +3282,12 @@ where_is_latency_header_enabled: Option<bool>,_platform: &domain::Platform,) -> RouterResponse<Self> {+ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;+Ok(services::ApplicationResponse::JsonWithHeaders((Self {payment_id: payment_data.get_payment_intent().payment_id.clone(),@@ -3286,6 +3296,8 @@ where.metadata.clone().map(Secret::new),+ feature_metadata,+ status: payment_data.get_payment_intent().status,},vec![],)))@@ -3959,6 +3971,12 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode SDK authorization")?;+ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;+let payments_response = api::PaymentsResponse {payment_id: payment_intent.payment_id,merchant_id: payment_intent.merchant_id,@@ -4045,7 +4063,7 @@ wherefrm_message,metadata: payment_intent.metadata,connector_metadata: payment_intent.connector_metadata,- feature_metadata: payment_intent.feature_metadata,+ feature_metadata,reference_id: payment_attempt.connector_response_reference_id,payment_link: payment_link_data,profile_id: payment_intent.profile_id,@@ -4589,6 +4607,7 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymenimage_data_url,qr_code_url,display_to_timestamp,+ expiry_type: _,} => Self::QrCodeInformation {image_data_url: Some(image_data_url),qr_code_url: Some(qr_code_url),@@ -4769,6 +4788,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizis_stored_credential: None,billing_descriptor: None,partner_merchant_identifier_details: None,+ feature_metadata: None,})}}@@ -4816,6 +4836,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz}).transpose()?;+ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;+let order_category = connector_metadata.as_ref().and_then(|cm| {cm.noon.as_ref()@@ -5018,6 +5044,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizpartner_merchant_identifier_details: payment_data.payment_intent.partner_merchant_identifier_details,+ feature_metadata,})}}@@ -5079,6 +5106,13 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData.payment_attempt.get_payment_method_type().to_owned();++ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;+Ok(Self {amount,integrity_object: None,@@ -5111,6 +5145,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData.payment_attempt.setup_future_usage_applied.or(payment_data.payment_intent.setup_future_usage),+ feature_metadata,})}}@@ -5366,6 +5401,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDacapture_method: Some(capture_method),split_payments: None,merchant_order_reference_id: None,+ feature_metadata: None,+ payment_method_type: None,})}}@@ -5391,6 +5428,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDa.change_context(errors::ApiErrorResponse::InvalidDataValue {field_name: "browser_info",})?;+ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;let amount = payment_data.payment_attempt.get_total_amount();let router_base_url = &additional_data.router_base_url;@@ -5424,6 +5466,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDacapture_method,split_payments: payment_data.payment_intent.split_payments.clone(),merchant_order_reference_id: payment_data.payment_intent.merchant_order_reference_id,+ payment_method_type: payment_data.payment_attempt.payment_method_type,+ feature_metadata,})}}@@ -5600,17 +5644,22 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsUpdateMeapi::GetToken::Connector,payment_data.payment_attempt.merchant_connector_id.clone(),)?;+ let feature_metadata = payment_data+ .get_payment_intent()+ .get_optional_feature_metadata()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse feature metadata")?;+Ok(Self {- metadata: payment_data- .payment_intent- .metadata- .map(Secret::new)- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("payment_intent.metadata not found")?,+ metadata: payment_data.payment_intent.metadata.map(Secret::new),connector_transaction_id: connector.connector.connector_transaction_id(&payment_data.payment_attempt)?.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,+ payment_method_type: payment_data.payment_attempt.payment_method_type,+ connector_meta: payment_data.payment_attempt.connector_metadata.clone(),+ payment_method_data: None,+ feature_metadata,})}}@@ -6641,6 +6690,8 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::paymentapple_pay_recurring_details: apple_pay_details,redirect_response: redirect_res,search_tags: feature_metadata.search_tags.clone(),+ pix_additional_details: None,+ boleto_additional_details: None,}}}diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rsindex 052075b95d..0c97bc05e7 100644--- a/crates/router/src/core/relay/utils.rs+++ b/crates/router/src/core/relay/utils.rs@@ -515,6 +515,7 @@ pub async fn construct_relay_payments_retrieve_router_data(amount: relay_capture_data.amount_to_capture,connector_reference_id: None,setup_future_usage: None,+ feature_metadata: None,},response: Err(ErrorResponse::default()),diff --git a/crates/router/src/types.rs b/crates/router/src/types.rsindex 4845ecf369..6d4e616500 100644--- a/crates/router/src/types.rs+++ b/crates/router/src/types.rs@@ -1341,6 +1341,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {.request.partner_merchant_identifier_details.clone(),+ feature_metadata: None,}}}diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rsindex 0790ec183e..d8daf666d4 100644--- a/crates/router/src/types/api/verify_connector.rs+++ b/crates/router/src/types/api/verify_connector.rs@@ -74,6 +74,7 @@ impl VerifyConnectorData {billing_descriptor: None,tokenization: None,partner_merchant_identifier_details: None,+ feature_metadata: None,}}diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex a7d7c9d360..4c02545025 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -1021,6 +1021,7 @@ impl Default for PaymentAuthorizeType {billing_descriptor: None,tokenization: None,partner_merchant_identifier_details: None,+ feature_metadata: None,};Self(data)}diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex a916c5ea20..bc8c6c3502 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -203,8 +203,8 @@ razorpay.base_url = "https://api.razorpay.com/"recurly.base_url = "https://v3.recurly.com"redsys.base_url = "https://sis-t.redsys.es:25443"riskified.base_url = "https://sandbox.riskified.com/api"-santander.base_url = "https://pix.santander.com.br/api/v1/sandbox/"-santander.secondary_base_url = "https://trust-sandbox.api.santander.com.br/collection_bill_management/"+santander.base_url = "https://trust-pix-h.santander.com.br/"+santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"shift4.base_url = "https://api.shift4.com/"sift.base_url = "https://api.sift.com/v205"silverflow.base_url = "https://api-sbx.silverflow.co/v1"@@ -664,6 +664,7 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }[pm_filters.santander]pix = { country = "BR", currency = "BRL" }+boleto = { country = "BR", currency = "BRL" }[pm_filters.calida]bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }