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): payment method id retrieval from payment token for V2 (#10834)

Shivansh Mathurf928daf733f0
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index fa67aaca6a..bc38ae53d1 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -2973,6 +2973,47 @@
]
}
},
+ "/v2/payment-methods/token/{payment_method_temporary_token}/details": {
+ "get": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Get Payment Method Token Data",
+ "description": "Retrieve the Payment method id associated with a payment method token.",
+ "operationId": "Get Payment Method Token Data",
+ "parameters": [
+ {
+ "name": "payment_method_temporary_token",
+ "in": "path",
+ "description": "The unique identifier for the Payment Method Token",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method Token Data Retrieved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodGetTokenDetailsResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payment Method Not Found | Payment method token either expired or does not exist"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/payment-method-sessions": {
"post": {
"tags": [
@@ -19305,6 +19346,25 @@
}
}
},
+ "PaymentMethodGetTokenDetailsResponse": {
+ "type": "object",
+ "required": [
+ "id",
+ "payment_method_token"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The payment method ID associated with the token",
+ "example": "12345_pm_019959146f92737389eb6927ce1eb7dc"
+ },
+ "payment_method_token": {
+ "type": "string",
+ "description": "The token associated with the payment method",
+ "example": "token_CSum555d9YxDOpGwYq6q"
+ }
+ }
+ },
"PaymentMethodIntentConfirm": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index ca98262e75..38febddab2 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -9,7 +9,8 @@ use super::{
};
#[cfg(feature = "v2")]
use crate::payment_methods::{
- ListMethodsForPaymentMethodsRequest, PaymentMethodListResponseForSession,
+ ListMethodsForPaymentMethodsRequest, PaymentMethodGetTokenDetailsResponse,
+ PaymentMethodListResponseForSession,
};
use crate::{
payment_methods::{
@@ -602,3 +603,14 @@ impl ApiEventMetric for payments::PaymentsCaptureResponse {
})
}
}
+
+#[cfg(feature = "v2")]
+impl ApiEventMetric for payment_methods::PaymentMethodGetTokenDetailsResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.id.clone(),
+ payment_method_type: None,
+ payment_method_subtype: None,
+ })
+ }
+}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index a432a8d656..269d0a22d5 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -3582,3 +3582,15 @@ pub enum NetworkTokenStatusCheckResponse {
/// Error response for network token status check
FailureResponse(NetworkTokenStatusCheckFailureResponse),
}
+
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct PaymentMethodGetTokenDetailsResponse {
+ /// The payment method ID associated with the token
+ #[schema(value_type = String, example = "12345_pm_019959146f92737389eb6927ce1eb7dc")]
+ pub id: id_type::GlobalPaymentMethodId,
+
+ /// The token associated with the payment method
+ #[schema(value_type = String, example = "token_CSum555d9YxDOpGwYq6q")]
+ pub payment_method_token: String,
+}
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 89190b9cd2..9053070c8e 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -139,6 +139,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payment_method::payment_method_delete_api,
routes::payment_method::network_token_status_check_api,
routes::payment_method::list_customer_payment_method_api,
+ routes::payment_method::payment_method_get_token_details_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
@@ -284,6 +285,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::NetworkTokenStatusCheckResponse,
api_models::payment_methods::NetworkTokenStatusCheckSuccessResponse,
api_models::payment_methods::NetworkTokenStatusCheckFailureResponse,
+ api_models::payment_methods::PaymentMethodGetTokenDetailsResponse,
api_models::enums::TokenStatus,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs
index ed4905ed53..a8d3d9065c 100644
--- a/crates/openapi/src/routes/payment_method.rs
+++ b/crates/openapi/src/routes/payment_method.rs
@@ -345,6 +345,26 @@ pub async fn payment_method_delete_api() {}
#[cfg(feature = "v2")]
pub async fn network_token_status_check_api() {}
+/// Payment Method - Get Payment Method Token Data
+///
+/// Retrieve the Payment method id associated with a payment method token.
+#[utoipa::path(
+ get,
+ path = "/v2/payment-methods/token/{payment_method_temporary_token}/details",
+ params (
+ ("payment_method_temporary_token" = String, Path, description = "The unique identifier for the Payment Method Token"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method Token Data Retrieved", body = PaymentMethodGetTokenDetailsResponse),
+ (status = 404, description = "Payment Method Not Found | Payment method token either expired or does not exist"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Get Payment Method Token Data",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn payment_method_get_token_details_api() {}
+
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index beebe667f0..41ec1794dc 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -4619,3 +4619,27 @@ pub async fn check_network_token_status(
network_token_status_check_response,
))
}
+
+#[cfg(feature = "v2")]
+pub async fn payment_method_get_token_details_core(
+ state: SessionState,
+ provider: domain::Provider,
+ temporary_token: String,
+) -> RouterResponse<payment_methods::PaymentMethodGetTokenDetailsResponse> {
+ let token_data = pm_routes::ParentPaymentMethodToken::create_key_for_token(&temporary_token)
+ .get_data_for_token(&state)
+ .await;
+
+ match token_data {
+ Ok(storage::PaymentTokenData::PermanentCard(card_token_data)) => {
+ Ok(services::ApplicationResponse::Json(
+ payment_methods::PaymentMethodGetTokenDetailsResponse {
+ id: card_token_data.payment_method_id,
+ payment_method_token: temporary_token,
+ },
+ ))
+ }
+ Ok(_) => Err(errors::ApiErrorResponse::PaymentMethodNotFound.into()),
+ Err(e) => Err(e),
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 3a953bd540..7a663b5391 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1583,6 +1583,11 @@ impl PaymentMethods {
.service(
web::resource("/{payment_method_id}/check-network-token-status")
.route(web::get().to(payment_methods::network_token_status_check_api)),
+ )
+ .service(
+ web::resource("/token/{payment_method_temporary_token}/details").route(
+ web::get().to(payment_methods::payment_method_get_token_details_api),
+ ),
);
route = route.service(
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 2ff3fc96ce..8061c031b9 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -138,7 +138,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListCountriesCurrencies
| Flow::DefaultPaymentMethodsSet
| Flow::PaymentMethodSave
- | Flow::TotalPaymentMethodCount => Self::PaymentMethods,
+ | Flow::TotalPaymentMethodCount
+ | Flow::PaymentMethodGetTokenDetails => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 3ab679e1f5..548a484874 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -1205,6 +1205,34 @@ impl ParentPaymentMethodToken {
}
}
}
+
+ pub async fn get_data_for_token(
+ &self,
+ state: &SessionState,
+ ) -> CustomResult<PaymentTokenData, errors::ApiErrorResponse> {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ logger::debug!(
+ "Fetching payment method token data from redis for key: {}",
+ self.key_for_token
+ );
+
+ let pm_token_data = redis_conn
+ .get_and_deserialize_key::<PaymentTokenData>(
+ &self.key_for_token.as_str().into(),
+ "Token Data",
+ )
+ .await
+ .map_err(|e| error_stack::report!(storage_impl::StorageError::from(e)))
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Payment method token either expired or does not exist".to_string(),
+ })?;
+ Ok(pm_token_data)
+ }
}
#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]
@@ -1658,3 +1686,39 @@ pub async fn network_token_status_check_api(
))
.await
}
+
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodGetTokenDetails))]
+pub async fn payment_method_get_token_details_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodGetTokenDetails;
+ let temporary_token = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ let temporary_token = temporary_token.clone();
+ async move {
+ let platform: domain::Platform = auth.platform;
+ payment_methods_routes::payment_method_get_token_details_core(
+ state,
+ platform.get_provider().clone(),
+ temporary_token,
+ )
+ .await
+ }
+ },
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 05b46c8a6a..8f6e096f7a 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -134,6 +134,8 @@ pub enum Flow {
PaymentMethodsList,
/// Payment method save flow
PaymentMethodSave,
+ /// Get token details using temporary token
+ PaymentMethodGetTokenDetails,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// Payment methods token data get flow.