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(payment-methods): add modular payment method create api (#11031)

Prasunna Soppaa2de0e4f8360
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index c8ada7e610..ebb2fbc6ca 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1547,7 +1547,6 @@ pub struct CardDetailFromLocker {
pub saved_to_locker: bool,
}
-#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct NetworkTokenResponse {
pub payment_method_data: NetworkTokenDetailsPaymentMethod,
diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rs
index ddb5d69bfc..69ededbb7a 100644
--- a/crates/common_utils/src/id_type/organization.rs
+++ b/crates/common_utils/src/id_type/organization.rs
@@ -26,4 +26,9 @@ impl OrganizationId {
pub fn get_threeds_routing_region_uas_key(&self) -> String {
format!("threeds_routing_region_uas_{}", self.get_string_repr())
}
+
+ /// Get should call PM modular service key for payment
+ pub fn get_should_call_pm_modular_service_key(&self) -> String {
+ format!("should_call_pm_modular_service_{}", self.get_string_repr())
+ }
}
diff --git a/crates/payment_methods/src/client.rs b/crates/payment_methods/src/client.rs
index aa9bb7e243..32114d0879 100644
--- a/crates/payment_methods/src/client.rs
+++ b/crates/payment_methods/src/client.rs
@@ -1,6 +1,7 @@
//! Payment method microservice flows and lightweight client context.
/// Create payment method flow.
+#[cfg(feature = "v1")]
pub mod create;
/// Delete payment method flow.
pub mod delete;
@@ -11,6 +12,7 @@ pub mod retrieve;
pub mod update;
use common_utils::request::Headers;
+#[cfg(feature = "v1")]
pub use create::{CreatePaymentMethod, CreatePaymentMethodV1Request};
pub use delete::{DeletePaymentMethod, DeletePaymentMethodV1Request};
use hyperswitch_interfaces::micro_service::MicroserviceClient;
diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rs
index ce321deefa..58da1b5dbb 100644
--- a/crates/payment_methods/src/client/create.rs
+++ b/crates/payment_methods/src/client/create.rs
@@ -1,72 +1,195 @@
//! Create payment method flow types and dummy models.
-use common_utils::request::{Method, RequestContent};
-use hyperswitch_interfaces::micro_service::MicroserviceClientError;
-use serde::Deserialize;
-use serde_json::Value;
-
+use api_models::payments;
+use cards::CardNumber;
+use common_utils::{
+ id_type, pii,
+ request::{Method, RequestContent},
+ types::MinorUnit,
+};
+use hyperswitch_domain_models::payment_method_data::PaymentMethodData;
+use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
/// V1-facing create flow type.
#[derive(Debug)]
pub struct CreatePaymentMethod;
-/// V1-facing create request payload.
#[derive(Debug)]
pub struct CreatePaymentMethodV1Request {
- /// Raw payload forwarded to the modular service.
- pub payload: Value,
+ pub merchant_id: id_type::MerchantId,
+ pub payment_method: common_enums::PaymentMethod,
+ pub payment_method_type: common_enums::PaymentMethodType,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub customer_id: id_type::CustomerId, // Payment method data will be saved when customer acceptance is given, hence customer id will always be present
+ pub payment_method_data: PaymentMethodData,
+ pub billing: Option<payments::Address>,
+ pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
+ pub storage_type: Option<common_enums::StorageType>,
}
-const DUMMY_PM_ID: &str = "pm_dummy";
-/// Dummy modular service request payload.
-#[derive(Clone, Debug)]
-// TODO: replace dummy request types with real v1/modular models.
-pub struct CreatePaymentMethodV2Request {
- /// Payload to send in the request body.
- pub payload: Value,
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ModularPMCreateRequest {
+ pub payment_method_type: common_enums::PaymentMethod,
+ pub payment_method_subtype: common_enums::PaymentMethodType,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub customer_id: id_type::CustomerId, // Payment method data will be saved when customer acceptance is given, hence customer id will always be present
+ pub payment_method_data: PaymentMethodCreateData,
+ pub billing: Option<payments::Address>,
+ pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
+ pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
+ pub storage_type: Option<common_enums::StorageType>,
+}
+
+//This struct will be deprecated when we fully migrate to Modular PMs
+//cannot reuse CardDetail since CardDetail under v2 does not have card_issuing_country code.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CardDetail {
+ pub card_number: CardNumber,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub card_holder_name: Option<Secret<String>>,
+ pub nick_name: Option<Secret<String>>,
+ pub card_issuing_country: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_issuer: Option<String>,
+ pub card_type: Option<common_enums::CardType>,
+ pub card_cvc: Option<Secret<String>>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentMethodCreateData {
+ Card(CardDetail),
}
-/// Dummy modular service response payload.
#[derive(Clone, Debug, Deserialize)]
-// TODO: replace dummy response types with real v1/modular models.
-pub struct CreatePaymentMethodV2Response {
- /// Dummy identifier returned by the modular service.
+pub struct ModularPMCreateResponse {
+ //payment method id
pub id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub customer_id: Option<id_type::CustomerId>,
+ pub payment_method_type: Option<common_enums::PaymentMethod>,
+ pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
+ pub recurring_enabled: Option<bool>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub created: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<PrimitiveDateTime>,
+ pub payment_method_data: Option<PaymentMethodResponseData>,
+ pub connector_tokens: Option<Vec<ConnectorTokenDetails>>,
+ pub network_token: Option<api_models::payment_methods::NetworkTokenResponse>,
+ pub storage_type: Option<common_enums::StorageType>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentMethodResponseData {
+ Card(api_models::payment_methods::CardDetailFromLocker),
}
-/// V1-facing create response (dummy for now).
#[derive(Clone, Debug)]
-// TODO: replace dummy response types with real v1/modular models.
pub struct CreatePaymentMethodResponse {
- /// V1 payment method identifier.
+ //payment method id
pub payment_method_id: String,
- /// Dummy delete marker (unused).
- pub deleted: Option<bool>,
+ pub merchant_id: id_type::MerchantId,
+ pub customer_id: Option<id_type::CustomerId>,
+ pub payment_method_type: Option<common_enums::PaymentMethod>,
+ pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
+ pub recurring_enabled: Option<bool>,
+ pub created: Option<PrimitiveDateTime>,
+ pub last_used_at: Option<PrimitiveDateTime>,
+ pub payment_method_data: Option<PaymentMethodResponseData>,
+ pub connector_tokens: Option<Vec<ConnectorTokenDetails>>,
+ pub network_token: Option<api_models::payment_methods::NetworkTokenResponse>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConnectorTokenDetails {
+ pub connector_id: id_type::MerchantConnectorAccountId,
+ pub token_type: common_enums::TokenizationType,
+ pub status: common_enums::ConnectorTokenStatus,
+ pub connector_token_request_reference_id: Option<String>,
+ pub original_payment_authorized_amount: Option<MinorUnit>,
+ pub original_payment_authorized_currency: Option<common_enums::Currency>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub token: Secret<String>,
+}
+
+impl TryFrom<PaymentMethodData> for PaymentMethodCreateData {
+ type Error = MicroserviceClientError;
+
+ fn try_from(value: PaymentMethodData) -> Result<Self, Self::Error> {
+ match value {
+ PaymentMethodData::Card(card) => {
+ let card_detail = CardDetail {
+ card_number: card.card_number,
+ card_exp_month: card.card_exp_month,
+ card_exp_year: card.card_exp_year,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_issuing_country: card.card_issuing_country,
+ card_network: card.card_network,
+ card_issuer: card.card_issuer,
+ card_type: None,
+ card_cvc: Some(card.card_cvc),
+ };
+ Ok(Self::Card(card_detail))
+ }
+ _ => Err(MicroserviceClientError {
+ operation: "CreatePaymentMethodV1Request to ModularPMCreateRequest".to_string(),
+ kind: MicroserviceClientErrorKind::InvalidRequest(
+ "Unsupported payment method type for modular PM creation".to_string(),
+ ),
+ }),
+ }
+ }
}
-impl TryFrom<&CreatePaymentMethodV1Request> for CreatePaymentMethodV2Request {
+impl TryFrom<&CreatePaymentMethodV1Request> for ModularPMCreateRequest {
type Error = MicroserviceClientError;
- fn try_from(value: &CreatePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ fn try_from(request: &CreatePaymentMethodV1Request) -> Result<Self, Self::Error> {
+ let payment_method_data =
+ PaymentMethodCreateData::try_from(request.payment_method_data.clone())?;
Ok(Self {
- payload: value.payload.clone(),
+ payment_method_type: request.payment_method,
+ payment_method_subtype: request.payment_method_type,
+ metadata: request.metadata.clone(),
+ customer_id: request.customer_id.clone(),
+ payment_method_data,
+ billing: request.billing.clone(),
+ psp_tokenization: None,
+ network_tokenization: request.network_tokenization.clone(),
+ storage_type: request.storage_type,
})
}
}
-impl TryFrom<CreatePaymentMethodV2Response> for CreatePaymentMethodResponse {
+impl TryFrom<ModularPMCreateResponse> for CreatePaymentMethodResponse {
type Error = MicroserviceClientError;
- fn try_from(_: CreatePaymentMethodV2Response) -> Result<Self, Self::Error> {
+ fn try_from(response: ModularPMCreateResponse) -> Result<Self, Self::Error> {
Ok(Self {
- payment_method_id: DUMMY_PM_ID.to_string(),
- deleted: None,
+ payment_method_id: response.id,
+ merchant_id: response.merchant_id,
+ customer_id: response.customer_id,
+ payment_method_type: response.payment_method_type,
+ payment_method_subtype: response.payment_method_subtype,
+ recurring_enabled: response.recurring_enabled,
+ created: response.created,
+ last_used_at: response.last_used_at,
+ payment_method_data: response.payment_method_data,
+ connector_tokens: response.connector_tokens,
+ network_token: response.network_token,
})
}
}
impl CreatePaymentMethod {
- fn build_body(&self, request: CreatePaymentMethodV2Request) -> Option<RequestContent> {
- Some(RequestContent::Json(Box::new(request.payload)))
+ fn build_body(&self, request: ModularPMCreateRequest) -> Option<RequestContent> {
+ Some(RequestContent::Json(Box::new(request)))
}
}
@@ -75,8 +198,8 @@ hyperswitch_interfaces::impl_microservice_flow!(
method = Method::Post,
path = "/v2/payment-methods",
v1_request = CreatePaymentMethodV1Request,
- v2_request = CreatePaymentMethodV2Request,
- v2_response = CreatePaymentMethodV2Response,
+ v2_request = ModularPMCreateRequest,
+ v2_response = ModularPMCreateResponse,
v1_response = CreatePaymentMethodResponse,
client = crate::client::PaymentMethodClient<'_>,
body = CreatePaymentMethod::build_body
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs
index f82dbb2c45..dab25670ea 100644
--- a/crates/router/src/core/payment_methods/utils.rs
+++ b/crates/router/src/core/payment_methods/utils.rs
@@ -833,6 +833,25 @@ pub async fn get_merchant_config_for_eligibility_check(
}
}
+pub async fn get_organization_eligibility_config_for_pm_modular_service(
+ db: &dyn StorageInterface,
+ organization_id: &common_utils::id_type::OrganizationId,
+) -> bool {
+ let config = db
+ .find_config_by_key_unwrap_or(
+ &organization_id.get_should_call_pm_modular_service_key(),
+ Some("false".to_string()),
+ )
+ .await;
+ match config {
+ Ok(conf) => conf.config == "true",
+ Err(error) => {
+ logger::error!(?error);
+ false
+ }
+ }
+}
+
pub async fn get_sdk_next_action_for_payment_method_list(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,