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): implement v2 default payment method set functionality (#12371)

Gaurav Rawatc657289862bf
diff --git a/api-reference/docs.json b/api-reference/docs.json
index 856a164176..63c5d79631 100644
--- a/api-reference/docs.json
+++ b/api-reference/docs.json
@@ -65,7 +65,8 @@
"v2/payment-methods/payment-method--update-v1",
"v2/payment-methods/payment-method--delete-v1",
"v2/payment-methods/payment-method--list-customer-saved-payment-methods-v1",
- "v2/payment-methods/payment-method--payment-method-token-to-payment-method-id-v1"
+ "v2/payment-methods/payment-method--payment-method-token-to-payment-method-id-v1",
+ "v2/payment-methods/payment-method--set-default-payment-method-for-customer-v1"
]
},
{
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 472f966f27..714d32a4d5 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -3747,6 +3747,59 @@
]
}
},
+ "/v1/{customer_id}/payment-methods/{payment_method_id}/default": {
+ "post": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Set Default Payment Method for Customer",
+ "description": "Set the Payment Method as Default for the Customer.",
+ "operationId": "Set the Payment Method as Default",
+ "parameters": [
+ {
+ "name": "customer_id",
+ "in": "path",
+ "description": "The unique identifier for the Customer",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "payment_method_id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Method",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method has been set as default",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomerDefaultPaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Payment Method has already been set as default for that customer"
+ },
+ "404": {
+ "description": "Payment Method not found for the customer"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/payment-method-sessions": {
"post": {
"tags": [
@@ -12516,6 +12569,39 @@
},
"additionalProperties": false
},
+ "CustomerDefaultPaymentMethodResponse": {
+ "type": "object",
+ "required": [
+ "default_payment_method_id",
+ "customer_id",
+ "payment_method_type"
+ ],
+ "properties": {
+ "default_payment_method_id": {
+ "type": "string",
+ "description": "The unique identifier of the Payment method",
+ "example": "card_rGK4Vi5iSW70MY7J2mIg"
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
+ "maxLength": 64,
+ "minLength": 1
+ },
+ "payment_method_type": {
+ "$ref": "#/components/schemas/PaymentMethod"
+ },
+ "payment_method_subtype": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"CustomerDeleteResponse": {
"type": "object",
"required": [
diff --git a/api-reference/v2/payment-methods/payment-method--set-default-payment-method-for-customer-v1.mdx b/api-reference/v2/payment-methods/payment-method--set-default-payment-method-for-customer-v1.mdx
new file mode 100644
index 0000000000..9dbaa37c18
--- /dev/null
+++ b/api-reference/v2/payment-methods/payment-method--set-default-payment-method-for-customer-v1.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v1/{customer_id}/payment-methods/{payment_method_id}/default
+---
\ No newline at end of file
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 955e8fc84c..b17e6d1a0f 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -1,4 +1,6 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
+#[cfg(feature = "v2")]
+use common_utils::id_type::GlobalPaymentMethodId;
#[cfg(feature = "v2")]
use super::{
@@ -378,7 +380,16 @@ impl ApiEventMetric for payment_methods::DefaultPaymentMethod {
})
}
}
-
+#[cfg(feature = "v2")]
+impl ApiEventMetric for payment_methods::DefaultPaymentMethod {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: GlobalPaymentMethodId::new_unchecked(self.payment_method_id.clone()),
+ payment_method_type: None,
+ payment_method_subtype: None,
+ })
+ }
+}
#[cfg(feature = "v2")]
impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -450,6 +461,19 @@ impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse {
}
}
+#[cfg(feature = "v2")]
+impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ self.default_payment_method_id
+ .as_ref()
+ .map(|id| ApiEventsType::PaymentMethod {
+ payment_method_id: id.clone(),
+ payment_method_type: Some(self.payment_method_type),
+ payment_method_subtype: self.payment_method_subtype,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentMethodCollectLinkRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.pm_collect_link_id
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7862f5e6ed..90b4809200 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -3351,6 +3351,23 @@ pub struct CustomerDefaultPaymentMethodResponse {
pub payment_method_type: Option<api_enums::PaymentMethodType>,
}
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CustomerDefaultPaymentMethodResponse {
+ /// The unique identifier of the Payment method
+ #[schema(value_type = String, example = "card_rGK4Vi5iSW70MY7J2mIg")]
+ pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
+ /// The unique identifier of the customer.
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: id_type::GlobalCustomerId,
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method_type: api_enums::PaymentMethod,
+ /// This is a sub-category of payment method.
+ #[schema(value_type = Option<PaymentMethodType>,example = "credit")]
+ pub payment_method_subtype: Option<api_enums::PaymentMethodType>,
+}
+
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponseItem {
@@ -3687,6 +3704,14 @@ pub struct DefaultPaymentMethod {
pub payment_method_id: String,
}
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+pub struct DefaultPaymentMethod {
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")]
+ pub customer_id: String,
+ pub payment_method_id: String,
+}
+
//------------------------------------------------TokenizeService------------------------------------------------
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizePayloadEncrypted {
diff --git a/crates/common_utils/src/id_type/global_id/customer.rs b/crates/common_utils/src/id_type/global_id/customer.rs
index 82e328fa5c..63dbaa72e4 100644
--- a/crates/common_utils/src/id_type/global_id/customer.rs
+++ b/crates/common_utils/src/id_type/global_id/customer.rs
@@ -1,13 +1,13 @@
use crate::errors;
-crate::global_id_type!(
- GlobalCustomerId,
- "A global id that can be used to identify a customer.
-
-The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
-
-Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
-);
+/// A global id that can be used to identify a customer.
+///
+/// The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
+///
+/// Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`
+#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, diesel::expression::AsExpression)]
+#[diesel(sql_type = diesel::sql_types::Text)]
+pub struct GlobalCustomerId(super::GlobalId);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalCustomerId);
@@ -61,6 +61,16 @@ impl GlobalCustomerId {
}
}
+impl<'de> serde::Deserialize<'de> for GlobalCustomerId {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let deserialized_string = String::deserialize(deserializer)?;
+ Ok(Self::new_unchecked(deserialized_string))
+ }
+}
+
impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId {
type Error = error_stack::Report<errors::ValidationError>;
diff --git a/crates/common_utils/src/id_type/global_id/payment_methods.rs b/crates/common_utils/src/id_type/global_id/payment_methods.rs
index 550e279c59..2133b8a1b1 100644
--- a/crates/common_utils/src/id_type/global_id/payment_methods.rs
+++ b/crates/common_utils/src/id_type/global_id/payment_methods.rs
@@ -6,16 +6,7 @@ use crate::{
};
/// A global id that can be used to identify a payment method
-#[derive(
- Debug,
- Clone,
- Hash,
- PartialEq,
- Eq,
- serde::Serialize,
- serde::Deserialize,
- diesel::expression::AsExpression,
-)]
+#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, diesel::expression::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalPaymentMethodId(GlobalId);
@@ -94,9 +85,9 @@ impl crate::events::ApiEventMetric for GlobalPaymentMethodId {
impl GlobalPaymentMethodId {
/// Create a new GlobalPaymentMethodId from cell id information
- pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> {
+ pub fn generate(cell_id: &CellId) -> Self {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
- Ok(Self(global_id))
+ Self(global_id)
}
/// Get string representation of the id
@@ -105,10 +96,8 @@ impl GlobalPaymentMethodId {
}
/// Construct a new GlobalPaymentMethodId from a string
- pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
- let id = GlobalId::from_string(value.into())
- .change_context(GlobalPaymentMethodIdError::ConstructionError)?;
- Ok(Self(id))
+ pub fn generate_from_string(value: String) -> Self {
+ Self::new_unchecked(value)
}
/// Create a new GlobalPaymentMethodId without validation
@@ -121,6 +110,16 @@ impl GlobalPaymentMethodId {
}
}
+impl<'de> serde::Deserialize<'de> for GlobalPaymentMethodId {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let deserialized_string = String::deserialize(deserializer)?;
+ Ok(Self::new_unchecked(deserialized_string))
+ }
+}
+
impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index c820672d38..3e7d5143ff 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -153,6 +153,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payment_method::list_customer_payment_method_api_v1,
routes::payment_method::payment_method_get_token_details_api,
routes::payment_method::payment_method_get_token_details_api_v1,
+ routes::payment_method::default_payment_method_set_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
@@ -706,6 +707,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::payment_methods::CardCVCTokenStorageDetails,
api_models::payment_methods::PaymentMethodDeleteSessionResponse,
+ api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::AmountFilter,
diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs
index 9656e34ab1..250839a992 100644
--- a/crates/openapi/src/routes/payment_method.rs
+++ b/crates/openapi/src/routes/payment_method.rs
@@ -199,6 +199,29 @@ pub async fn payment_method_delete_api() {}
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
+#[cfg(feature = "v1")]
+pub async fn default_payment_method_set_api() {}
+
+/// Payment Method - Set Default Payment Method for Customer
+///
+/// Set the Payment Method as Default for the Customer.
+#[utoipa::path(
+ post,
+ path = "/v1/{customer_id}/payment-methods/{payment_method_id}/default",
+ params (
+ ("customer_id" = String,Path, description ="The unique identifier for the Customer"),
+ ("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
+ (status = 400, description = "Payment Method has already been set as default for that customer"),
+ (status = 404, description = "Payment Method not found for the customer")
+ ),
+ tag = "Payment Methods",
+ operation_id = "Set the Payment Method as Default",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs
index 89474a6a28..07f57fc09b 100644
--- a/crates/payment_methods/src/controller.rs
+++ b/crates/payment_methods/src/controller.rs
@@ -276,6 +276,15 @@ pub trait PaymentMethodsController {
initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>;
+ #[cfg(feature = "v2")]
+ async fn set_default_payment_method(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::GlobalCustomerId,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+ ) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>;
+
#[cfg(feature = "v1")]
async fn add_payment_method_status_update_task(
&self,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 7decfb09fc..505539b02f 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1351,9 +1351,7 @@ pub async fn create_persistent_payment_method_core(
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
- id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+ id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id);
match &req.payment_method_data {
api::PaymentMethodCreateData::Card(_) | api::PaymentMethodCreateData::BankDebit(_) => {
@@ -1464,9 +1462,7 @@ pub async fn create_volatile_payment_method_core(
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
- id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+ id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id);
match &req.payment_method_data {
api::PaymentMethodCreateData::Card(_) | api::PaymentMethodCreateData::BankDebit(_) => {
@@ -3481,9 +3477,7 @@ pub async fn payment_method_intent_create(
// create pm entry
let payment_method_id =
- id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+ id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id);
let payment_method = create_payment_method_for_intent(
state,
@@ -4996,9 +4990,26 @@ pub async fn list_payment_methods_core(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let customer = db
+ .find_customer_by_global_id_merchant_id(
+ customer_id,
+ provider.get_account().get_id(),
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let default_payment_method_id = customer.default_payment_method_id;
+
let customer_payment_methods = saved_payment_methods
.into_iter()
- .map(ForeignTryFrom::foreign_try_from)
+ .map(|pm| {
+ payment_methods::PaymentMethodResponseItem::foreign_try_from((
+ pm,
+ default_payment_method_id.clone(),
+ ))
+ })
.collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -5037,45 +5048,62 @@ pub async fn list_customer_payment_methods_core(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let customer = db
+ .find_customer_by_global_id_merchant_id(
+ customer_id,
+ provider.get_account().get_id(),
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let default_payment_method_id = customer.default_payment_method_id;
+
let mut customer_payment_methods = Vec::new();
let payment_method_results: Result<Vec<_>, error_stack::Report<errors::ApiErrorResponse>> =
saved_payment_methods
.into_iter()
- .map(|pm| async move {
- let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
+ .map(|pm| {
+ let default_payment_method_id = default_payment_method_id.clone();
+ async move {
+ let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
- // For payment methods that are active we should always have the payment method type
- let payment_method_type = pm
- .payment_method_type
- .get_required_value("payment_method_type")?;
+ // For payment methods that are active we should always have the payment method type
+ let payment_method_type = pm
+ .payment_method_type
+ .get_required_value("payment_method_type")?;
- let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
-
- let token_data = get_pm_list_token_data(
- payment_method_type,
- &pm,
- // storage type is hardcoded to Persistent as we are fetching saved payment methods from the database
- enums::StorageType::Persistent,
- )?;
+ let intent_fulfillment_time =
+ common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
- if let Some(token_data) = token_data {
- pm_routes::ParentPaymentMethodToken::create_key_for_token(
- &parent_payment_method_token,
- )
- .insert(intent_fulfillment_time, token_data, state)
- .await?;
+ let token_data = get_pm_list_token_data(
+ payment_method_type,
+ &pm,
+ // storage type is hardcoded to Persistent as we are fetching saved payment methods from the database
+ enums::StorageType::Persistent,
+ )?;
- let final_pm = api::CustomerPaymentMethodResponseItem::foreign_try_from((
- pm,
- parent_payment_method_token,
- ))
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to convert payment method to response format")?;
+ if let Some(token_data) = token_data {
+ pm_routes::ParentPaymentMethodToken::create_key_for_token(
+ &parent_payment_method_token,
+ )
+ .insert(intent_fulfillment_time, token_data, state)
+ .await?;
+
+ let final_pm = api::CustomerPaymentMethodResponseItem::foreign_try_from((
+ pm,
+ parent_payment_method_token,
+ default_payment_method_id,
+ ))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert payment method to response format")?;
- Ok(Some(final_pm))
- } else {
- Ok(None)
+ Ok(Some(final_pm))
+ } else {
+ Ok(None)
+ }
}
})
.collect::<futures::stream::FuturesUnordered<_>>()
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 799c568109..b1c11a5054 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -50,9 +50,7 @@ use euclid::{
frontend::dir,
};
use hyperswitch_constraint_graph as cgraph;
-#[cfg(feature = "v1")]
-use hyperswitch_domain_models::customer::CustomerUpdate;
-use hyperswitch_domain_models::mandates::CommonMandateReference;
+use hyperswitch_domain_models::{customer::CustomerUpdate, mandates::CommonMandateReference};
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use hyperswitch_masking::Secret;
#[cfg(feature = "v1")]
@@ -1251,6 +1249,106 @@ impl PaymentMethodsController for PmCards<'_> {
Ok(services::ApplicationResponse::Json(resp))
}
+ #[cfg(feature = "v2")]
+ async fn set_default_payment_method(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ customer_id: &id_type::GlobalCustomerId,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ initiator: Option<&domain::Initiator>,
+ ) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>
+ {
+ let db = &*self.state.store;
+ // check for the customer
+ // TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value
+ let customer = db
+ .find_customer_by_global_id_merchant_id(
+ customer_id,
+ merchant_id,
+ self.provider.get_key_store(),
+ self.provider.get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ // check for the presence of payment_method
+ let payment_method = db
+ .find_payment_method(
+ self.provider.get_key_store(),
+ payment_method_id,
+ self.provider.get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let pm = payment_method
+ .get_payment_method_type()
+ .get_required_value("payment_method")?;
+
+ let pm_customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")?;
+
+ utils::when(
+ &pm_customer_id != customer_id || payment_method.merchant_id != *merchant_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "The payment_method_id is not valid".to_string(),
+ })
+ },
+ )?;
+
+ utils::when(
+ payment_method.status != common_enums::PaymentMethodStatus::Active,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "The payment_method is not active".to_string(),
+ })
+ },
+ )?;
+
+ utils::when(
+ Some(payment_method_id.clone()) == customer.default_payment_method_id,
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Payment Method is already set as default".to_string(),
+ })
+ },
+ )?;
+
+ let customer_id = customer.id.clone();
+
+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id: Some(Some(payment_method_id.to_owned())),
+ last_modified_by: initiator
+ .and_then(|initiator| initiator.to_created_by())
+ .map(|last_modified_by| last_modified_by.to_string()),
+ };
+ // update the db with the default payment method id
+
+ let updated_customer_details = db
+ .update_customer_by_global_id(
+ &customer_id,
+ customer,
+ customer_update,
+ self.provider.get_key_store(),
+ self.provider.get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the default payment method id for the customer")?;
+
+ let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {
+ default_payment_method_id: updated_customer_details.default_payment_method_id,
+ customer_id,
+ payment_method_subtype: payment_method.get_payment_method_subtype(),
+ payment_method_type: pm,
+ };
+
+ Ok(services::ApplicationResponse::Json(resp))
+ }
+
#[cfg(feature = "v1")]
async fn add_payment_method_status_update_task(
&self,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 7ed10747dd..f435eb9acb 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -955,13 +955,21 @@ pub fn mk_card_value2(
}
#[cfg(feature = "v2")]
-impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
- for api::CustomerPaymentMethodResponseItem
+impl
+ transformers::ForeignTryFrom<(
+ domain::PaymentMethod,
+ String,
+ Option<id_type::GlobalPaymentMethodId>,
+ )> for api::CustomerPaymentMethodResponseItem
{
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(
- (item, payment_token): (domain::PaymentMethod, String),
+ (item, payment_token, default_payment_method_id): (
+ domain::PaymentMethod,
+ String,
+ Option<id_type::GlobalPaymentMethodId>,
+ ),
) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
@@ -1029,6 +1037,9 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
// TODO: check how we can get this field
let recurring_enabled = true;
+ let is_default = default_payment_method_id.is_some()
+ && default_payment_method_id == Some(item.id.clone());
+
Ok(Self {
customer_id: item
.customer_id
@@ -1044,7 +1055,7 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
payment_method_data,
bank: None,
requires_cvv: true,
- is_default: false,
+ is_default,
billing: payment_method_billing,
payment_method_token: payment_token,
})
@@ -1052,10 +1063,20 @@ impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
}
#[cfg(feature = "v2")]
-impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponseItem {
+impl
+ transformers::ForeignTryFrom<(
+ domain::PaymentMethod,
+ Option<id_type::GlobalPaymentMethodId>,
+ )> for PaymentMethodResponseItem
+{
type Error = error_stack::Report<errors::ValidationError>;
- fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> {
+ fn foreign_try_from(
+ (item, default_payment_method_id): (
+ domain::PaymentMethod,
+ Option<id_type::GlobalPaymentMethodId>,
+ ),
+ ) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
@@ -1146,6 +1167,9 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodRespon
})
});
+ let is_default = default_payment_method_id.is_some()
+ && default_payment_method_id == Some(item.id.clone());
+
Ok(Self {
id: item.id,
customer_id: item
@@ -1162,7 +1186,7 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodRespon
payment_method_data,
bank: None,
requires_cvv: true,
- is_default: false,
+ is_default,
billing: payment_method_billing,
network_tokenization: network_token_resp,
psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 48e1946110..3ac655b053 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -2384,7 +2384,9 @@ impl PaymentConfirm {
logger::info!("Payment method fetched from PM Modular Service.");
utils::when(
- pm_info.payment_method.customer_id.as_ref() != req.get_customer_id(),
+ req.get_customer_id().is_some_and(|customer_id| {
+ pm_info.payment_method.customer_id.as_ref() != Some(customer_id)
+ }),
|| {
logger::info!(
"Payment method id does not belong to the customer id provided in the request."
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 32e4682252..f20eac0beb 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1342,7 +1342,9 @@ impl PaymentCreate {
logger::info!("Payment method fetched from PM Modular Service.");
utils::when(
- pm_info.payment_method.customer_id.as_ref() != req.get_customer_id(),
+ req.get_customer_id().is_some_and(|customer_id| {
+ pm_info.payment_method.customer_id.as_ref() != Some(customer_id)
+ }),
|| {
logger::info!(
"Payment method id does not belong to the customer id provided in the request."
diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rs
index 376cbfb690..dcfd02d62c 100644
--- a/crates/router/src/core/proxy/utils.rs
+++ b/crates/router/src/core/proxy/utils.rs
@@ -48,9 +48,7 @@ impl ProxyRequestWrapper {
payment_method_id: token.clone(),
};
let pm_id =
- id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+ id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id);
let payment_method_record = state
.store
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2590b06123..84009c856c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1411,6 +1411,10 @@ impl Customers {
.route(web::get().to(customers::customers_retrieve))
.route(web::delete().to(customers::customers_delete)),
)
+ .service(
+ web::resource("/{customer_id}/payment-methods/{payment_method_id}/default")
+ .route(web::post().to(payment_methods::default_payment_method_set_api)),
+ )
}
route
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index b374e9b43f..80382043c1 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -1343,6 +1343,52 @@ pub async fn default_payment_method_set_api(
.await
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
+pub async fn default_payment_method_set_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<payment_methods::DefaultPaymentMethod>,
+) -> HttpResponse {
+ let flow = Flow::DefaultPaymentMethodsSet;
+ let payload = path.into_inner();
+ let customer_id = id_type::GlobalCustomerId::new_unchecked(payload.customer_id.clone());
+
+ let auth = auth::V2ApiKeyAuth {
+ allow_connected_scope_operation: true,
+ allow_platform_self_operation: true,
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, default_payment_method, _| {
+ let customer_id = customer_id.clone();
+ let payment_method_id = id_type::GlobalPaymentMethodId::new_unchecked(
+ default_payment_method.payment_method_id.clone(),
+ );
+ async move {
+ cards::PmCards {
+ state: &state,
+ provider: auth.platform.get_provider(),
+ }
+ .set_default_payment_method(
+ auth.platform.get_provider().get_account().get_id(),
+ &customer_id,
+ &payment_method_id,
+ auth.platform.get_initiator(),
+ )
+ .await
+ }
+ },
+ &auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index ea0fd6da32..63e5040f0f 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -2,7 +2,7 @@
pub use api_models::payment_methods::{
BankDebitDetailUpdate, CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod,
CardNetworkTokenizeRequest, CardNetworkTokenizeResponse, CardType,
- CustomerPaymentMethodResponseItem, DeleteTokenizeByTokenRequest,
+ CustomerPaymentMethodResponseItem, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
GetNetworkTokenEiligibilityResponse, GetTokenizePayloadRequest, GetTokenizePayloadResponse,
ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod,
NetworkTokenDetailsResponse, NetworkTokenEligibilityRequest, NetworkTokenResponse,
diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
index 16e1ee7fab..bc73005bbd 100644
--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
@@ -420,11 +420,7 @@ pub async fn run_payment_method_modular_backward_compat_backfill(
#[cfg(feature = "v2")]
let payment_method_id = id_type::GlobalPaymentMethodId::generate_from_string(
tracking_data.payment_method_id.clone(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to parse payment method id for modular backward compatibility backfill",
- )?;
+ );
let payment_method = db
.find_payment_method(