Skip to content

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

feat(core): add customer_document_number in payment request (#10683)

Swangi Kumari6e8f28ed3d1b
diff --git a/Cargo.lock b/Cargo.lock
index 5c52501075..317e1084cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -472,6 +472,7 @@ dependencies = [
"nutype",
"reqwest 0.11.27",
"router_derive",
+ "router_env",
"serde",
"serde_json",
"smithy",
@@ -5844,9 +5845,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
[[package]]
name = "openssl-src"
-version = "300.5.4+3.5.4"
+version = "300.5.5+3.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a507b3792995dae9b0df8a1c1e3771e8418b7c2d9f0baeba32e6fe8b06c7cb72"
+checksum = "3f1787d533e03597a7934fd0a765f0d28e94ecc5fb7789f8053b1e699a56f709"
dependencies = [
"cc",
]
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 20d3970701..6f5ce04003 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -13076,7 +13076,7 @@
"$ref": "#/components/schemas/DocumentKind"
}
],
- "default": "Cnpj",
+ "default": "cnpj",
"nullable": true
},
"fine_percentage": {
@@ -16669,6 +16669,14 @@
"description": "The tax registration identifier of the customer.",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -16711,6 +16719,14 @@
"example": "+1",
"nullable": true,
"maxLength": 2
+ },
+ "customer_document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -16786,6 +16802,24 @@
"gaming_console"
]
},
+ "CustomerDocumentDetails": {
+ "type": "object",
+ "required": [
+ "document_type",
+ "document_number"
+ ],
+ "properties": {
+ "document_type": {
+ "$ref": "#/components/schemas/DocumentKind"
+ },
+ "document_number": {
+ "type": "string",
+ "description": "The customer's document number\nLength of the document number depends upon the document_type.\nFor CPF/CNPJ it is typically 11/14 digits long",
+ "example": "12345678911",
+ "maxLength": 255
+ }
+ }
+ },
"CustomerId": {
"type": "string",
"description": "A type for customer_id that can be used for customer ids"
@@ -17132,6 +17166,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -17216,6 +17258,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -17277,6 +17327,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -17748,9 +17806,10 @@
},
"DocumentKind": {
"type": "string",
+ "description": "Represents the type of identification document used for validation.",
"enum": [
- "CNPJ",
- "CPF"
+ "cpf",
+ "cnpj"
]
},
"DokuBankTransferInstructions": {
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 37e79a2f8a..0d3dd978ec 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -7761,7 +7761,7 @@
"$ref": "#/components/schemas/DocumentKind"
}
],
- "default": "Cnpj",
+ "default": "cnpj",
"nullable": true
},
"fine_percentage": {
@@ -10655,6 +10655,14 @@
"description": "The tax registration identifier of the customer.",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -10692,6 +10700,24 @@
}
}
},
+ "CustomerDocumentDetails": {
+ "type": "object",
+ "required": [
+ "document_type",
+ "document_number"
+ ],
+ "properties": {
+ "document_type": {
+ "$ref": "#/components/schemas/DocumentKind"
+ },
+ "document_number": {
+ "type": "string",
+ "description": "The customer's document number\nLength of the document number depends upon the document_type.\nFor CPF/CNPJ it is typically 11/14 digits long",
+ "example": "12345678911",
+ "maxLength": 255
+ }
+ }
+ },
"CustomerPaymentMethodResponseItem": {
"type": "object",
"required": [
@@ -10868,6 +10894,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -10974,6 +11008,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -11050,6 +11092,14 @@
"example": "123456789",
"nullable": true,
"maxLength": 255
+ },
+ "document_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CustomerDocumentDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -11462,9 +11512,10 @@
},
"DocumentKind": {
"type": "string",
+ "description": "Represents the type of identification document used for validation.",
"enum": [
- "CNPJ",
- "CPF"
+ "cpf",
+ "cnpj"
]
},
"DokuBankTransferInstructions": {
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 5c1c426309..98eb4e41ff 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -23,6 +23,7 @@ revenue_recovery = ["dep:actix-multipart"]
tokenization_v2 = ["common_utils/tokenization_v2"]
[dependencies]
+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
actix-multipart = { version = "0.6.2", optional = true }
actix-web = { version = "4.11.0", optional = true }
csv = "1.3"
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index 69087e5758..0d1771185c 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -1,6 +1,12 @@
-use common_types::primitive_wrappers::CustomerListLimit;
-use common_utils::{crypto, custom_serde, id_type, pii, types::Description};
-use masking::Secret;
+use common_types::{customers::DocumentKind, primitive_wrappers::CustomerListLimit};
+use common_utils::{
+ crypto, custom_serde,
+ errors::{ParsingError, ValidationError},
+ ext_traits::{Encode, ValueExt},
+ id_type, pii,
+ types::Description,
+};
+use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use smithy::SmithyModel;
use utoipa::ToSchema;
@@ -54,6 +60,10 @@ pub struct CustomerRequest {
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ #[smithy(value_type = "Option<CustomerDocumentDetails>")]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, SmithyModel)]
@@ -100,6 +110,14 @@ impl CustomerRequest {
pub fn get_optional_email(&self) -> Option<pii::Email> {
self.email.clone()
}
+ pub fn validate_document_details(
+ &self,
+ ) -> common_utils::errors::CustomResult<(), ValidationError> {
+ self.document_details
+ .as_ref()
+ .map(|doc| doc.validate())
+ .unwrap_or(Ok(()))
+ }
}
/// The customer details
@@ -139,6 +157,9 @@ pub struct CustomerRequest {
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: Option<Secret<String>>,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v2")]
@@ -211,6 +232,10 @@ pub struct CustomerResponse {
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ #[smithy(value_type = "Option<CustomerDocumentDetails>")]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v1")]
@@ -273,6 +298,9 @@ pub struct CustomerResponse {
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v2")]
@@ -372,6 +400,10 @@ pub struct CustomerUpdateRequest {
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ #[smithy(value_type = "Option<CustomerDocumentDetails>")]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v1")]
@@ -417,6 +449,9 @@ pub struct CustomerUpdateRequest {
/// The customer's tax registration number.
#[schema(max_length = 255, value_type = Option<String>, example = "123456789")]
pub tax_registration_id: Option<Secret<String>>,
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v2")]
@@ -451,3 +486,44 @@ pub struct CustomerListResponse {
/// Total count of customers
pub total_count: usize,
}
+
+#[derive(Debug, Clone, Deserialize, Serialize, ToSchema, PartialEq)]
+pub struct CustomerDocumentDetails {
+ /// The customer's document type
+ #[schema(value_type = DocumentKind, example = "cpf")]
+ pub document_type: DocumentKind,
+ /// The customer's document number
+ /// Length of the document number depends upon the document_type.
+ /// For CPF/CNPJ it is typically 11/14 digits long
+ #[schema(max_length = 255, value_type = String, example = "12345678911")]
+ pub document_number: Secret<String>,
+}
+
+impl CustomerDocumentDetails {
+ pub fn from(value: &Option<pii::SecretSerdeValue>) -> Result<Option<Self>, ParsingError> {
+ value
+ .as_ref()
+ .map(|pii_value| {
+ pii_value
+ .peek()
+ .clone()
+ .parse_value::<Self>("CustomerDocumentDetails")
+ .map_err(|err| {
+ router_env::logger::error!(
+ parsing_error = ?err,
+ "Failed to parse CustomerDocumentDetails"
+ );
+ ParsingError::StructParseFailure("CustomerDocumentDetails")
+ })
+ })
+ .transpose()
+ }
+
+ pub fn to(&self) -> common_utils::errors::CustomResult<pii::SecretSerdeValue, ParsingError> {
+ self.encode_to_value().map(Secret::new)
+ }
+
+ pub fn validate(&self) -> common_utils::errors::CustomResult<(), ValidationError> {
+ self.document_type.validate(self.document_number.peek())
+ }
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index bab7d2c5fc..92a7efe2bf 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -28,6 +28,7 @@ use common_utils::{
};
use error_stack::ResultExt;
+use crate::customers::CustomerDocumentDetails;
#[cfg(feature = "v2")]
fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>
where
@@ -152,6 +153,11 @@ pub struct CustomerDetails {
#[schema(value_type=Option<String>,max_length = 255)]
#[smithy(value_type = "Option<String>")]
pub tax_registration_id: Option<Secret<String>>,
+
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ #[smithy(value_type = "Option<CustomerDocumentDetails>")]
+ pub document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v1")]
@@ -193,6 +199,11 @@ pub struct CustomerDetailsResponse {
#[schema(max_length = 2, example = "+1")]
#[smithy(value_type = "Option<String>")]
pub phone_country_code: Option<String>,
+
+ /// Customer’s country-specific identification number and type used for regulatory or tax purposes
+ #[schema(value_type = Option<CustomerDocumentDetails>)]
+ #[smithy(value_type = "Option<CustomerDocumentDetails>")]
+ pub customer_document_details: Option<CustomerDocumentDetails>,
}
#[cfg(feature = "v2")]
@@ -1657,6 +1668,16 @@ impl PaymentsRequest {
}
}
+ pub fn validate_document_details(
+ &self,
+ ) -> common_utils::errors::CustomResult<(), ValidationError> {
+ self.customer
+ .as_ref()
+ .and_then(|data| data.document_details.as_ref())
+ .map(|doc| doc.validate())
+ .unwrap_or(Ok(()))
+ }
+
pub fn get_feature_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
@@ -1772,6 +1793,7 @@ mod payments_request_test {
phone: None,
phone_country_code: None,
tax_registration_id: None,
+ document_details: None,
};
let payments_request = PaymentsRequest {
@@ -1797,6 +1819,7 @@ mod payments_request_test {
phone: None,
phone_country_code: None,
tax_registration_id: None,
+ document_details: None,
};
let payments_request = PaymentsRequest {
@@ -5734,9 +5757,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", default = "cnpj")]
#[smithy(value_type = "Option<DocumentKind>")]
- pub document_type: Option<common_enums::DocumentKind>,
+ pub document_type: Option<common_types::customers::DocumentKind>,
/// The fine percentage charged if payment is overdue
#[schema(value_type = Option<String>)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index cb51ca0642..c28c627f91 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -778,29 +778,6 @@ pub enum CallConnectorAction {
UCSHandleResponse(Vec<u8>),
}
-#[derive(
- Clone,
- Copy,
- Debug,
- Eq,
- Hash,
- PartialEq,
- serde::Deserialize,
- serde::Serialize,
- SmithyModel,
- strum::Display,
- strum::VariantNames,
- strum::EnumIter,
- strum::EnumString,
- ToSchema,
-)]
-#[serde(rename_all = "UPPERCASE")]
-#[smithy(namespace = "com.hyperswitch.smithy.types")]
-pub enum DocumentKind {
- Cnpj,
- Cpf,
-}
-
/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment.
#[allow(clippy::upper_case_acronyms)]
#[derive(
diff --git a/crates/common_types/src/customers.rs b/crates/common_types/src/customers.rs
index 1610bef511..caaef7086e 100644
--- a/crates/common_types/src/customers.rs
+++ b/crates/common_types/src/customers.rs
@@ -1,5 +1,8 @@
//! Customer related types
+use common_utils::errors::ValidationError;
+use error_stack::Report;
+use utoipa::ToSchema;
/// HashMap containing MerchantConnectorAccountId and corresponding customer id
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
@@ -38,3 +41,61 @@ impl std::ops::DerefMut for ConnectorCustomerMap {
&mut self.0
}
}
+
+/// Represents the type of identification document used for validation.
+#[derive(
+ Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Deserialize, serde::Serialize, ToSchema,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum DocumentKind {
+ /// Cadastro de Pessoas Físicas - The Brazilian individual taxpayer identifier.
+ Cpf,
+ /// Cadastro Nacional da Pessoa Jurídica - The Brazilian business identifier.
+ Cnpj,
+}
+
+impl DocumentKind {
+ /// Validation function for document number depending on document type
+ pub fn validate(
+ &self,
+ doc_number: &str,
+ ) -> common_utils::errors::CustomResult<(), ValidationError> {
+ match self {
+ Self::Cpf => self.validate_cpf(doc_number),
+ Self::Cnpj => self.validate_cnpj(doc_number),
+ }
+ }
+
+ fn validate_cpf(
+ self,
+ doc_number: &str,
+ ) -> common_utils::errors::CustomResult<(), ValidationError> {
+ (doc_number.len() == common_utils::consts::CPF_LENGTH)
+ .then_some(())
+ .ok_or_else(|| {
+ self.length_error("CPF", common_utils::consts::CPF_LENGTH, doc_number.len())
+ })?;
+
+ Ok(())
+ }
+
+ fn validate_cnpj(
+ self,
+ doc_number: &str,
+ ) -> common_utils::errors::CustomResult<(), ValidationError> {
+ (doc_number.len() == common_utils::consts::CNPJ_LENGTH)
+ .then_some(())
+ .ok_or_else(|| {
+ self.length_error("CNPJ", common_utils::consts::CNPJ_LENGTH, doc_number.len())
+ })?;
+
+ Ok(())
+ }
+
+ fn length_error(self, name: &str, expected: usize, actual: usize) -> Report<ValidationError> {
+ let message = format!("{name} document_number (expected {expected}, got {actual})");
+ Report::new(ValidationError::IncorrectValueProvided {
+ field_name: Box::leak(message.into_boxed_str()),
+ })
+ }
+}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index ee3f881664..db4b6c64ea 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -226,3 +226,9 @@ pub const DEFAULT_LIST_LIMIT: i64 = 100;
/// Default offset for list operations (can be used across different entities)
pub const DEFAULT_LIST_OFFSET: i64 = 0;
+
+/// Length of CPF document number, used in Brazil commonly
+pub const CPF_LENGTH: usize = 11;
+
+/// Length of CNPJ document number, used in Brazil commonly
+pub const CNPJ_LENGTH: usize = 14;
diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs
index 66ae55391d..54d047afcd 100644
--- a/crates/common_utils/src/errors.rs
+++ b/crates/common_utils/src/errors.rs
@@ -13,7 +13,7 @@ pub type CustomResult<T, E> = error_stack::Result<T, E>;
/// Parsing Errors
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
-#[derive(Debug, thiserror::Error)]
+#[derive(Debug, Clone, thiserror::Error)]
pub enum ParsingError {
///Failed to parse enum
#[error("Failed to parse enum: {0}")]
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index f9eef640d1..f69f81cb4e 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -33,6 +33,7 @@ pub struct CustomerNew {
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub document_details: Option<Encryption>,
}
#[cfg(feature = "v1")]
@@ -62,6 +63,7 @@ impl From<CustomerNew> for Customer {
updated_by: customer_new.updated_by,
version: customer_new.version,
tax_registration_id: customer_new.tax_registration_id,
+ document_details: customer_new.document_details,
created_by: customer_new.created_by,
last_modified_by: customer_new.last_modified_by,
}
@@ -96,6 +98,7 @@ pub struct CustomerNew {
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,
+ pub document_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -122,6 +125,7 @@ impl From<CustomerNew> for Customer {
default_payment_method_id: None,
updated_by: customer_new.updated_by,
tax_registration_id: customer_new.tax_registration_id,
+ document_details: customer_new.document_details,
merchant_reference_id: customer_new.merchant_reference_id,
default_billing_address: customer_new.default_billing_address,
default_shipping_address: customer_new.default_shipping_address,
@@ -159,6 +163,7 @@ pub struct Customer {
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub document_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -183,6 +188,7 @@ pub struct Customer {
pub tax_registration_id: Option<Encryption>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub document_details: Option<Encryption>,
pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
@@ -211,6 +217,7 @@ pub struct CustomerUpdateInternal {
pub updated_by: Option<String>,
pub tax_registration_id: Option<Encryption>,
pub last_modified_by: Option<String>,
+ pub document_details: Option<Encryption>,
}
#[cfg(feature = "v1")]
@@ -227,6 +234,7 @@ impl CustomerUpdateInternal {
address_id,
default_payment_method_id,
tax_registration_id,
+ document_details,
last_modified_by,
..
} = self;
@@ -245,6 +253,7 @@ impl CustomerUpdateInternal {
.flatten()
.map_or(source.default_payment_method_id, Some),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
+ document_details: document_details.map_or(source.document_details, Some),
last_modified_by: last_modified_by.or(source.last_modified_by),
..source
}
@@ -272,6 +281,7 @@ pub struct CustomerUpdateInternal {
pub status: Option<DeleteStatus>,
pub tax_registration_id: Option<Encryption>,
pub last_modified_by: Option<String>,
+ pub document_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -290,6 +300,7 @@ impl CustomerUpdateInternal {
default_shipping_address,
status,
tax_registration_id,
+ document_details,
last_modified_by,
..
} = self;
@@ -312,6 +323,7 @@ impl CustomerUpdateInternal {
.map_or(source.default_shipping_address, Some),
status: status.unwrap_or(source.status),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
+ document_details: document_details.map_or(source.document_details, Some),
last_modified_by: last_modified_by.or(source.last_modified_by),
..source
}
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index ea3c0e0dcb..d80cb969ca 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -225,7 +225,7 @@ pub enum Updateable {
PaymentIntentUpdate(Box<PaymentIntentUpdateMems>),
PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>),
RefundUpdate(Box<RefundUpdateMems>),
- CustomerUpdate(CustomerUpdateMems),
+ CustomerUpdate(Box<CustomerUpdateMems>),
AddressUpdate(Box<AddressUpdateMems>),
PayoutsUpdate(PayoutsUpdateMems),
PayoutAttemptUpdate(PayoutAttemptUpdateMems),
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 5826ef928c..d5099e8683 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -65,6 +65,7 @@ pub struct PaymentMethod {
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub customer_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -93,6 +94,7 @@ pub struct PaymentMethod {
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub customer_details: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
@@ -156,6 +158,7 @@ pub struct PaymentMethodNew {
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub customer_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -188,6 +191,7 @@ pub struct PaymentMethodNew {
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<String>,
pub last_modified_by: Option<String>,
+ pub customer_details: Option<Encryption>,
}
impl PaymentMethodNew {
@@ -360,6 +364,7 @@ pub struct PaymentMethodUpdateInternal {
locker_fingerprint_id: Option<String>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
last_modified_by: Option<String>,
+ customer_details: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -382,6 +387,7 @@ impl PaymentMethodUpdateInternal {
locker_fingerprint_id,
external_vault_source,
last_modified_by,
+ customer_details,
} = self;
PaymentMethod {
@@ -415,6 +421,7 @@ impl PaymentMethodUpdateInternal {
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
+ customer_details: customer_details.or(source.customer_details),
}
}
}
@@ -440,6 +447,7 @@ pub struct PaymentMethodUpdateInternal {
network_token_payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_modified_by: Option<String>,
+ customer_details: Option<Encryption>,
}
#[cfg(feature = "v1")]
@@ -463,6 +471,7 @@ impl PaymentMethodUpdateInternal {
network_token_payment_method_data,
scheme,
last_modified_by,
+ customer_details,
} = self;
PaymentMethod {
@@ -507,6 +516,7 @@ impl PaymentMethodUpdateInternal {
vault_type: source.vault_type,
created_by: source.created_by,
last_modified_by: last_modified_by.or(source.last_modified_by),
+ customer_details: customer_details.or(source.customer_details),
}
}
}
@@ -537,6 +547,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -559,6 +570,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
@@ -578,6 +590,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by: None,
+ customer_details: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
@@ -602,6 +615,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -625,6 +639,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
@@ -647,6 +662,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
@@ -677,6 +693,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -699,6 +716,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
@@ -723,6 +741,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
@@ -747,6 +766,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_payment_method_data: None,
scheme: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
@@ -773,6 +793,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
scheme: None,
payment_method_data,
last_modified_by,
+ customer_details: None,
},
}
}
@@ -802,6 +823,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
payment_method_data: None,
@@ -820,6 +842,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by: None,
+ customer_details: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
@@ -843,6 +866,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -865,6 +889,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
@@ -886,6 +911,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::GenericUpdate {
payment_method_data,
@@ -918,6 +944,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
external_vault_source,
network_transaction_id,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -939,6 +966,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id: None,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
PaymentMethodUpdate::StatusAndFingerprintUpdate {
status,
@@ -961,6 +989,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_fingerprint_id,
external_vault_source: None,
last_modified_by,
+ customer_details: None,
},
}
}
@@ -1014,6 +1043,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
vault_type: payment_method_new.vault_type,
created_by: payment_method_new.created_by.clone(),
last_modified_by: payment_method_new.last_modified_by.clone(),
+ customer_details: payment_method_new.customer_details.clone(),
}
}
}
@@ -1058,6 +1088,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
vault_type: payment_method_new.vault_type,
created_by: payment_method_new.created_by.clone(),
last_modified_by: payment_method_new.last_modified_by.clone(),
+ customer_details: payment_method_new.customer_details.clone(),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index dc002d8736..fc6f8a835e 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -419,6 +419,7 @@ diesel::table! {
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
+ document_details -> Nullable<Bytea>,
}
}
@@ -1350,6 +1351,7 @@ diesel::table! {
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
+ customer_details -> Nullable<Bytea>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 4c27156a24..376e069ed1 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -424,6 +424,7 @@ diesel::table! {
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
+ document_details -> Nullable<Bytea>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
default_billing_address -> Nullable<Bytea>,
@@ -1288,6 +1289,7 @@ diesel::table! {
created_by -> Nullable<Varchar>,
#[max_length = 255]
last_modified_by -> Nullable<Varchar>,
+ customer_details -> Nullable<Bytea>,
#[max_length = 64]
locker_fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
index ecfe205b54..eefa8aa6c8 100644
--- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
@@ -103,8 +103,13 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
let payer = Payer {
name,
email,
- // [#589]: Allow securely collecting PII from customer in payments request
- document: get_doc_from_currency(country.to_string()),
+ document: item
+ .router_data
+ .get_customer_document_details()?
+ .map(|details| details.document_number)
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "customer.document_details.document_number",
+ })?,
};
let order_id = item.router_data.connector_request_reference_id.clone();
let callback_url = item.router_data.request.get_router_return_url()?;
@@ -529,23 +534,3 @@ pub struct DlocalErrorResponse {
pub message: String,
pub param: Option<String>,
}
-
-fn get_doc_from_currency(country: String) -> Secret<String> {
- let doc = match country.as_str() {
- "BR" => "91483309223",
- "ZA" => "2001014800086",
- "BD" | "GT" | "HN" | "PK" | "SN" | "TH" => "1234567890001",
- "CR" | "SV" | "VN" => "123456789",
- "DO" | "NG" => "12345678901",
- "EG" => "12345678901112",
- "GH" | "ID" | "RW" | "UG" => "1234567890111123",
- "IN" => "NHSTP6374G",
- "CI" => "CA124356789",
- "JP" | "MY" | "PH" => "123456789012",
- "NI" => "1234567890111A",
- "TZ" => "12345678912345678900",
- "MX" => "1234567890",
- _ => "12345678",
- };
- Secret::new(doc.to_string())
-}
diff --git a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
index 4759a73a93..821c932269 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
@@ -471,7 +471,7 @@ pub struct SantanderBoletoPaymentRequest {
#[serde(rename_all = "camelCase")]
pub struct Payer {
pub name: Secret<String>,
- pub document_type: enums::DocumentKind,
+ pub document_type: common_types::customers::DocumentKind,
pub document_number: Option<Secret<String>>,
pub address: Secret<String>,
pub neighborhood: Secret<String>,
@@ -484,7 +484,7 @@ pub struct Payer {
#[serde(rename_all = "camelCase")]
pub struct Beneficiary {
pub name: Option<Secret<String>>,
- pub document_type: Option<enums::DocumentKind>,
+ pub document_type: Option<common_types::customers::DocumentKind>,
pub document_number: Option<String>,
}
@@ -1274,16 +1274,16 @@ pub struct SantanderWebhookBody {
pub payment_channel: PaymentChannel,
pub payment_kind: PaymentKind,
pub covenant: String,
- pub type_of_person_agreement: enums::DocumentKind,
+ 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: enums::DocumentKind,
+ pub payer_document_type: common_types::customers::DocumentKind,
pub payer_document_number: String,
pub payer_name: String,
- pub final_beneficiary_document_type: enums::DocumentKind,
+ pub final_beneficiary_document_type: common_types::customers::DocumentKind,
pub final_beneficiary_document_number: String,
pub final_beneficiary_name: String,
pub due_date: String,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index d3abcffba7..773664c3bc 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -568,6 +568,9 @@ pub trait RouterData {
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
+ fn get_customer_document_details(
+ &self,
+ ) -> Result<Option<api_models::customers::CustomerDocumentDetails>, Error>;
fn get_optional_customer_id(&self) -> Option<id_type::CustomerId>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
@@ -1078,6 +1081,11 @@ impl<Flow, Request, Response> RouterData
.to_owned()
.ok_or_else(missing_field_err("customer_id"))
}
+ fn get_customer_document_details(
+ &self,
+ ) -> Result<Option<api_models::customers::CustomerDocumentDetails>, Error> {
+ Ok(self.customer_document_details.clone())
+ }
fn get_connector_customer_id(&self) -> Result<String, Error> {
self.connector_customer
.to_owned()
@@ -7506,6 +7514,7 @@ pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>(
l2_l3_data: data.l2_l3_data.clone(),
minor_amount_capturable: data.minor_amount_capturable,
authorized_amount: data.authorized_amount,
+ customer_document_details: data.customer_document_details.clone(),
}
}
diff --git a/crates/hyperswitch_domain_models/src/bulk_tokenization.rs b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs
index 524d5ad772..5b3b6d655b 100644
--- a/crates/hyperswitch_domain_models/src/bulk_tokenization.rs
+++ b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs
@@ -82,6 +82,8 @@ pub struct CardNetworkTokenizeRecord {
pub customer_phone_country_code: Option<String>,
#[serde(rename = "tax_registration_id")]
pub customer_tax_registration_id: Option<masking::Secret<String>>,
+ #[serde(rename = "document_details")]
+ pub customer_document_details: Option<api_models::customers::CustomerDocumentDetails>,
// Billing details
pub billing_address_city: Option<String>,
pub billing_address_country: Option<enums::CountryAlpha2>,
@@ -110,6 +112,7 @@ impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails {
phone: record.customer_phone.clone(),
phone_country_code: record.customer_phone_country_code.clone(),
tax_registration_id: record.customer_tax_registration_id.clone(),
+ document_details: record.customer_document_details.clone(),
}
}
}
@@ -225,6 +228,7 @@ impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails {
phone: customer.phone,
phone_country_code: customer.phone_country_code,
tax_registration_id: customer.tax_registration_id,
+ document_details: customer.document_details,
})
}
}
@@ -278,6 +282,7 @@ impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails {
phone: req.phone,
phone_country_code: req.phone_country_code,
tax_registration_id: req.tax_registration_id,
+ document_details: req.document_details,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index ef0c092101..8b1025c107 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -2,7 +2,7 @@ use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v2")]
use common_enums::DeleteStatus;
use common_utils::{
- crypto::{self, Encryptable},
+ crypto::{self, Encryptable, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
@@ -20,11 +20,16 @@ use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy};
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
+use serde_json::Value;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails;
-use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types};
+use crate::{
+ behaviour,
+ merchant_key_store::MerchantKeyStore,
+ type_encryption::{self as types, AsyncLift},
+};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
@@ -49,6 +54,7 @@ pub struct Customer {
pub version: common_enums::ApiVersion,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
+ pub document_details: OptionalEncryptableValue,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
@@ -79,6 +85,7 @@ pub struct Customer {
pub status: DeleteStatus,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
+ pub document_details: OptionalEncryptableValue,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
}
@@ -168,6 +175,7 @@ impl behaviour::Conversion for Customer {
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
+ document_details: self.document_details.map(Encryption::from),
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
@@ -208,6 +216,23 @@ impl behaviour::Conversion for Customer {
message: "Failed while decrypting customer data".to_string(),
},
)?;
+ let document_details = item
+ .document_details
+ .async_lift(|inner| async {
+ types::crypto_operation(
+ state,
+ common_utils::type_name!(Self),
+ types::CryptoOperation::DecryptOptional(inner),
+ keymanager::Identifier::Merchant(item.merchant_id.clone()),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed to decrypt document details".to_string(),
+ })?;
Ok(Self {
customer_id: item.customer_id,
@@ -232,6 +257,7 @@ impl behaviour::Conversion for Customer {
updated_by: item.updated_by,
version: item.version,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details,
created_by: item
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
@@ -259,6 +285,7 @@ impl behaviour::Conversion for Customer {
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
+ document_details: self.document_details.map(Encryption::from),
created_by: self
.created_by
.as_ref()
@@ -295,6 +322,7 @@ impl behaviour::Conversion for Customer {
version: self.version,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
+ document_details: self.document_details.map(Encryption::from),
created_by: self.created_by.map(|created_by| created_by.to_string()),
last_modified_by: self
.last_modified_by
@@ -362,6 +390,7 @@ impl behaviour::Conversion for Customer {
version: item.version,
status: item.status,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: None,
created_by: item
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
@@ -393,6 +422,7 @@ impl behaviour::Conversion for Customer {
version: common_types::consts::API_VERSION,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
+ document_details: self.document_details.map(Encryption::from),
created_by: self
.created_by
.as_ref()
@@ -418,6 +448,7 @@ pub struct CustomerGeneralUpdate {
pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
+ pub document_details: OptionalEncryptableValue,
pub last_modified_by: Option<String>,
}
@@ -453,6 +484,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
default_payment_method_id,
status,
tax_registration_id,
+ document_details,
last_modified_by,
} = *update;
Self {
@@ -470,6 +502,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
updated_by: None,
status,
tax_registration_id: tax_registration_id.map(Encryption::from),
+ document_details: document_details.map(Encryption::from),
last_modified_by,
}
}
@@ -491,6 +524,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
default_shipping_address: None,
status: None,
tax_registration_id: None,
+ document_details: None,
last_modified_by,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
@@ -511,6 +545,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
default_shipping_address: None,
status: None,
tax_registration_id: None,
+ document_details: None,
last_modified_by,
},
}
@@ -530,6 +565,7 @@ pub enum CustomerUpdate {
connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
tax_registration_id: crypto::OptionalEncryptableSecretString,
+ document_details: Box<OptionalEncryptableValue>,
last_modified_by: Option<String>,
},
ConnectorCustomer {
@@ -556,6 +592,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
connector_customer,
address_id,
tax_registration_id,
+ document_details,
last_modified_by,
} => Self {
name: name.map(Encryption::from),
@@ -570,6 +607,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
default_payment_method_id: None,
updated_by: None,
tax_registration_id: tax_registration_id.map(Encryption::from),
+ document_details: document_details.map(Encryption::from),
last_modified_by,
},
CustomerUpdate::ConnectorCustomer {
@@ -588,6 +626,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
updated_by: None,
address_id: None,
tax_registration_id: None,
+ document_details: None,
last_modified_by,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
@@ -606,6 +645,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
updated_by: None,
address_id: None,
tax_registration_id: None,
+ document_details: None,
last_modified_by,
},
}
@@ -756,13 +796,13 @@ pub async fn update_connector_customer_in_customers(
.unwrap_or_default();
let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| {
- let connector_customer_value = serde_json::Value::String(connector_customer_id);
+ let connector_customer_value = Value::String(connector_customer_id);
connector_customer_map.insert(connector_label.to_string(), connector_customer_value);
connector_customer_map
});
updated_connector_customer_map
- .map(serde_json::Value::Object)
+ .map(Value::Object)
.map(
|connector_customer_value| CustomerUpdate::ConnectorCustomer {
connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)),
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index acf295b266..f3e7d671ab 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -961,7 +961,7 @@ pub struct BoletoVoucherData {
/// The bank number associated with the boleto
pub bank_number: Option<Secret<String>>,
/// The type of document (e.g., CPF, CNPJ)
- pub document_type: Option<common_enums::DocumentKind>,
+ pub document_type: Option<common_types::customers::DocumentKind>,
/// The percentage of fine applied for late payment
pub fine_percentage: Option<String>,
/// The number of days after due date when fine is applied
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index b4ca313f85..4c325156ae 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -93,6 +93,7 @@ pub struct PaymentMethod {
pub vault_source_details: PaymentMethodVaultSourceDetails,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
+ pub customer_details: OptionalEncryptableValue,
}
#[cfg(feature = "v2")]
@@ -138,6 +139,8 @@ pub struct PaymentMethod {
pub vault_type: Option<storage_enums::VaultType>,
pub created_by: Option<CreatedBy>,
pub last_modified_by: Option<CreatedBy>,
+ #[encrypt(ty = Value)]
+ pub customer_details: Option<Encryptable<customers::CustomerDocumentDetails>>,
}
impl PaymentMethod {
@@ -365,6 +368,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
+ customer_details: self.customer_details.map(|val| val.into()),
})
}
@@ -382,6 +386,7 @@ impl super::behaviour::Conversion for PaymentMethod {
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
+ customer_details,
) = async {
let payment_method_data = item
.payment_method_data
@@ -428,10 +433,26 @@ impl super::behaviour::Conversion for PaymentMethod {
})
.await?;
+ let customer_details = item
+ .customer_details
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?;
+
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>((
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
+ customer_details,
))
}
.await
@@ -487,6 +508,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: item
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
+ customer_details,
})
}
@@ -537,6 +559,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
+ customer_details: self.customer_details.map(|val| val.into()),
})
}
}
@@ -581,6 +604,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
+ customer_details: self.customer_details.map(|val| val.into()),
})
}
@@ -607,6 +631,7 @@ impl super::behaviour::Conversion for PaymentMethod {
network_token_payment_method_data: storage_model
.network_token_payment_method_data,
external_vault_token_data: storage_model.external_vault_token_data,
+ customer_details: storage_model.customer_details,
},
)),
key_manager_identifier,
@@ -649,6 +674,17 @@ impl super::behaviour::Conversion for PaymentMethod {
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Network token Payment Method Data")?;
+ let customer_details = data
+ .customer_details
+ .map(|customer_details| {
+ customer_details.deserialize_inner_value(|value| {
+ value.parse_value("Payment Method Customer Details")
+ })
+ })
+ .transpose()
+ .change_context(common_utils::errors::CryptoError::DecodingFailed)
+ .attach_printable("Error while deserializing Payment Method Customer Details")?;
+
let external_vault_token_data = data
.external_vault_token_data
.map(|external_vault_token_data| {
@@ -695,6 +731,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: storage_model
.last_modified_by
.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),
+ customer_details,
})
}
.await
@@ -737,6 +774,7 @@ impl super::behaviour::Conversion for PaymentMethod {
last_modified_by: self
.last_modified_by
.map(|last_modified_by| last_modified_by.to_string()),
+ customer_details: self.customer_details.map(|val| val.into()),
})
}
}
@@ -1165,6 +1203,7 @@ impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>
}),
metadata: None,
tax_registration_id: None,
+ document_details: None,
},
connector_customer_details,
})
@@ -1377,6 +1416,7 @@ mod tests {
vault_source_details: Default::default(),
created_by: None,
last_modified_by: None,
+ customer_details: None,
};
payment_method.clone()
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 077a952c88..963de4d97a 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1,6 +1,7 @@
#[cfg(feature = "v2")]
use std::marker::PhantomData;
+use api_models::customers::CustomerDocumentDetails;
#[cfg(feature = "v2")]
use api_models::payments::{ConnectorMetadata, SessionToken, VaultSessionDetails};
use common_types::primitive_wrappers;
@@ -40,8 +41,9 @@ pub mod split_payments;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount};
+use masking::ExposeInterface;
-use self::payment_attempt::PaymentAttempt;
+use self::{payment_attempt::PaymentAttempt, payment_intent::CustomerData};
#[cfg(feature = "v2")]
use crate::{
address::Address, business_profile, customer, errors, merchant_connector_account,
@@ -378,6 +380,22 @@ impl PaymentIntent {
Ok(())
}
}
+
+ pub fn get_customer_document_details(
+ &self,
+ ) -> Result<Option<CustomerDocumentDetails>, common_utils::errors::ParsingError> {
+ self.customer_details
+ .as_ref()
+ .map(|details| {
+ let decrypted_value = details.clone().into_inner().expose();
+
+ ValueExt::parse_value::<CustomerData>(decrypted_value, "CustomerData")
+ .map(|data| data.customer_document_details)
+ })
+ .transpose()
+ .map(|opt| opt.flatten())
+ .map_err(|report| (*report.current_context()).clone())
+ }
}
#[cfg(feature = "v2")]
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index c54ed1a8e7..c0cab4f17e 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1,3 +1,4 @@
+use api_models::customers::CustomerDocumentDetails;
use common_types::primitive_wrappers;
#[cfg(feature = "v1")]
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
@@ -160,6 +161,7 @@ pub struct CustomerData {
pub phone: Option<Secret<String>>,
pub phone_country_code: Option<String>,
pub tax_registration_id: Option<Secret<String>>,
+ pub customer_document_details: Option<CustomerDocumentDetails>,
}
impl CustomerData {
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 3233521bb1..4562685d65 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -1,5 +1,6 @@
use std::{collections::HashMap, marker::PhantomData};
+use api_models::customers::CustomerDocumentDetails;
use cards::NetworkToken;
use common_types::{payments as common_payment_types, primitive_wrappers};
use common_utils::{
@@ -119,6 +120,9 @@ pub struct RouterData<Flow, Request, Response> {
/// Indicates whether the payment ID was provided by the merchant (true),
/// or generated internally by Hyperswitch (false)
pub is_payment_id_from_merchant: Option<bool>,
+
+ // Document details of the customer consisting of document number and type
+ pub customer_document_details: Option<CustomerDocumentDetails>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index cee8e0fd38..7ce6cc7cc4 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1543,6 +1543,7 @@ pub struct CustomerDetails {
pub phone: Option<Secret<String, masking::WithType>>,
pub phone_country_code: Option<String>,
pub tax_registration_id: Option<Secret<String, masking::WithType>>,
+ pub document_details: Option<api_models::customers::CustomerDocumentDetails>,
}
impl CustomerDetails {
@@ -1552,6 +1553,7 @@ impl CustomerDetails {
|| self.phone.is_some()
|| self.phone_country_code.is_some()
|| self.tax_registration_id.is_some()
+ || self.document_details.is_some()
{
Some(payments::payment_intent::CustomerData {
name: self.name.clone(),
@@ -1559,6 +1561,7 @@ impl CustomerDetails {
phone: self.phone.clone(),
phone_country_code: self.phone_country_code.clone(),
tax_registration_id: self.tax_registration_id.clone(),
+ customer_document_details: self.document_details.clone(),
})
} else {
None
diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs
index 2804647cb5..de6e4d4dad 100644
--- a/crates/hyperswitch_interfaces/src/conversion_impls.rs
+++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs
@@ -96,6 +96,7 @@ fn get_default_router_data<F, Req, Resp>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 1ef759d8a2..9de1081e81 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -335,6 +335,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
+ api_models::customers::CustomerDocumentDetails,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::CustomerPaymentMethodUpdateResponse,
@@ -379,7 +380,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::Currency,
api_models::enums::CavvAlgorithm,
api_models::enums::ExemptionIndicator,
- api_models::enums::DocumentKind,
+ common_types::customers::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index ac39e72a81..a3200f1785 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -255,6 +255,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
+ api_models::customers::CustomerDocumentDetails,
api_models::ephemeral_key::ResourceId,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodIntentCreate,
@@ -311,7 +312,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::Currency,
api_models::enums::CavvAlgorithm,
api_models::enums::ExemptionIndicator,
- api_models::enums::DocumentKind,
+ common_types::customers::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs
index 96bc3cfc8d..ce7d95545c 100644
--- a/crates/payment_methods/src/controller.rs
+++ b/crates/payment_methods/src/controller.rs
@@ -57,6 +57,7 @@ pub trait PaymentMethodsController {
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<PaymentMethodVaultSourceDetails>,
+ payment_method_customer_details_encrypted: crypto::OptionalEncryptableValue,
) -> errors::PmResult<payment_methods::PaymentMethod>;
#[cfg(feature = "v1")]
diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs
index 8c1e746ad6..3b7dfc0958 100644
--- a/crates/payment_methods/src/core/migration/payment_methods.rs
+++ b/crates/payment_methods/src/core/migration/payment_methods.rs
@@ -450,6 +450,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
None,
None,
Default::default(),
+ None,
)
.await?;
migration_status.connector_mandate_details_migrated(
@@ -614,6 +615,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
vault_source_details: Default::default(),
created_by: None,
last_modified_by: None,
+ customer_details: None,
},
provider.get_account().storage_scheme,
)
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 78b297b330..7604694993 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -214,6 +214,7 @@ pub fn construct_router_data<F: Clone, Req, Res>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
})
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index bb1189acfa..3f3b74b8d3 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,3 +1,4 @@
+use api_models::customers::CustomerDocumentDetails;
use common_types::primitive_wrappers::CustomerListLimit;
use common_utils::{
crypto::Encryptable,
@@ -10,7 +11,9 @@ use common_utils::{
},
};
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::payment_methods as payment_methods_domain;
+use hyperswitch_domain_models::{
+ payment_methods as payment_methods_domain, type_encryption::AsyncLift,
+};
use masking::{ExposeInterface, Secret, SwitchStrategy};
use payment_methods::controller::PaymentMethodsController;
use router_env::{instrument, tracing};
@@ -30,9 +33,11 @@ use crate::{
services,
types::{
api::customers,
- domain::{self, types},
+ domain::{
+ self,
+ types::{self, CryptoOperation},
+ },
storage::{self, enums},
- transformers::ForeignFrom,
},
};
@@ -45,6 +50,15 @@ pub async fn create_customer(
customer_data: customers::CustomerRequest,
connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>,
) -> errors::CustomerResponse<customers::CustomerResponse> {
+ customer_data
+ .document_details
+ .as_ref()
+ .map(|doc_details| doc_details.validate())
+ .transpose()
+ .map_err(|err| errors::CustomersErrorResponse::InvalidRequestData {
+ message: err.to_string(),
+ })?;
+
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -141,6 +155,39 @@ impl CustomerCreateBridge for customers::CustomerRequest {
state,
};
+ let document_details_encrypted = self
+ .document_details
+ .clone()
+ .async_lift(|inner| async move {
+ let encoded_inner = inner
+ .map(|details| CustomerDocumentDetails::to(&details))
+ .transpose()
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to encode customer document details for encryption",
+ )?;
+
+ let crypto_result = types::crypto_operation(
+ &state.into(),
+ common_utils::type_name!(domain::Customer),
+ CryptoOperation::EncryptOptional(encoded_inner),
+ Identifier::Merchant(merchant_id.clone()),
+ provider.get_key_store().key.peek(),
+ )
+ .await
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Crypto operation failed during document details encryption")?;
+
+ let final_val = crypto_result
+ .try_into_optionaloperation()
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse encrypted document details")?;
+
+ Ok(final_val)
+ })
+ .await
+ .attach_printable("Unable to encrypt document_details")?;
+
let address_from_db = customer_billing_address_struct
.encrypt_customer_address_and_set_to_db(db)
.await?;
@@ -148,16 +195,14 @@ impl CustomerCreateBridge for customers::CustomerRequest {
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(
- domain::FromRequestEncryptableCustomer::to_encryptable(
- domain::FromRequestEncryptableCustomer {
- name: self.name.clone(),
- email: self.email.clone().map(|a| a.expose().switch_strategy()),
- phone: self.phone.clone(),
- tax_registration_id: self.tax_registration_id.clone(),
- },
- ),
- ),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: self.name.clone(),
+ email: self.email.clone().map(|a| a.expose().switch_strategy()),
+ phone: self.phone.clone(),
+ tax_registration_id: self.tax_registration_id.clone(),
+ },
+ )),
Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
@@ -206,6 +251,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: document_details_encrypted,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None,
@@ -218,7 +264,9 @@ impl CustomerCreateBridge for customers::CustomerRequest {
) -> errors::CustomerResponse<customers::CustomerResponse> {
let address = self.get_address();
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from((customer.clone(), address)),
+ customers::CustomerResponse::try_from((customer.clone(), address))
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
}
@@ -323,6 +371,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
version: common_types::consts::API_VERSION,
status: common_enums::DeleteStatus::Active,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: None,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None,
@@ -334,7 +383,9 @@ impl CustomerCreateBridge for customers::CustomerRequest {
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from(customer.clone()),
+ customers::CustomerResponse::try_from(customer.clone())
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
}
@@ -514,7 +565,9 @@ pub async fn retrieve_customer(
None => None,
};
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from((response, address)),
+ customers::CustomerResponse::try_from((response, address))
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
@@ -537,7 +590,9 @@ pub async fn retrieve_customer(
.switch()?;
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from(response),
+ customers::CustomerResponse::try_from(response)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
@@ -571,14 +626,20 @@ pub async fn list_customers(
#[cfg(feature = "v1")]
let customers = domain_customers
.into_iter()
- .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
- .collect();
+ .map(|domain_customer| {
+ customers::CustomerResponse::try_from((domain_customer, None))
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")
+ })
+ .collect::<Result<_, _>>()?;
#[cfg(feature = "v2")]
let customers = domain_customers
.into_iter()
- .map(customers::CustomerResponse::foreign_from)
- .collect();
+ .map(customers::CustomerResponse::try_from)
+ .collect::<Result<Vec<_>, _>>()
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?;
Ok(services::ApplicationResponse::Json(customers))
}
@@ -613,15 +674,19 @@ pub async fn list_customers_with_count(
let customers: Vec<customers::CustomerResponse> = domain_customers
.0
.into_iter()
- .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
- .collect();
+ .map(|domain_customer| customers::CustomerResponse::try_from((domain_customer, None)))
+ .collect::<Result<Vec<_>, _>>()
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?;
#[cfg(feature = "v2")]
- let customers: Vec<customers::CustomerResponse> = domain_customers
+ let customers = domain_customers
.0
.into_iter()
- .map(customers::CustomerResponse::foreign_from)
- .collect();
+ .map(customers::CustomerResponse::try_from)
+ .collect::<Result<Vec<_>, _>>()
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?;
Ok(services::ApplicationResponse::Json(
customers::CustomerListResponse {
@@ -748,7 +813,8 @@ impl CustomerDeleteBridge for id_type::GlobalCustomerId {
default_shipping_address: None,
default_payment_method_id: None,
status: Some(common_enums::DeleteStatus::Redacted),
- tax_registration_id: Some(redacted_encrypted_value),
+ tax_registration_id: Some(redacted_encrypted_value.clone()),
+ document_details: None,
last_modified_by: None,
}));
@@ -898,7 +964,7 @@ impl CustomerDeleteBridge for id_type::CustomerId {
let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation(
key_manager_state,
type_name!(storage::Address),
- types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
+ CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier.clone(),
key,
)
@@ -958,7 +1024,7 @@ impl CustomerDeleteBridge for id_type::CustomerId {
types::crypto_operation(
key_manager_state,
type_name!(storage::Customer),
- types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
+ CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier,
key,
)
@@ -973,6 +1039,7 @@ impl CustomerDeleteBridge for id_type::CustomerId {
connector_customer: Box::new(None),
address_id: None,
tax_registration_id: Some(redacted_encrypted_value.clone()),
+ document_details: Box::new(None),
last_modified_by: None,
};
@@ -1004,6 +1071,16 @@ pub async fn update_customer(
provider: domain::Provider,
update_customer: customers::CustomerUpdateRequestInternal,
) -> errors::CustomerResponse<customers::CustomerResponse> {
+ update_customer
+ .request
+ .document_details
+ .as_ref()
+ .map(|doc| doc.validate())
+ .transpose()
+ .map_err(|err| errors::CustomersErrorResponse::InvalidRequestData {
+ message: err.to_string(),
+ })?;
+
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
//Add this in update call if customer can be updated anywhere else
@@ -1229,19 +1306,17 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(
- domain::FromRequestEncryptableCustomer::to_encryptable(
- domain::FromRequestEncryptableCustomer {
- name: self.name.clone(),
- email: self
- .email
- .as_ref()
- .map(|a| a.clone().expose().switch_strategy()),
- phone: self.phone.clone(),
- tax_registration_id: self.tax_registration_id.clone(),
- },
- ),
- ),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: self.name.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ phone: self.phone.clone(),
+ tax_registration_id: self.tax_registration_id.clone(),
+ },
+ )),
Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
@@ -1253,6 +1328,36 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
+ let document_details = hyperswitch_domain_models::type_encryption::crypto_operation(
+ key_manager_state,
+ type_name!(CustomerDocumentDetails),
+ CryptoOperation::EncryptOptional(
+ self.document_details
+ .as_ref()
+ .map(|details| {
+ details.to().map_err(|e| {
+ error_stack::Report::new(
+ errors::CustomersErrorResponse::InternalServerError,
+ )
+ .attach_printable(format!("Failed to encode details: {:?}", e))
+ })
+ })
+ .transpose()?,
+ ),
+ Identifier::Merchant(provider.get_account().get_id().clone()),
+ key,
+ )
+ .await
+ .map_err(|e| {
+ error_stack::Report::new(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable(e)
+ })?
+ .try_into_optionaloperation()
+ .map_err(|e| {
+ error_stack::Report::new(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable(e)
+ })?;
+
let response = db
.update_customer_by_customer_id_merchant_id(
domain_customer.customer_id.to_owned(),
@@ -1270,6 +1375,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
}),
phone: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: Box::new(document_details),
phone_country_code: self.phone_country_code.clone(),
metadata: Box::new(self.metadata.clone()),
description: self.description.clone(),
@@ -1292,7 +1398,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
) -> errors::CustomerResponse<customers::CustomerResponse> {
let address = self.get_address();
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from((customer.clone(), address)),
+ customers::CustomerResponse::try_from((customer.clone(), address))
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
}
@@ -1380,6 +1488,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
})),
phone: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: None,
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
description: self.description.clone(),
@@ -1403,7 +1512,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::foreign_from(customer.clone()),
+ customers::CustomerResponse::try_from(customer.clone())
+ .change_context(errors::CustomersErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert domain customer to CustomerResponse")?,
))
}
}
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 30e3e134d8..1db60bc104 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -174,6 +174,13 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: self
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to extract customer document details from payment_intent",
+ )?,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index 39542a898b..afce3dc6d6 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -137,6 +137,10 @@ pub async fn construct_fulfillment_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index 8606af945b..b494ca851f 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -137,6 +137,13 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: self
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to extract customer document details from payment_intent",
+ )?,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index 291f285e44..55766031ea 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -153,6 +153,13 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: self
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to extract customer document details from payment_intent",
+ )?,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index f3a91175f5..b0f366681b 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -155,6 +155,13 @@ impl
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: self
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to extract customer document details from payment_intent",
+ )?,
};
Ok(router_data)
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index e89065e55d..e554477108 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -92,6 +92,7 @@ pub async fn construct_mandate_revoke_router_data(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 14d1058106..cba1131432 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -2423,6 +2423,7 @@ pub async fn create_payment_method_for_intent(
vault_type: None,
created_by: None,
last_modified_by: None,
+ customer_details: None,
},
storage_scheme,
)
@@ -2508,6 +2509,7 @@ pub async fn construct_payment_method_object(
vault_type: None,
created_by: None,
last_modified_by: None,
+ customer_details: None,
})
}
@@ -2567,6 +2569,7 @@ pub async fn create_payment_method_for_confirm(
vault_type,
created_by: None,
last_modified_by: None,
+ customer_details: None,
},
storage_scheme,
)
@@ -4966,6 +4969,7 @@ async fn create_single_use_tokenization_flow(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
let payment_method_token_response = Box::pin(tokenization::add_token_for_payment_method(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 066de2ca90..70573c6b4c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -141,6 +141,7 @@ impl PaymentMethodsController for PmCards<'_> {
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>,
+ payment_method_customer_details_encrypted: crypto::OptionalEncryptableValue,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*self.state.store;
let customer = db
@@ -202,6 +203,7 @@ impl PaymentMethodsController for PmCards<'_> {
.unwrap_or(domain::PaymentMethodVaultSourceDetails::InternalVault),
created_by: None,
last_modified_by: None,
+ customer_details: payment_method_customer_details_encrypted,
},
self.provider.get_account().storage_scheme,
)
@@ -510,6 +512,7 @@ impl PaymentMethodsController for PmCards<'_> {
network_token_locker_id,
network_token_payment_method_data,
vault_source_details,
+ None,
)
.await
}
@@ -1427,6 +1430,7 @@ pub async fn get_client_secret_or_add_payment_method(
None,
None,
Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault type
+ None,
)
.await?;
diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs
index 5b8b2f7c5f..7366947123 100644
--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs
@@ -366,6 +366,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
.tax_registration_id
.clone()
.map(|tax_registration_id| tax_registration_id.into_inner()),
+ document_details: None,
}))
},
)
@@ -435,6 +436,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: None,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None, // Same as created_by on creation
@@ -463,6 +465,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
phone: self.customer.phone.clone(),
phone_country_code: self.customer.phone_country_code.clone(),
tax_registration_id: self.customer.tax_registration_id.clone(),
+ document_details: self.customer.document_details.clone(),
})
}
@@ -604,6 +607,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
Some(stored_locker_resp.store_token_resp.card_reference.clone()),
Some(enc_token_data),
Default::default(), // this method is used only for card bulk tokenization, and currently external vault is not supported for this hence passing Default i.e. InternalVault
+ None,
)
.await
}
diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
index f104a9fdf4..9dba8ce3e6 100644
--- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
@@ -376,6 +376,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
.tax_registration_id
.clone()
.map(|tax_registration_id| tax_registration_id.into_inner()),
+ document_details: None,
};
Ok((locker_id, customer_details))
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 69ef21dbce..2ade484d05 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -7,6 +7,7 @@ pub use ::payment_methods::helpers::{
#[cfg(feature = "v2")]
use api_models::ephemeral_key::ClientSecretResponse;
use api_models::{
+ customers::CustomerDocumentDetails,
mandates::RecurringDetails,
payments::{
additional_info::{self as payment_additional_types},
@@ -33,9 +34,9 @@ use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, ResultExt};
use futures::future::Either;
-pub use hyperswitch_domain_models::customer;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
+pub use hyperswitch_domain_models::{customer, type_encryption::AsyncLift};
use hyperswitch_domain_models::{
mandates::MandateData,
payment_method_data::{GetPaymentMethodType, PazeWalletData},
@@ -99,7 +100,10 @@ use crate::{
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
- domain::{self, types},
+ domain::{
+ self,
+ types::{self, CryptoOperation},
+ },
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
@@ -139,7 +143,7 @@ pub async fn create_or_update_address_for_payment_by_request(
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
- types::CryptoOperation::BatchEncrypt(
+ CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address.address.as_ref().and_then(|a| a.line1.clone()),
@@ -355,29 +359,27 @@ pub async fn get_domain_address(
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
- types::CryptoOperation::BatchEncrypt(
- domain::FromRequestEncryptableAddress::to_encryptable(
- domain::FromRequestEncryptableAddress {
- line1: address.address.as_ref().and_then(|a| a.line1.clone()),
- line2: address.address.as_ref().and_then(|a| a.line2.clone()),
- line3: address.address.as_ref().and_then(|a| a.line3.clone()),
- state: address.address.as_ref().and_then(|a| a.state.clone()),
- first_name: address.address.as_ref().and_then(|a| a.first_name.clone()),
- last_name: address.address.as_ref().and_then(|a| a.last_name.clone()),
- zip: address.address.as_ref().and_then(|a| a.zip.clone()),
- phone_number: address
- .phone
- .as_ref()
- .and_then(|phone_details| phone_details.number.clone())
- .and_then(utils::trim_secret_string),
- email: address
- .email
- .as_ref()
- .map(|a| a.clone().expose().switch_strategy()),
- origin_zip: address.address.as_ref().and_then(|a| a.origin_zip.clone()),
- },
- ),
- ),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address.address.as_ref().and_then(|a| a.line1.clone()),
+ line2: address.address.as_ref().and_then(|a| a.line2.clone()),
+ line3: address.address.as_ref().and_then(|a| a.line3.clone()),
+ state: address.address.as_ref().and_then(|a| a.state.clone()),
+ first_name: address.address.as_ref().and_then(|a| a.first_name.clone()),
+ last_name: address.address.as_ref().and_then(|a| a.last_name.clone()),
+ zip: address.address.as_ref().and_then(|a| a.zip.clone()),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone_details| phone_details.number.clone())
+ .and_then(utils::trim_secret_string),
+ email: address
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ origin_zip: address.address.as_ref().and_then(|a| a.origin_zip.clone()),
+ },
+ )),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
@@ -1536,9 +1538,13 @@ pub fn validate_customer_information(
"The field names `{mismatched_fields}` sent in both places is ambiguous"
),
})?
- } else {
- Ok(())
}
+ request.validate_document_details().map_err(|err| {
+ errors::ApiErrorResponse::PreconditionFailed {
+ message: err.to_string(),
+ }
+ })?;
+ Ok(())
}
pub async fn validate_card_ip_blocking_for_business_profile(
@@ -1659,6 +1665,11 @@ pub fn get_customer_details_from_request(
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
+ let document_details = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.document_details.clone());
+
CustomerDetails {
customer_id,
name: customer_name,
@@ -1666,6 +1677,7 @@ pub fn get_customer_details_from_request(
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
+ document_details,
}
}
@@ -1727,6 +1739,7 @@ pub async fn populate_raw_customer_details<F: Clone>(
phone: request_customer_details.phone.clone(),
phone_country_code: request_customer_details.phone_country_code.clone(),
tax_registration_id: request_customer_details.tax_registration_id.clone(),
+ customer_document_details: request_customer_details.document_details.clone(),
})
} else {
None
@@ -1768,6 +1781,10 @@ pub async fn populate_raw_customer_details<F: Clone>(
.tax_registration_id
.clone()
.or(parsed_customer_data.tax_registration_id.clone()),
+ customer_document_details: request_customer_details
+ .document_details
+ .clone()
+ .or(parsed_customer_data.customer_document_details.clone()),
})
.or(temp_customer_data);
@@ -1875,7 +1892,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(
+ CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: request_customer_details.name.clone(),
@@ -1899,6 +1916,48 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
+
+ let document_details = if request_customer_details.document_details.is_some() {
+ request_customer_details
+ .document_details
+ .clone()
+ .async_lift(|inner| async move {
+ let encoded_inner = inner
+ .as_ref()
+ .map(CustomerDocumentDetails::to)
+ .transpose()
+ .change_context(storage_impl::StorageError::EncryptionError)
+ .attach_printable(
+ "Failed to encode customer document details for encryption",
+ )?;
+
+ let crypto_result = types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::Customer),
+ CryptoOperation::EncryptOptional(encoded_inner),
+ Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
+ key,
+ )
+ .await
+ .change_context(storage_impl::StorageError::EncryptionError)
+ .attach_printable(
+ "Crypto operation failed during document details encryption",
+ )?;
+
+ crypto_result
+ .try_into_optionaloperation()
+ .change_context(storage_impl::StorageError::EncryptionError)
+ .attach_printable("Failed to parse encrypted document details result")
+ })
+ .await
+ .change_context(storage_impl::StorageError::EncryptionError)
+ .attach_printable("Lift operation failed for document_details")?
+ } else {
+ customer_data
+ .as_ref()
+ .and_then(|c| c.document_details.clone())
+ };
+
Some(match customer_data {
Some(c) => {
let implicit_customer_update = configs::get_config_bool(
@@ -1924,6 +1983,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
| request_customer_details.phone.is_some()
| request_customer_details.phone_country_code.is_some()
| request_customer_details.tax_registration_id.is_some())
+ | request_customer_details.document_details.is_some()
{
let customer_update = Update {
name: encryptable_customer.name,
@@ -1943,6 +2003,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
metadata: Box::new(None),
address_id: None,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details: Box::new(document_details),
last_modified_by: None,
};
@@ -1985,6 +2046,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None, // Same as created_by on creation
@@ -2013,6 +2075,17 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
.tax_registration_id
.clone()
.map(|val| val.into_inner()),
+ customer_document_details: customer
+ .document_details
+ .clone()
+ .map(|encryptable| {
+ encryptable
+ .into_inner()
+ .expose()
+ .parse_value::<CustomerDocumentDetails>("CustomerDocumentDetails")
+ .change_context(storage_impl::StorageError::SerializationFailed)
+ })
+ .transpose()?,
};
// Merge with existing payment intent customer details if present
@@ -4786,6 +4859,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
l2_l3_data: router_data.l2_l3_data,
minor_amount_capturable: router_data.minor_amount_capturable,
authorized_amount: router_data.authorized_amount,
+ customer_document_details: router_data.customer_document_details,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 3c8a50dbf2..f4731f3a2b 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -306,6 +306,13 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
merchant_connector_details.creds_identifier.to_owned()
});
+ let customer_document_details = payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "failed while fetching customer_document_details from payment_intent",
+ )?;
+
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
@@ -372,6 +379,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
phone: request.phone.clone(),
phone_country_code: request.phone_country_code.clone(),
tax_registration_id: None,
+ document_details: customer_document_details,
});
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index dc8abb8de4..afe30ec8e2 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1480,7 +1480,6 @@ impl PaymentCreate {
// Derivation of directly supplied Customer data in our Payment Create Request
let raw_customer_details =
helpers::get_customer_details_from_request(request).get_customer_data();
-
let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then(
|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(_) => Some(true),
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index b36cbb37dd..f3ac4543cd 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -432,6 +432,12 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
+ let customer_details = payment_data
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?;
+
let save_payment_call_future = Box::pin(tokenization::save_payment_method(
state,
connector_name.clone(),
@@ -447,6 +453,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
vault_operation.clone(),
payment_method_info.clone(),
payment_data.payment_method_token.clone(),
+ customer_details.clone(),
));
let is_connector_mandate = resp.request.customer_acceptance.is_some()
@@ -597,6 +604,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
vault_operation.clone(),
payment_method_info.clone(),
payment_method_token.clone(),
+ customer_details.clone(),
))
.await;
@@ -1604,6 +1612,11 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
let vault_operation = payment_data.vault_operation.clone();
let payment_method_info = payment_data.payment_method_info.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
+ let customer_details = payment_data
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?;
let tokenization::SavePaymentMethodDataResponse {
payment_method_id,
connector_mandate_reference_id,
@@ -1623,6 +1636,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
vault_operation,
payment_method_info,
payment_data.payment_method_token.clone(),
+ customer_details,
))
.await?;
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 4f1f9dce76..31445d40b8 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -134,6 +134,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR
phone: None,
phone_country_code: None,
tax_registration_id: None,
+ document_details: None,
};
let creds_identifier = request
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 92a627539e..9f98a67205 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -1,7 +1,8 @@
use std::marker::PhantomData;
use api_models::{
- enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails,
+ customers::CustomerDocumentDetails, enums::FrmSuggestion, mandates::RecurringDetails,
+ payments::RequestSurchargeDetails,
};
use async_trait::async_trait;
use common_utils::{
@@ -1092,6 +1093,15 @@ impl ForeignTryFrom<domain::Customer> for CustomerData {
tax_registration_id: value
.tax_registration_id
.map(|tax_registration_id| tax_registration_id.into_inner()),
+ customer_document_details: CustomerDocumentDetails::from(
+ &value
+ .document_details
+ .map(|customer_document_details| customer_document_details.into_inner()),
+ )
+ .map_err(|report| {
+ router_env::logger::error!(error = ?report, "Failed to convert customer document details");
+ errors::ApiErrorResponse::InternalServerError
+ })?,
})
}
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 165e4d4985..982530cd35 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use ::payment_methods::controller::PaymentMethodsController;
use api_models::payments::ConnectorMandateReferenceId;
use common_enums::{ConnectorMandateStatus, PaymentMethod};
-use common_types::callback_mapper::CallbackMapperData;
+use common_types::{self, callback_mapper::CallbackMapperData};
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, Encode, ValueExt},
@@ -130,6 +130,7 @@ pub async fn save_payment_method<FData>(
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
payment_method_token: Option<hyperswitch_domain_models::router_data::PaymentMethodToken>,
+ customer_details: Option<api_models::customers::CustomerDocumentDetails>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
@@ -370,6 +371,21 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method billing address")?;
+ let payment_method_customer_details_encrypted: Option<
+ Encryptable<Secret<serde_json::Value>>,
+ > = customer_details
+ .async_map(|customer_details| {
+ create_encrypted_data(
+ &key_manager_state,
+ platform.get_processor().get_key_store(),
+ customer_details,
+ )
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt payment method customer details")?;
+
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let (external_vault_details, vault_type) = match &business_profile.external_vault_details{
@@ -478,6 +494,7 @@ where
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
+ payment_method_customer_details_encrypted,
)
.await
} else {
@@ -596,6 +613,7 @@ where
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
+ payment_method_customer_details_encrypted,
)
.await
} else {
@@ -819,6 +837,7 @@ where
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
+ payment_method_customer_details_encrypted,
)
.await?;
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 4a4aca2e2e..dc43161510 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -221,6 +221,7 @@ where
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
}
@@ -571,6 +572,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -917,6 +919,7 @@ pub async fn construct_payment_router_data_for_capture<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -1051,6 +1054,7 @@ pub async fn construct_router_data_for_psync<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -1419,6 +1423,7 @@ pub async fn construct_payment_router_data_for_sdk_session<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -1645,6 +1650,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -1870,6 +1876,12 @@ where
});
crate::logger::debug!("unified address details {:?}", unified_address);
+ let customer_document_details = payment_data
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?;
+
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: processor.get_account().get_id().clone(),
@@ -1958,6 +1970,7 @@ where
l2_l3_data,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details,
};
Ok(router_data)
@@ -2173,6 +2186,11 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_data
+ .payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
@@ -3603,6 +3621,7 @@ where
// If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the
// same. If the customer is deleted then we use the customer table to populate customer details
+
let customer_details_response = payment_intent
.customer_details
.clone()
@@ -3619,6 +3638,7 @@ where
email: customer_details.email,
phone: customer_details.phone,
phone_country_code: customer_details.phone_country_code,
+ customer_document_details: customer_details.customer_document_details,
});
headers.extend(
@@ -4287,7 +4307,8 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
name: parsed_data.name,
phone: parsed_data.phone,
email: parsed_data.email,
- phone_country_code:parsed_data.phone_country_code
+ phone_country_code:parsed_data.phone_country_code,
+ customer_document_details: parsed_data.customer_document_details
}),
Err(e) => {
router_env::logger::error!("Failed to parse 'CustomerDetailsResponse' from payment method data. Error: {e:?}");
@@ -6340,6 +6361,7 @@ impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails {
phone: customer.phone,
phone_country_code: customer.phone_country_code,
tax_registration_id: customer.tax_registration_id,
+ document_details: customer.document_details,
}
}
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index d1c8995f28..c7e9190785 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -1,5 +1,5 @@
use ::payment_methods::controller::PaymentMethodsController;
-use api_models::{enums, payment_methods::Card, payouts};
+use api_models::{customers::CustomerDocumentDetails, enums, payment_methods::Card, payouts};
use common_utils::{
crypto::Encryptable,
encryption::Encryption,
@@ -652,6 +652,7 @@ pub async fn save_payout_data_to_locker(
None,
None,
Default::default(),
+ None,
)
.await?,
);
@@ -843,6 +844,35 @@ pub(super) async fn get_or_create_customer_details(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form EncryptableCustomer")?;
+ let document_details = customer_details
+ .document_details
+ .clone()
+ .async_lift(|inner| async move {
+ let encrypted_inner = inner
+ .as_ref()
+ .map(CustomerDocumentDetails::to)
+ .transpose()
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)
+ .attach_printable(
+ "Failed to convert CustomerDocumentDetails to SecretSerdeValue",
+ )?;
+
+ crypto_operation(
+ &state.into(),
+ common_utils::type_name!(domain::Customer),
+ CryptoOperation::EncryptOptional(encrypted_inner),
+ Identifier::Merchant(
+ platform.get_processor().get_key_store().merchant_id.clone(),
+ ),
+ platform.get_processor().get_key_store().key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt document_details")?;
+
let customer = domain::Customer {
customer_id: customer_id.clone(),
merchant_id: merchant_id.to_owned().clone(),
@@ -867,6 +897,7 @@ pub(super) async fn get_or_create_customer_details(
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
+ document_details,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None, // Same as created_by on creation
@@ -1417,6 +1448,11 @@ pub(super) fn get_customer_details_from_request(
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
+ let document_details = request
+ .customer
+ .as_ref()
+ .and_then(|customer_details| customer_details.document_details.clone());
+
CustomerDetails {
customer_id,
name: customer_name,
@@ -1424,6 +1460,7 @@ pub(super) fn get_customer_details_from_request(
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
+ document_details,
}
}
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index bec8637514..711a42be23 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -530,6 +530,7 @@ async fn store_bank_details_in_payment_methods(
vault_source_details: Default::default(),
created_by: None,
last_modified_by: None,
+ customer_details: None,
};
new_entries.push(pm_new);
diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rs
index a54daf3dc2..9e987887f4 100644
--- a/crates/router/src/core/relay/utils.rs
+++ b/crates/router/src/core/relay/utils.rs
@@ -159,6 +159,7 @@ pub async fn construct_relay_refund_router_data<F>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -301,6 +302,7 @@ pub async fn construct_relay_capture_router_data(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -455,6 +457,7 @@ pub async fn construct_relay_payments_retrieve_router_data(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs
index 86d6bb2575..6931831b31 100644
--- a/crates/router/src/core/unified_authentication_service.rs
+++ b/crates/router/src/core/unified_authentication_service.rs
@@ -934,6 +934,7 @@ impl
phone: details.phone,
phone_country_code: details.phone_country_code,
tax_registration_id: details.tax_registration_id,
+ document_details: details.customer_document_details,
})
} else {
None
diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rs
index 50b5f75c1a..dce5caf991 100644
--- a/crates/router/src/core/unified_authentication_service/utils.rs
+++ b/crates/router/src/core/unified_authentication_service/utils.rs
@@ -147,6 +147,7 @@ pub fn construct_uas_router_data<F: Clone, Req, Res>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
})
}
@@ -697,6 +698,7 @@ pub fn construct_uas_webhook_router_data<F: Clone, Req, Res>(
l2_l3_data: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
+ customer_document_details: None,
})
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 0d508643b5..f91ee420a5 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -218,6 +218,7 @@ pub async fn construct_payout_router_data<'a, F>(
phone: c.phone.map(Encryptable::into_inner),
phone_country_code: c.phone_country_code,
tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner),
+ document_details: None,
}),
connector_transfer_method_id,
webhook_url: Some(webhook_url),
@@ -257,6 +258,7 @@ pub async fn construct_payout_router_data<'a, F>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -433,6 +435,7 @@ pub async fn construct_refund_router_data<'a, F>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
@@ -625,6 +628,10 @@ pub async fn construct_refund_router_data<'a, F>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
@@ -1070,6 +1077,10 @@ pub async fn construct_accept_dispute_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
@@ -1176,6 +1187,10 @@ pub async fn construct_submit_evidence_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
@@ -1291,6 +1306,7 @@ pub async fn construct_upload_file_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
}
@@ -1367,6 +1383,7 @@ pub async fn construct_dispute_list_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
})
}
@@ -1475,6 +1492,10 @@ pub async fn construct_dispute_sync_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
@@ -1606,6 +1627,10 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
@@ -1715,6 +1740,10 @@ pub async fn construct_defend_dispute_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: payment_intent
+ .get_customer_document_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract customer document details from payment_intent")?,
};
Ok(router_data)
}
@@ -1817,6 +1846,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
}
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 81655b4c52..18670b286c 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -146,6 +146,7 @@ pub async fn construct_webhook_router_data(
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
};
Ok(router_data)
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 301d7298e3..4845ecf369 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -1409,6 +1409,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)
l2_l3_data: data.l2_l3_data.clone(),
minor_amount_capturable: data.minor_amount_capturable,
authorized_amount: data.authorized_amount,
+ customer_document_details: data.customer_document_details.clone(),
}
}
}
@@ -1482,6 +1483,7 @@ impl<F1, F2>
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
}
}
}
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 6d7e2430b9..d8271c33d0 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -1,18 +1,17 @@
use api_models::customers;
pub use api_models::customers::{
- CustomerDeleteResponse, CustomerListRequest, CustomerListRequestWithConstraints,
- CustomerListResponse, CustomerRequest, CustomerUpdateRequest, CustomerUpdateRequestInternal,
+ CustomerDeleteResponse, CustomerDocumentDetails, CustomerListRequest,
+ CustomerListRequestWithConstraints, CustomerListResponse, CustomerRequest,
+ CustomerUpdateRequest, CustomerUpdateRequestInternal,
};
+use common_utils::ext_traits::ValueExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::customer;
use serde::Serialize;
#[cfg(feature = "v1")]
use super::payments;
-use crate::{
- newtype,
- types::{domain, ForeignFrom},
-};
+use crate::{newtype, types::domain};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
@@ -26,9 +25,26 @@ impl common_utils::events::ApiEventMetric for CustomerResponse {
}
#[cfg(feature = "v1")]
-impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
- fn foreign_from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
- customers::CustomerResponse {
+impl TryFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
+ type Error = error_stack::Report<common_utils::errors::ParsingError>;
+ fn try_from(
+ (cust, address): (domain::Customer, Option<payments::AddressDetails>),
+ ) -> Result<Self, Self::Error> {
+ let document_details = cust
+ .document_details
+ .as_ref()
+ .map(|encryptable| {
+ encryptable
+ .clone()
+ .into_inner()
+ .parse_value::<CustomerDocumentDetails>("CustomerDocumentDetails")
+ .map_err(|err| {
+ router_env::logger::error!(?err, "Failed to parse CustomerDocumentDetails");
+ err
+ })
+ })
+ .transpose()?;
+ Ok(Self(customers::CustomerResponse {
customer_id: cust.customer_id,
name: cust.name,
email: cust.email,
@@ -40,15 +56,30 @@ impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for Custo
address,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
- }
- .into()
+ document_details,
+ }))
}
}
#[cfg(feature = "v2")]
-impl ForeignFrom<customer::Customer> for CustomerResponse {
- fn foreign_from(cust: domain::Customer) -> Self {
- customers::CustomerResponse {
+impl TryFrom<customer::Customer> for CustomerResponse {
+ type Error = error_stack::Report<common_utils::errors::ParsingError>;
+ fn try_from(cust: customer::Customer) -> Result<Self, Self::Error> {
+ let document_details = cust
+ .document_details
+ .as_ref()
+ .map(|encryptable| {
+ encryptable
+ .clone()
+ .into_inner()
+ .parse_value::<CustomerDocumentDetails>("CustomerDocumentDetails")
+ .map_err(|err| {
+ router_env::logger::error!(?err, "Failed to parse CustomerDocumentDetails");
+ err
+ })
+ })
+ .transpose()?;
+ Ok(Self(customers::CustomerResponse {
id: cust.id,
merchant_reference_id: cust.merchant_reference_id,
connector_customer_ids: cust.connector_customer,
@@ -63,7 +94,7 @@ impl ForeignFrom<customer::Customer> for CustomerResponse {
default_shipping_address: None,
default_payment_method_id: cust.default_payment_method_id,
tax_registration_id: cust.tax_registration_id,
- }
- .into()
+ document_details,
+ }))
}
}
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 48d967601d..0790ec183e 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -143,6 +143,7 @@ impl VerifyConnectorData {
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
}
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 97475f8c6d..281aaf5428 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1926,6 +1926,11 @@ impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse {
.as_ref()
.map(|phone| phone.get_inner().to_owned()),
phone_country_code: customer.phone_country_code.clone(),
+ customer_document_details: customer
+ .document_details
+ .clone()
+ .map(|encryptable| encryptable.into_inner())
+ .and_then(|secret_value| secret_value.parse_value("CustomerDocumentDetails").ok()),
}
}
}
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 283024e271..a7d7c9d360 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -473,6 +473,7 @@ pub trait ConnectorActions: Connector {
phone: Some(Secret::new("620874518".to_string())),
phone_country_code: Some("+31".to_string()),
tax_registration_id: Some("1232343243".to_string().into()),
+ document_details: None,
}),
vendor_details: None,
priority: None,
@@ -567,6 +568,7 @@ pub trait ConnectorActions: Connector {
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
+ customer_document_details: None,
}
}
diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs
index c5941f8e93..e76baff0ec 100644
--- a/crates/storage_impl/src/customers.rs
+++ b/crates/storage_impl/src/customers.rs
@@ -184,10 +184,10 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
),
updated_customer,
kv_router_store::UpdateResourceParams {
- updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
+ updateable: kv::Updateable::CustomerUpdate(Box::new(kv::CustomerUpdateMems {
orig: customer.clone(),
update_data: customer_update.clone().into(),
- }),
+ })),
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
@@ -450,10 +450,10 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt
diesel_models::CustomerUpdateInternal::from(customer_update.clone())
.apply_changeset(customer.clone()),
kv_router_store::UpdateResourceParams {
- updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
+ updateable: kv::Updateable::CustomerUpdate(Box::new(kv::CustomerUpdateMems {
orig: customer.clone(),
update_data: customer_update.into(),
- }),
+ })),
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
diff --git a/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/down.sql b/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/down.sql
new file mode 100644
index 0000000000..992dd4f182
--- /dev/null
+++ b/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE customers
+DROP COLUMN IF EXISTS document_details;
\ No newline at end of file
diff --git a/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/up.sql b/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/up.sql
new file mode 100644
index 0000000000..4a7f010887
--- /dev/null
+++ b/migrations/2025-12-15-101025-0000_add_document_number_in_customer_table/up.sql
@@ -0,0 +1,4 @@
+-- Your SQL goes here
+ALTER TABLE customers
+ADD COLUMN
+IF NOT EXISTS document_details BYTEA DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/down.sql b/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/down.sql
new file mode 100644
index 0000000000..c8e89b3215
--- /dev/null
+++ b/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS customer_details;
\ No newline at end of file
diff --git a/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/up.sql b/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/up.sql
new file mode 100644
index 0000000000..b91cc54e37
--- /dev/null
+++ b/migrations/2025-12-16-101412-0000_add_payment_method_customer_details_to_payment_methods_table/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS customer_details BYTEA DEFAULT NULL;
\ No newline at end of file