Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(router): Add support for updating wallet pm_data to PM update API (#9388)
Anurag Thakur2c3fa825d914
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex d6df74045b..0d207a5a51 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -15488,6 +15488,115 @@}}},+ "CustomerPaymentMethodUpdateResponse": {+ "type": "object",+ "required": [+ "merchant_id",+ "payment_method_id",+ "payment_method"+ ],+ "properties": {+ "merchant_id": {+ "type": "string",+ "description": "Unique identifier for a merchant",+ "example": "merchant_1671528864"+ },+ "customer_id": {+ "type": "string",+ "description": "The unique identifier of the customer.",+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",+ "nullable": true,+ "maxLength": 64,+ "minLength": 1+ },+ "payment_method_id": {+ "type": "string",+ "description": "The unique identifier of the Payment method",+ "example": "card_rGK4Vi5iSW70MY7J2mIg"+ },+ "payment_method": {+ "$ref": "#/components/schemas/PaymentMethod"+ },+ "payment_method_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodType"+ }+ ],+ "nullable": true+ },+ "card": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CardDetailFromLocker"+ }+ ],+ "nullable": true+ },+ "wallet": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodDataWalletInfo"+ }+ ],+ "nullable": true+ },+ "recurring_enabled": {+ "type": "boolean",+ "description": "Indicates whether the payment method supports recurring payments. Optional.",+ "example": true,+ "nullable": true+ },+ "installment_payment_enabled": {+ "type": "boolean",+ "description": "Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.",+ "example": true,+ "nullable": true+ },+ "payment_experience": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PaymentExperience"+ },+ "description": "Type of payment experience enabled with the connector",+ "example": [+ "redirect_to_url"+ ],+ "nullable": true+ },+ "metadata": {+ "type": "object",+ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",+ "nullable": true+ },+ "created": {+ "type": "string",+ "format": "date-time",+ "description": "A timestamp (ISO 8601 code) that determines when the payment method was created",+ "example": "2023-01-18T11:04:09.922Z",+ "nullable": true+ },+ "bank_transfer": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Bank"+ }+ ],+ "nullable": true+ },+ "last_used_at": {+ "type": "string",+ "format": "date-time",+ "example": "2024-02-24T11:04:09.922Z",+ "nullable": true+ },+ "client_secret": {+ "type": "string",+ "description": "For Client based calls",+ "nullable": true+ }+ }+ },"CustomerPaymentMethodsListResponse": {"type": "object","required": [@@ -24127,6 +24236,28 @@}]},+ "PaymentMethodDataWalletInfo": {+ "type": "object",+ "required": [+ "last4",+ "card_network"+ ],+ "properties": {+ "last4": {+ "type": "string",+ "description": "Last 4 digits of the card number"+ },+ "card_network": {+ "type": "string",+ "description": "The information of the payment method"+ },+ "type": {+ "type": "string",+ "description": "The type of payment method",+ "nullable": true+ }+ }+ },"PaymentMethodDeleteResponse": {"type": "object","required": [@@ -24490,6 +24621,14 @@],"nullable": true},+ "wallet": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodDataWalletInfo"+ }+ ],+ "nullable": true+ },"client_secret": {"type": "string","description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK",diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex aa60e8f7fc..0711690621 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -25,7 +25,9 @@ use crate::{};#[cfg(feature = "v1")]use crate::{- payment_methods::{PaymentMethodListRequest, PaymentMethodListResponse},+ payment_methods::{+ CustomerPaymentMethodUpdateResponse, PaymentMethodListRequest, PaymentMethodListResponse,+ },payments::{ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints,PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,@@ -317,6 +319,17 @@ impl ApiEventMetric for PaymentMethodResponse {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for CustomerPaymentMethodUpdateResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::PaymentMethod {+ payment_method_id: self.payment_method_id.clone(),+ payment_method: self.payment_method,+ payment_method_type: self.payment_method_type,+ })+ }+}+impl ApiEventMetric for PaymentMethodMigrateResponse {#[cfg(feature = "v1")]fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex e295687b2a..dcf13dd95f 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -481,6 +481,9 @@ pub struct PaymentMethodUpdate {"card_holder_name": "John Doe"}))]pub card: Option<CardDetailUpdate>,+ /// Wallet Details+ pub wallet: Option<PaymentMethodDataWalletInfo>,+/// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK#[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]pub client_secret: Option<String>,@@ -922,6 +925,70 @@ pub struct PaymentMethodResponse {pub client_secret: Option<String>,}+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct CustomerPaymentMethodUpdateResponse {+ /// Unique identifier for a merchant+ #[schema(example = "merchant_1671528864", value_type = String)]+ pub merchant_id: id_type::MerchantId,++ /// The unique identifier of the customer.+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]+ pub customer_id: Option<id_type::CustomerId>,++ /// The unique identifier of the Payment method+ #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")]+ pub payment_method_id: String,++ /// The type of payment method use for the payment.+ #[schema(value_type = PaymentMethod, example = "card")]+ pub payment_method: Option<api_enums::PaymentMethod>,++ /// This is a sub-category of payment method.+ #[schema(value_type = Option<PaymentMethodType>, example = "credit")]+ pub payment_method_type: Option<api_enums::PaymentMethodType>,++ /// Card details from card locker+ #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))]+ pub card: Option<CardDetailFromLocker>,++ /// Updated Wallet Details+ pub wallet: Option<PaymentMethodDataWalletInfo>,++ /// Indicates whether the payment method supports recurring payments. Optional.+ #[schema(example = true)]+ pub recurring_enabled: Option<bool>,++ /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.+ #[schema(example = true)]+ pub installment_payment_enabled: Option<bool>,++ /// Type of payment experience enabled with the connector+ #[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))]+ pub payment_experience: Option<Vec<api_enums::PaymentExperience>>,++ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.+ #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))]+ pub metadata: Option<pii::SecretSerdeValue>,++ /// A timestamp (ISO 8601 code) that determines when the payment method was created+ #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created: Option<time::PrimitiveDateTime>,++ /// Payment method details from locker+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<Bank>)]+ #[serde(skip_serializing_if = "Option::is_none")]+ pub bank_transfer: Option<payouts::Bank>,++ #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub last_used_at: Option<time::PrimitiveDateTime>,++ /// For Client based calls+ pub client_secret: Option<String>,+}#[cfg(feature = "v2")]#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)]pub struct ConnectorTokenDetails {@@ -1095,7 +1162,7 @@ pub struct PaymentMethodDataBankCreds {pub connector_details: Vec<BankAccountConnectorDetails>,}-#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]pub struct PaymentMethodDataWalletInfo {/// Last 4 digits of the card numberpub last4: String,diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex fbf737a681..daa311cb2a 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -317,11 +317,13 @@ Never share your secret api keys. Keep them guarded and secure.api_models::customers::CustomerDeleteResponse,api_models::payment_methods::PaymentMethodCreate,api_models::payment_methods::PaymentMethodResponse,+ api_models::payment_methods::CustomerPaymentMethodUpdateResponse,api_models::payment_methods::CustomerPaymentMethod,common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,common_types::domain::AcquirerConfigMap,common_types::domain::AcquirerConfig,api_models::payment_methods::PaymentMethodListResponse,+ api_models::payment_methods::PaymentMethodDataWalletInfo,api_models::payment_methods::ResponsePaymentMethodsEnabled,api_models::payment_methods::ResponsePaymentMethodTypes,api_models::payment_methods::PaymentExperienceTypes,diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 635cc39aac..4d60b1d1ce 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -1640,29 +1640,29 @@ pub async fn update_customer_payment_method(merchant_context: domain::MerchantContext,req: api::PaymentMethodUpdate,payment_method_id: &str,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- // Currently update is supported only for cards- if let Some(card_update) = req.card.clone() {- let db = state.store.as_ref();+) -> errors::RouterResponse<api::CustomerPaymentMethodUpdateResponse> {+ let db = state.store.as_ref();- let pm = db- .find_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- payment_method_id,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;+ let pm = db+ .find_payment_method(+ &((&state).into()),+ merchant_context.get_merchant_key_store(),+ payment_method_id,+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- if let Some(cs) = &req.client_secret {- let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;+ if let Some(cs) = &req.client_secret {+ let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;- if is_client_secret_expired {- return Err((errors::ApiErrorResponse::ClientSecretExpired).into());- };+ if is_client_secret_expired {+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());};+ };+ // Currently update is supported only for cards and wallets+ if let Some(card_update) = req.card.clone() {if pm.status == enums::PaymentMethodStatus::AwaitingData {return Err(report!(errors::ApiErrorResponse::NotSupported {message: "Payment method is awaiting data so it cannot be updated".into()@@ -1832,10 +1832,27 @@ pub async fn update_customer_payment_method(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update payment method in db")?;- add_card_resp+ api::CustomerPaymentMethodUpdateResponse {+ merchant_id: add_card_resp.merchant_id,+ customer_id: add_card_resp.customer_id,+ payment_method_id: add_card_resp.payment_method_id,+ payment_method: add_card_resp.payment_method,+ payment_method_type: add_card_resp.payment_method_type,+ #[cfg(feature = "payouts")]+ bank_transfer: add_card_resp.bank_transfer,+ card: add_card_resp.card,+ wallet: None,+ metadata: add_card_resp.metadata,+ created: add_card_resp.created,+ recurring_enabled: add_card_resp.recurring_enabled,+ installment_payment_enabled: add_card_resp.installment_payment_enabled,+ payment_experience: add_card_resp.payment_experience,+ last_used_at: add_card_resp.last_used_at,+ client_secret: add_card_resp.client_secret,+ }} else {// Return existing payment method data as response without any changes- api::PaymentMethodResponse {+ api::CustomerPaymentMethodUpdateResponse {merchant_id: pm.merchant_id.to_owned(),customer_id: Some(pm.customer_id.clone()),payment_method_id: pm.payment_method_id.clone(),@@ -1844,6 +1861,7 @@ pub async fn update_customer_payment_method(#[cfg(feature = "payouts")]bank_transfer: None,card: Some(existing_card_data),+ wallet: None,metadata: pm.metadata,created: Some(pm.created_at),recurring_enabled: Some(false),@@ -1855,6 +1873,61 @@ pub async fn update_customer_payment_method(};Ok(services::ApplicationResponse::Json(response))+ } else if let Some(wallet_update) = req.wallet.clone() {+ if pm.payment_method != Some(common_enums::PaymentMethod::Wallet) {+ return Err((errors::ApiErrorResponse::InvalidRequestData {+ message: "The Payment Method is not wallet".to_string(),+ })+ .into());+ }++ let updated_pmd = PaymentMethodsData::WalletDetails(wallet_update);+ let key_manager_state = (&state).into();+ let pm_data_encrypted = create_encrypted_data(+ &key_manager_state,+ merchant_context.get_merchant_key_store(),+ updated_pmd,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?;++ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {+ payment_method_data: Some(pm_data_encrypted.into()),+ };++ let pm = db+ .update_payment_method(+ &((&state).into()),+ merchant_context.get_merchant_key_store(),+ pm,+ pm_update,+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment method in db")?;++ Ok(services::ApplicationResponse::Json(+ api::CustomerPaymentMethodUpdateResponse {+ merchant_id: pm.merchant_id.to_owned(),+ customer_id: Some(pm.customer_id.clone()),+ payment_method_id: pm.payment_method_id.clone(),+ payment_method: pm.get_payment_method_type(),+ payment_method_type: pm.get_payment_method_subtype(),+ #[cfg(feature = "payouts")]+ bank_transfer: None,+ card: None,+ wallet: req.wallet.clone(),+ metadata: pm.metadata,+ created: Some(pm.created_at),+ recurring_enabled: Some(false),+ installment_payment_enabled: Some(false),+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),+ last_used_at: Some(common_utils::date_time::now()),+ client_secret: pm.client_secret.clone(),+ },+ ))} else {Err(report!(errors::ApiErrorResponse::NotSupported {message: "Payment method update for the given payment method is not supported".into()diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rsindex ed05d5aebe..96c0c5987d 100644--- a/crates/router/src/types/api/payment_methods.rs+++ b/crates/router/src/types/api/payment_methods.rs@@ -17,11 +17,11 @@ pub use api_models::payment_methods::{#[cfg(feature = "v1")]pub use api_models::payment_methods::{CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,- CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodsListResponse,- DefaultPaymentMethod, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest,- GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail,- PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,- PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,+ CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodUpdateResponse,+ CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,+ GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,+ MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,+ PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate,PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest,