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(payments): add update intent api support to have update intent, session tokens, combined pml flow based on integration header (#14050)
Prasunna Soppa45be22b1a224
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex a08f3ac420..f0bc339f32 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -32608,6 +32608,26 @@}}},+ "PaymentMethodListResult": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/ClientPaymentMethodsListResponse"+ },+ {+ "type": "object",+ "description": "Serializes as `{ \"error\": { ... } }` — the same envelope the HTTP layer puts around\n`ErrorResponse`, so this reads identically to the standalone endpoint's error body.",+ "required": [+ "error"+ ],+ "properties": {+ "error": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }+ ],+ "description": "The combined payment-method list, or the error that prevented it being built.\n\nSerialized untagged: a success is the listing object itself, a failure is `{ \"error\": {...} }`.\nGated on `errors` as well as `v1`: it holds [`crate::errors::types::ErrorResponse`], which\nlives behind that feature because it pulls in `reqwest`. `euclid_wasm` builds\n`api_models/v1` without `errors`, and cannot take `actix-web` in via that feature on a\nwasm target, so the section types simply do not exist there."+ },"PaymentMethodMetaData": {"type": "object","description": "Represents metadata about the payment method used in the 3DS decision rule.",@@ -34557,6 +34577,22 @@"example": "cHJvZmlsZV9pZD1wcm9mXzEyMyxwdWJsaXNoYWJsZV9rZXk9cGtfbGl2ZV8xMjM=","nullable": true},+ "payment_method_list": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodListResult"+ }+ ],+ "nullable": true+ },+ "session_tokens": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SessionTokensResult"+ }+ ],+ "nullable": true+ },"connector": {"type": "string","description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.",@@ -36395,6 +36431,22 @@"example": "cHJvZmlsZV9pZD1wcm9mXzEyMyxwdWJsaXNoYWJsZV9rZXk9cGtfbGl2ZV8xMjM=","nullable": true},+ "payment_method_list": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodListResult"+ }+ ],+ "nullable": true+ },+ "session_tokens": {+ "allOf": [+ {+ "$ref": "#/components/schemas/SessionTokensResult"+ }+ ],+ "nullable": true+ },"connector": {"type": "string","description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.",@@ -45478,6 +45530,26 @@}]},+ "SessionTokensResult": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/PaymentsSessionResponse"+ },+ {+ "type": "object",+ "description": "Serializes as `{ \"error\": { ... } }` — the same envelope the HTTP layer puts around\n`ErrorResponse`, so this reads identically to the standalone endpoint's error body.",+ "required": [+ "error"+ ],+ "properties": {+ "error": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }+ ],+ "description": "Wallet session tokens, or the error that prevented them being minted.\n\nSerialized untagged: a success is the whole `PaymentsSessionResponse` object, a failure is\n`{ \"error\": {...} }`.\nGated on `errors` as well as `v1` — see [`crate::payment_methods::PaymentMethodListResult`]."+ },"SizeVariants": {"type": "string","enum": [diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rsindex bb6065649a..6abd2d1005 100644--- a/crates/api_models/src/errors/types.rs+++ b/crates/api_models/src/errors/types.rs@@ -34,7 +34,7 @@ impl ApiError {}}-#[derive(Debug, serde::Serialize, ToSchema, PolymorphicSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema, PolymorphicSchema)]#[generate_schemas(GenericErrorResponseOpenApi)]pub struct ErrorResponse {#[serde(rename = "type")]@@ -70,7 +70,7 @@ impl From<&ApiErrorResponse> for ErrorResponse {}}-#[derive(Debug, serde::Serialize, Default, Clone)]+#[derive(Debug, serde::Serialize, Default, Clone, PartialEq)]pub struct Extra {#[serde(skip_serializing_if = "Option::is_none")]pub payment_id: Option<common_utils::id_type::PaymentId>,diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 507156e9cb..116f565611 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -27,6 +27,8 @@ use rust_decimal::{use serde::de;use utoipa::ToSchema;+#[cfg(all(feature = "v1", feature = "errors"))]+use crate::errors::types::ErrorResponse;#[cfg(feature = "v1")]use crate::payments::BankCodeResponse;#[cfg(feature = "payouts")]@@ -1966,7 +1968,7 @@ impl From<(Card, Option<common_enums::CardNetwork>)> for CardDetail {}#[cfg(feature = "v1")]-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, ToSchema)]pub struct CardDetailFromLocker {pub scheme: Option<String>,pub issuer_country: Option<String>,@@ -2888,7 +2890,7 @@ pub struct PaymentMethodListIntentDataInput {}/// Intent-only payment details returned as part of the Payment Method List response-#[derive(Debug, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct PaymentMethodListIntentData {/// Unique identifier for the payment#[schema(value_type = String)]@@ -3050,7 +3052,7 @@ pub struct ResponsePaymentMethodsEnabledForClient {/// `CustomerPaymentMethodForClient` is `None`./// Wallet payment method data returned in the client-facing PM list.#[cfg(feature = "v1")]-#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]#[serde(rename_all = "snake_case")]pub enum WalletPaymentMethodDataForClient {ApplePay(Box<PaymentMethodDataWalletInfo>),@@ -3062,7 +3064,7 @@ pub enum WalletPaymentMethodDataForClient {/// Bank debit payment method data returned in the client-facing PM list./// Field names use `_last4_digits` to match the modular service response.#[cfg(feature = "v1")]-#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]#[serde(rename_all = "snake_case")]pub enum BankDebitDataForClient {AchBankDebit {@@ -3080,7 +3082,7 @@ pub enum BankDebitDataForClient {}#[cfg(feature = "v1")]-#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)]#[serde(rename_all = "snake_case")]pub enum CustomerPaymentMethodDataForClient {/// Masked card details from the card locker.@@ -3100,7 +3102,7 @@ pub enum CustomerPaymentMethodDataForClient {/// Only the fields needed by the SDK are included; server-side fields/// (e.g. `surcharge_details`, `metadata`) are omitted.#[cfg(feature = "v1")]-#[derive(Debug, Clone, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct CustomerPaymentMethodForClient {/// Token for payment method in temporary card locker which gets refreshed often./// The SDK passes this back when submitting the payment.@@ -3144,7 +3146,7 @@ pub struct CustomerPaymentMethodForClient {/// Response for the GET /payments/{payment_id}/payment-methods/client endpoint#[cfg(feature = "v1")]-#[derive(Debug, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct ClientPaymentMethodsListResponse {/// Flat list of enabled payment methods — one entry per (payment_method_type × payment_method_subtype)pub payment_methods_enabled: Vec<ResponsePaymentMethodsEnabledForClient>,@@ -3160,8 +3162,28 @@ pub struct ClientPaymentMethodsListResponse {pub intent_data: PaymentMethodListIntentData,}+/// The combined payment-method list, or the error that prevented it being built.+///+/// Serialized untagged: a success is the listing object itself, a failure is `{ "error": {...} }`.+/// Gated on `errors` as well as `v1`: it holds [`crate::errors::types::ErrorResponse`], which+/// lives behind that feature because it pulls in `reqwest`. `euclid_wasm` builds+/// `api_models/v1` without `errors`, and cannot take `actix-web` in via that feature on a+/// wasm target, so the section types simply do not exist there.+#[cfg(all(feature = "v1", feature = "errors"))]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]+#[serde(untagged)]+pub enum PaymentMethodListResult {+ Success(Box<ClientPaymentMethodsListResponse>),+ /// Serializes as `{ "error": { ... } }` — the same envelope the HTTP layer puts around+ /// `ErrorResponse`, so this reads identically to the standalone endpoint's error body.+ Failed {+ #[schema(value_type = GenericErrorResponseOpenApi)]+ error: Box<ErrorResponse>,+ },+}+/// Installment options for a payment method, as returned in the payment method list response-#[derive(Debug, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct PaymentMethodListInstallmentOption {/// The payment method these plans apply to#[schema(value_type = PaymentMethod)]@@ -3171,7 +3193,7 @@ pub struct PaymentMethodListInstallmentOption {}/// A single installment plan with pre-computed amount breakdown-#[derive(Debug, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct PaymentMethodListInstallmentPlan {/// Number of installments for this plan#[schema(value_type = u8)]@@ -3187,7 +3209,7 @@ pub struct PaymentMethodListInstallmentPlan {}/// Amount breakdown for a single installment plan-#[derive(Debug, serde::Serialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]pub struct PaymentMethodListInstallmentAmountDetails {/// Amount charged per installment in major units#[schema(value_type = f64)]@@ -3787,7 +3809,7 @@ pub struct PaymentMethodCollectLinkStatusDetails {pub ui_config: link_utils::GenericLinkUiConfigFormData,}-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]pub struct MaskedBankDetails {pub mask: String,pub account_holder_name: Option<String>,diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 67e48088b6..722da890e6 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -80,6 +80,8 @@ use time::{Date, PrimitiveDateTime};use url::Url;use utoipa::ToSchema;+#[cfg(all(feature = "v1", feature = "errors"))]+use crate::errors::types::ErrorResponse;#[cfg(feature = "v2")]use crate::mandates;use crate::{@@ -7411,6 +7413,20 @@ pub struct PaymentsResponse {#[smithy(value_type = "Option<String>")]pub sdk_authorization: Option<String>,+ /// The combined payment-method list, returned only for `X-Integration-Type: server`.+ #[cfg(feature = "errors")]+ #[serde(skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<PaymentMethodListResult>)]+ #[smithy(value_type = "Option<Object>")]+ pub payment_method_list: Option<payment_methods::PaymentMethodListResult>,++ /// Wallet session tokens for this payment, returned only for `X-Integration-Type: server`.+ #[cfg(feature = "errors")]+ #[serde(skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<SessionTokensResult>)]+ #[smithy(value_type = "Option<Object>")]+ pub session_tokens: Option<SessionTokensResult>,+/// The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.#[schema(example = "stripe")]#[smithy(value_type = "Option<String>")]@@ -10582,6 +10598,56 @@ pub struct GooglePayTokenizationParameters {pub stripe_version: Option<Secret<String>>,}+/// Which integration the caller is building, taken from the `X-Integration-Type` header.+///+/// `Client` is the default by design: an integration that has never heard of the header keeps+/// its current response shape.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum IntegrationType {+ Client,+ Server,+}++#[cfg(feature = "v1")]+impl IntegrationType {+ /// Parses the raw header value. `None`, or anything other than `server`, is a client+ /// integration — the caller logs the unrecognised case, since this crate has no logger.+ pub fn from_header_value(value: Option<&str>) -> Self {+ value.map_or(Self::Client, |value| {+ if value.trim().eq_ignore_ascii_case("server") {+ Self::Server+ } else {+ Self::Client+ }+ })+ }++ pub fn is_server(self) -> bool {+ matches!(self, Self::Server)+ }+}++/// Wallet session tokens, or the error that prevented them being minted.+///+/// Serialized untagged: a success is the whole `PaymentsSessionResponse` object, a failure is+/// `{ "error": {...} }`.+/// Gated on `errors` as well as `v1` — see [`crate::payment_methods::PaymentMethodListResult`].+#[cfg(all(feature = "v1", feature = "errors"))]+#[derive(Debug, Clone, PartialEq, serde::Serialize, ToSchema)]+#[serde(untagged)]+pub enum SessionTokensResult {+ /// The session response exactly as `POST /payments/session_tokens` returns it, including+ /// `vault_details` — which carries the internal vault SDK authorization.+ Success(Box<PaymentsSessionResponse>),+ /// Serializes as `{ "error": { ... } }` — the same envelope the HTTP layer puts around+ /// `ErrorResponse`, so this reads identically to the standalone endpoint's error body.+ Failed {+ #[schema(value_type = GenericErrorResponseOpenApi)]+ error: Box<ErrorResponse>,+ },+}+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]#[serde(tag = "wallet_name")]#[serde(rename_all = "snake_case")]@@ -11440,7 +11506,7 @@ impl AmazonPayDeliveryOptions {}#[cfg(feature = "v1")]-#[derive(Default, Debug, serde::Serialize, Clone, ToSchema)]+#[derive(Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema)]pub struct PaymentsSessionResponse {/// The identifier for the payment#[schema(value_type = String)]diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rsindex c688c600b6..ae44408f37 100644--- a/crates/common_utils/src/consts.rs+++ b/crates/common_utils/src/consts.rs@@ -223,6 +223,11 @@ pub const X_CONFIG_OVERRIDE: &str = "x-config-override";/// Merchant ID Headerpub const X_MERCHANT_ID: &str = "x-merchant-id";+/// Selects the integration the caller is building. `server` opts a payments response into the+/// combined shape that also carries the payment-method list and wallet session tokens; `client`+/// or an absent header keeps the existing response untouched.+pub const X_INTEGRATION_TYPE: &str = "x-integration-type";+/// Default Tenant ID for the `Global` tenantpub const DEFAULT_GLOBAL_TENANT_ID: &str = "global";diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex f15933234e..fb062af8e6 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -440,6 +440,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::BankTransferTypes,api_models::payment_methods::CustomerPaymentMethodsListResponse,api_models::payment_methods::ClientPaymentMethodsListResponse,+ api_models::payment_methods::PaymentMethodListResult,api_models::payment_methods::ResponsePaymentMethodsEnabledForClient,api_models::payment_methods::PaymentMethodSubtypeSpecificDataForClient,api_models::payment_methods::CustomerPaymentMethodForClient,@@ -688,6 +689,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::PaymentsCaptureRequest,api_models::payments::PaymentsSessionRequest,api_models::payments::PaymentsSessionResponse,+ api_models::payments::SessionTokensResult,api_models::payments::PazeWalletData,api_models::payments::SessionToken,api_models::payments::VaultSessionDetails,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 68ca389b02..b7915b3d5b 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -17,6 +17,8 @@ pub mod session_operation;pub mod tokenization;pub mod transformers;pub mod types;+#[cfg(feature = "v1")]+pub mod update_context;pub mod vault_session;#[cfg(feature = "olap")]use std::collections::HashMap;diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 5c1fca9e73..851339dc32 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -4333,6 +4333,9 @@ where.attach_printable("Failed to parse recipient details")?.map(api_models::payments::MaskedRecipientDetails::from);let payments_response = api::PaymentsResponse {+ // Populated only for server integrations, by the update-context enrichment.+ payment_method_list: None,+ session_tokens: None,payment_id: payment_intent.payment_id,merchant_id: payment_intent.merchant_id,status: payment_intent.status,@@ -4745,6 +4748,9 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay.flatten().map(api_models::payments::MaskedRecipientDetails::from);Self {+ // Populated only for server integrations, by the update-context enrichment.+ payment_method_list: None,+ session_tokens: None,connector_response_metadata: pa.get_connector_response_metadata_from_attempt_metadata(),applied_offer: applied_offer_response(pa.applied_offer_details.clone()),payment_id: pi.payment_id,diff --git a/crates/router/src/core/payments/update_context.rs b/crates/router/src/core/payments/update_context.rsnew file mode 100644index 0000000000..2fea73ac0a--- /dev/null+++ b/crates/router/src/core/payments/update_context.rs@@ -0,0 +1,278 @@+//! Server-integration enrichment for payments responses.+//!+//! A caller that sends `X-Integration-Type: server` gets the payment response it always got,+//! plus the two artifacts its checkout would otherwise fetch in separate calls: the combined+//! payment-method list and the wallet session tokens. Client integrations, and callers that+//! send no header at all, are unaffected.+//!+//! This module adds no business logic. It calls the two existing cores — the same ones behind+//! `POST /payments/session_tokens` and `GET /payments/{id}/client` — and attaches their results+//! to the response. Both reads run after the write they depend on, and concurrently with each+//! other, since neither reads the other's output.++use api_models::{+ payment_methods as payment_methods_api,+ payments::{self as payment_types, IntegrationType},+};+use common_utils::{consts, errors::ErrorSwitch, id_type};+use error_stack::ResultExt;+use router_env::{instrument, logger, tracing};++use crate::{+ core::{errors, payment_methods::client as pm_client, payments},+ routes::{app::ReqState, SessionState},+ services::{ApplicationResponse, AuthFlow},+ types::{api as api_types, domain},+};++/// How long a single section may run before it is reported as degraded.+///+/// The same bound an outgoing connector call gets. The session core makes outbound calls of its+/// own — the Apple Pay session call among them — and those already run under+/// [`consts::REQUEST_TIME_OUT`], so a tighter bound here would cut short a call the standalone+/// endpoint would have let finish. The payment has already committed by the time either section+/// runs, so a section that hangs would hold back a response the caller is entitled to; each is+/// bounded separately so a slow one cannot starve the other.+const SECTION_TIMEOUT: std::time::Duration =+ std::time::Duration::from_secs(consts::REQUEST_TIME_OUT);++/// Reads [`IntegrationType`] from the request headers.+///+/// Falling back to `Client` keeps a malformed header from failing the payment, but a caller that+/// meant `server` would otherwise silently never see the extra sections — so that case is logged.+pub fn integration_type_from_headers(+ headers: &actix_web::http::header::HeaderMap,+) -> IntegrationType {+ let value = headers+ .get(consts::X_INTEGRATION_TYPE)+ .and_then(|value| value.to_str().ok());++ let integration_type = IntegrationType::from_header_value(value);++ // Tested against the accepted spellings directly rather than inferred from `integration_type`+ // being `Client`: that inference only holds while `Client` is the fallback, and would stop+ // reporting anything the day the fallback changed.+ let unrecognised = value.filter(|value| {+ let value = value.trim();+ !value.eq_ignore_ascii_case("server") && !value.eq_ignore_ascii_case("client")+ });++ if let Some(value) = unrecognised {+ logger::warn!(+ header = consts::X_INTEGRATION_TYPE,+ value,+ "unrecognised integration type, defaulting to client"+ );+ }++ integration_type+}++/// Builds the error payload a degraded section carries, from the same error the standalone+/// endpoint would have surfaced.+fn section_error(+ error: &error_stack::Report<errors::ApiErrorResponse>,+) -> Box<api_models::errors::types::ErrorResponse> {+ // Route through the same conversion the HTTP layer uses, so an inline section error reads+ // identically to the body the standalone endpoint would have returned.+ let switched: api_models::errors::types::ApiErrorResponse = error.current_context().switch();+ Box::new(api_models::errors::types::ErrorResponse::from(&switched))+}++/// The error a section reports when it exceeds [`SECTION_TIMEOUT`].+fn timed_out(section: &str) -> error_stack::Report<errors::ApiErrorResponse> {+ error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(+ "server-integration: {section} exceeded {}s and was reported as degraded",+ SECTION_TIMEOUT.as_secs()+ ))+}++/// Attaches the payment-method list and wallet session tokens to a payments response.+///+/// Best-effort by design: the payment write has already committed by the time this runs, so a+/// failing section reports its own error inline and the response still succeeds. Turning a+/// section failure into a 5xx would hide a committed state change from the caller.+#[instrument(skip_all, fields(payment_id))]+pub async fn attach_server_context(+ state: SessionState,+ req_state: ReqState,+ platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,+ payment_id: &id_type::PaymentId,+ header_payload: hyperswitch_domain_models::payments::HeaderPayload,+ response: &mut payment_types::PaymentsResponse,+) {+ tracing::Span::current().record("payment_id", payment_id.get_string_repr());++ // Logged unconditionally on entry. This function runs only for a caller that opted in with+ // `X-Integration-Type: server`, so the presence of this line is what separates "the header+ // arrived and enrichment ran" from "the request never reached this path" — the two cases a+ // response missing both sections cannot otherwise distinguish.+ logger::info!(+ timeout_secs = SECTION_TIMEOUT.as_secs(),+ "server-integration: enriching payments response with session tokens and payment-method list"+ );++ let started = std::time::Instant::now();++ // Both reads observe the committed payment; neither reads the other's output. Each is+ // bounded separately so one slow section still lets the other through.+ let (session_result, payment_methods_result) = Box::pin(futures::future::join(+ tokio::time::timeout(+ SECTION_TIMEOUT,+ Box::pin(session_tokens(+ state.clone(),+ req_state,+ platform.clone(),+ profile_id,+ payment_id,+ header_payload,+ )),+ ),+ tokio::time::timeout(+ SECTION_TIMEOUT,+ Box::pin(payment_method_list(state, platform, payment_id)),+ ),+ ))+ .await;++ let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);++ let session_result = session_result.unwrap_or_else(|_| Err(timed_out("session_tokens")));+ let payment_methods_result =+ payment_methods_result.unwrap_or_else(|_| Err(timed_out("payment_method_list")));++ response.session_tokens = Some(match session_result {+ Ok(session) => {+ logger::info!(+ session_token_count = session.session_token.len(),+ "server-integration: session tokens attached"+ );+ payment_types::SessionTokensResult::Success(Box::new(session))+ }+ Err(error) => {+ logger::warn!(?error, "server-integration: session tokens unavailable");+ payment_types::SessionTokensResult::Failed {+ error: section_error(&error),+ }+ }+ });++ response.payment_method_list = Some(match payment_methods_result {+ Ok(listing) => {+ logger::info!(+ payment_methods_enabled_count = listing.payment_methods_enabled.len(),+ customer_payment_methods_count = listing.customer_payment_methods.len(),+ "server-integration: payment-method list attached"+ );+ payment_methods_api::PaymentMethodListResult::Success(Box::new(listing))+ }+ Err(error) => {+ logger::warn!(+ ?error,+ "server-integration: payment-method list unavailable"+ );+ payment_methods_api::PaymentMethodListResult::Failed {+ error: section_error(&error),+ }+ }+ });++ // Reports what each section actually produced. A blanket "complete" here would read as+ // success on a response whose sections both carry errors.+ logger::info!(+ elapsed_ms,+ session_tokens_ok = matches!(+ response.session_tokens,+ Some(payment_types::SessionTokensResult::Success(_))+ ),+ payment_method_list_ok = matches!(+ response.payment_method_list,+ Some(payment_methods_api::PaymentMethodListResult::Success(_))+ ),+ "server-integration: enrichment complete"+ );+}++/// Runs the session-token core for this payment.+async fn session_tokens(+ state: SessionState,+ req_state: ReqState,+ platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,+ payment_id: &id_type::PaymentId,+ header_payload: hyperswitch_domain_models::payments::HeaderPayload,+) -> errors::RouterResult<payment_types::PaymentsSessionResponse> {+ logger::info!("server-integration: calling session-token core");++ let response = Box::pin(payments::payments_core::<+ api_types::Session,+ payment_types::PaymentsSessionResponse,+ _,+ _,+ _,+ payments::PaymentData<api_types::Session>,+ >(+ state,+ req_state,+ platform,+ profile_id,+ payments::PaymentSession,+ payment_types::PaymentsSessionRequest {+ payment_id: payment_id.clone(),+ client_secret: None,+ wallets: Vec::new(),+ merchant_connector_details: None,+ },+ AuthFlow::Merchant,+ payments::CallConnectorAction::Trigger,+ None,+ None,+ header_payload,+ None,+ ))+ .await?;++ // Returned whole: the caller gets `session_token` and `vault_details` (the internal vault+ // SDK authorization) exactly as the standalone endpoint would have returned them.+ json_body(response, "session_tokens")+}++/// Runs the payment-method-list core the client endpoint is backed by.+///+/// A thin wrapper over the core call so this section announces itself before it starts, the same+/// way [`session_tokens`] does — without it, a section that hangs until [`SECTION_TIMEOUT`] leaves+/// no trace of having been entered.+async fn payment_method_list(+ state: SessionState,+ platform: domain::Platform,+ payment_id: &id_type::PaymentId,+) -> errors::RouterResult<payment_methods_api::ClientPaymentMethodsListResponse> {+ logger::info!("server-integration: calling payment-method-list core");++ let response = Box::pin(pm_client::list_payment_methods_client(+ state,+ platform,+ payment_id.clone(),+ // Merchant API key authenticated; there is no client secret to validate.+ None,+ ))+ .await?;++ json_body(response, "payment_method_list")+}++/// A core response can only contribute when it is a plain JSON body.+fn json_body<T>(response: ApplicationResponse<T>, section: &str) -> errors::RouterResult<T> {+ match response {+ ApplicationResponse::Json(payload) | ApplicationResponse::JsonWithHeaders((payload, _)) => {+ Ok(payload)+ }+ _ => Err(error_stack::report!(+ errors::ApiErrorResponse::InternalServerError+ ))+ .attach_printable_lazy(|| {+ format!("server-integration: {section} core returned a non-JSON response")+ }),+ }+}diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex e192d40061..fb05f33741 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -2112,6 +2112,8 @@ mod tests {let primary_object_created_at = Some(common_utils::date_time::now());let expected_response = api::PaymentsResponse {payment_id,+ payment_method_list: None,+ session_tokens: None,status: IntentStatus::Succeeded,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 98c6445efb..5ad7e10f6f 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -28,6 +28,8 @@ use router_env::{env, instrument, logger, tracing, types, Flow};use super::app::ReqState;#[cfg(feature = "v2")]use crate::core::payment_method_balance;+#[cfg(feature = "v1")]+use crate::core::payments::update_context;#[cfg(feature = "v2")]use crate::core::revenue_recovery::api as recovery;#[cfg(feature = "v1")]@@ -40,7 +42,7 @@ use crate::{payments::{self, transformers::ToResponse, OperationSessionGetters, PaymentRedirectFlow},},routes::lock_utils,- services::{api, authentication as auth},+ services::{self, api, authentication as auth},types::{api::{self as api_types, enums as api_enums,@@ -927,33 +929,94 @@ pub async fn payments_update(}};+ let integration_type = update_context::integration_type_from_headers(req.headers());++ // Gated on merchant auth too: this route also accepts publishable-key + client-secret, and+ // the enrichment runs as `AuthFlow::Merchant`, so a client caller must not opt in by header.+ let enrich = integration_type.is_server() && auth_flow == api::AuthFlow::Merchant;+Box::pin(api::server_wrap(flow,state,&req,payload,- |state, auth: auth::AuthenticationData, req, req_state| {- payments::payments_core::<- api_types::UpdatePostConfirm,- payment_types::PaymentsResponse,- _,- _,- _,- payments::PaymentData<api_types::UpdatePostConfirm>,- >(- state,- req_state,- auth.platform,- auth.profile.map(|profile| profile.get_id().clone()),- payments::PaymentUpdate,- req,- auth_flow,- payments::CallConnectorAction::Trigger,- None,- None,- header_payload.clone(),- None,- )+ move |state, auth: auth::AuthenticationData, req, req_state| {+ let header_payload = header_payload.clone();+ async move {+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());++ // Only the enrichment path needs these afterwards. A client update — the vast+ // majority — clones nothing.+ let enrichment_inputs = enrich.then(|| {+ (+ state.clone(),+ req_state.clone(),+ auth.platform.clone(),+ profile_id.clone(),+ header_payload.clone(),+ )+ });++ let response = Box::pin(payments::payments_core::<+ api_types::UpdatePostConfirm,+ payment_types::PaymentsResponse,+ _,+ _,+ _,+ payments::PaymentData<api_types::UpdatePostConfirm>,+ >(+ state,+ req_state,+ auth.platform,+ profile_id,+ payments::PaymentUpdate,+ req,+ auth_flow,+ payments::CallConnectorAction::Trigger,+ None,+ None,+ header_payload,+ None,+ ))+ .await?;++ // Invoked directly, not through `server_wrap`: both flows map to+ // `ApiIdentifier::Payments`, so a nested wrap would deadlock on the lock this+ // request already holds.+ let enrich_payment = |mut payment: payment_types::PaymentsResponse| async {+ if let Some((state, req_state, platform, profile_id, header_payload)) =+ enrichment_inputs+ {+ let id = payment.payment_id.clone();+ Box::pin(update_context::attach_server_context(+ state,+ req_state,+ platform,+ profile_id,+ &id,+ header_payload,+ &mut payment,+ ))+ .await;+ }+ payment+ };++ // `enrich_payment` is a no-op when `enrichment_inputs` is `None`, so the opt-in+ // decision lives in exactly one place rather than being re-tested here.+ match response {+ services::ApplicationResponse::JsonWithHeaders((payment, headers)) => {+ Ok(services::ApplicationResponse::JsonWithHeaders((+ enrich_payment(payment).await,+ headers,+ )))+ }+ services::ApplicationResponse::Json(payment) => Ok(+ services::ApplicationResponse::Json(enrich_payment(payment).await),+ ),+ response => Ok(response),+ }+ }},&*auth_type,locking_action,diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rsindex 022259f52e..681283750e 100644--- a/crates/router/tests/payments.rs+++ b/crates/router/tests/payments.rs@@ -375,6 +375,8 @@ async fn payments_create_core() {let expected_response = api::PaymentsResponse {payment_id,applied_offer: None,+ payment_method_list: None,+ session_tokens: None,status: api_enums::IntentStatus::Succeeded,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),@@ -687,6 +689,8 @@ async fn payments_create_core_adyen_no_redirect() {api::PaymentsResponse {payment_id: payment_id.clone(),applied_offer: None,+ payment_method_list: None,+ session_tokens: None,status: api_enums::IntentStatus::Processing,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rsindex fe78b3b671..11c5488e88 100644--- a/crates/router/tests/payments2.rs+++ b/crates/router/tests/payments2.rs@@ -135,6 +135,8 @@ async fn payments_create_core() {let expected_response = api::PaymentsResponse {payment_id,applied_offer: None,+ payment_method_list: None,+ session_tokens: None,status: api_enums::IntentStatus::Succeeded,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),@@ -456,6 +458,8 @@ async fn payments_create_core_adyen_no_redirect() {api::PaymentsResponse {payment_id: payment_id.clone(),applied_offer: None,+ payment_method_list: None,+ session_tokens: None,status: api_enums::IntentStatus::Processing,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),