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(connector): [Paypal] Returning Customer Flow (#14673)
Nithin N6ed69284f016
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 76e99df6a2..fc61c33107 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -20242,6 +20242,14 @@],"nullable": true},+ "paypal": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaypalConnectorMetadata"+ }+ ],+ "nullable": true+ },"worldpayxml": {"allOf": [{@@ -22318,6 +22326,14 @@],"nullable": true},+ "wallets": {+ "allOf": [+ {+ "$ref": "#/components/schemas/WalletPaymentMethodDataForClient"+ }+ ],+ "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.",@@ -34366,6 +34382,14 @@"description": "Email address associated with the wallet (e.g. PayPal email)","example": "[email protected]","nullable": true+ },+ "provider_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/WalletProviderDetails"+ }+ ],+ "nullable": true}}},@@ -41937,6 +41961,17 @@"authorize"]},+ "PaypalConnectorMetadata": {+ "type": "object",+ "description": "PayPal-specific metadata supplied with a payment request.",+ "properties": {+ "paypal_client_metadata_id": {+ "type": "string",+ "description": "FraudNet session identifier sent in the PAYPAL-CLIENT-METADATA-ID request header.",+ "nullable": true+ }+ }+ },"PaypalFlow": {"type": "string","enum": [@@ -41952,6 +41987,12 @@"example": "[email protected]","nullable": true,"maxLength": 255+ },+ "payer_id": {+ "type": "string",+ "description": "PayPal payer identifier.",+ "example": "7DY7FRMPQ8CT6",+ "nullable": true}}},@@ -42048,6 +42089,18 @@}}},+ "PaypalWalletInfo": {+ "type": "object",+ "description": "PayPal-specific wallet details. Email belongs to the shared wallet model.",+ "properties": {+ "payer_id": {+ "type": "string",+ "description": "Unique identifier of the payer's PayPal account.",+ "example": "7DY7FRMPQ8CT6",+ "nullable": true+ }+ }+ },"PayseraData": {"type": "object"},@@ -51343,6 +51396,21 @@],"description": "Typed subtype-specific data for a saved customer payment method, returned in the\n`GET /payments/{payment_id}/payment-methods/client` response.\n\nSerializes as an externally-tagged enum, producing e.g.:\n`{ \"card\": { \"last4_digits\": \"4242\", ... } }`\n\nOnly variants for subtypes that actually carry extra data are included;\nfor all other subtypes the `payment_method_data` field on\n`CustomerPaymentMethodForClient` is `None`.\nWallet payment method data returned in the client-facing PM list."},+ "WalletProviderDetails": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "PayPal"+ ],+ "properties": {+ "PayPal": {+ "$ref": "#/components/schemas/PaypalWalletInfo"+ }+ }+ }+ ]+ },"WalletResponse": {"allOf": [{diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 4b10a56f14..c235173218 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -12932,6 +12932,14 @@],"nullable": true},+ "paypal": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaypalConnectorMetadata"+ }+ ],+ "nullable": true+ },"worldpayxml": {"allOf": [{@@ -24558,6 +24566,14 @@"description": "Email address associated with the wallet (e.g. PayPal email)","example": "[email protected]","nullable": true+ },+ "provider_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/WalletProviderDetails"+ }+ ],+ "nullable": true}}},@@ -25546,6 +25562,17 @@"$ref": "#/components/schemas/BankDebitDetailUpdate"}}+ },+ {+ "type": "object",+ "required": [+ "wallet"+ ],+ "properties": {+ "wallet": {+ "$ref": "#/components/schemas/WalletDetailUpdate"+ }+ }}]},@@ -28907,6 +28934,17 @@"authorize"]},+ "PaypalConnectorMetadata": {+ "type": "object",+ "description": "PayPal-specific metadata supplied with a payment request.",+ "properties": {+ "paypal_client_metadata_id": {+ "type": "string",+ "description": "FraudNet session identifier sent in the PAYPAL-CLIENT-METADATA-ID request header.",+ "nullable": true+ }+ }+ },"PaypalFlow": {"type": "string","enum": [@@ -28922,6 +28960,12 @@"example": "[email protected]","nullable": true,"maxLength": 255+ },+ "payer_id": {+ "type": "string",+ "description": "PayPal payer identifier.",+ "example": "7DY7FRMPQ8CT6",+ "nullable": true}}},@@ -29018,6 +29062,18 @@}}},+ "PaypalWalletInfo": {+ "type": "object",+ "description": "PayPal-specific wallet details. Email belongs to the shared wallet model.",+ "properties": {+ "payer_id": {+ "type": "string",+ "description": "Unique identifier of the payer's PayPal account.",+ "example": "7DY7FRMPQ8CT6",+ "nullable": true+ }+ }+ },"PayseraData": {"type": "object"},@@ -37069,6 +37125,31 @@}]},+ "WalletDetailUpdate": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "pay_pal"+ ],+ "properties": {+ "pay_pal": {+ "type": "object",+ "properties": {+ "email": {+ "type": "string",+ "nullable": true+ },+ "payer_id": {+ "type": "string",+ "nullable": true+ }+ }+ }+ }+ }+ ]+ },"WalletPaymentMethodData": {"oneOf": [{@@ -37128,6 +37209,21 @@}]},+ "WalletProviderDetails": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "PayPal"+ ],+ "properties": {+ "PayPal": {+ "$ref": "#/components/schemas/PaypalWalletInfo"+ }+ }+ }+ ]+ },"WalletResponse": {"allOf": [{diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex e71a22fcc2..d1ad59a087 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2673,6 +2673,7 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen[43200, 4], # 12 hour * 4 = 48 hours[86400, 4], # 24 hour * 4 = 96 hours], start_after = 60 }, max_retries_count = 17 }, schema = { type = "object" }, description = "Refund sync retry process tracker mapping configuration", change_reason = "Initial setup" }+"payments.should_override_setup_future_usage_to_off_session" = { value = false, schema = { type = "boolean" }, description = "Override setup_future_usage_applied to off_session while preserving intent setup_future_usage , when customer acceptance is passed", change_reason = "Initial setup" }"payments.requires_cvv" = { value = true, schema = { type = "boolean" }, description = "Whether CVV is required for payments", change_reason = "Initial setup" }"payments.accept_payment_amount_mismatch" = { value = false, schema = { type = "boolean" }, description = "Whether to accept a connector-reported payment amount that differs from the requested amount for a merchant and payment method type (payments only, not refunds). When true, the amount mismatch does not fail the integrity check and the payment is updated with the amount actually received instead of being moved to conflicted", change_reason = "Initial setup" }"routing.routing_result_source" = { value = "hyperswitch_routing", schema = { enum = [diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex df1de0aaff..50ab039d66 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -597,6 +597,44 @@ pub struct PaymentMethodUpdate {pub enum PaymentMethodUpdateData {Card(CardDetailUpdate),BankDebit(BankDebitDetailUpdate),+ Wallet(WalletDetailUpdate),+}++#[cfg(feature = "v2")]+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)]+#[serde(deny_unknown_fields, rename_all = "snake_case")]+pub enum WalletDetailUpdate {+ PayPal {+ #[schema(value_type = Option<String>)]+ email: Option<pii::Email>,+ #[schema(value_type = Option<String>)]+ payer_id: Option<hyperswitch_masking::Secret<String>>,+ },+}++#[cfg(feature = "v2")]+impl WalletDetailUpdate {+ pub fn is_metadata_update(&self) -> bool {+ match self {+ Self::PayPal { email, payer_id } => email.is_some() || payer_id.is_some(),+ }+ }++ /// Preserve stored wallet fields omitted from the update.+ pub fn apply_to(self, mut saved: PaymentMethodDataWalletInfo) -> PaymentMethodDataWalletInfo {+ match self {+ Self::PayPal { email, payer_id } => {+ saved.email = email.or(saved.email);+ if let Some(payer_id) = payer_id {+ saved.provider_details =+ Some(WalletProviderDetails::PayPal(PaypalWalletInfo {+ payer_id: Some(payer_id),+ }));+ }+ }+ }+ saved+ }}#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)]@@ -1718,6 +1756,7 @@ impl From<WalletPaymentMethodData> for PaymentMethodsData {card_exp_month: None,card_exp_year: None,auth_code: None,+ provider_details: None,email: data.email,})}@@ -1895,6 +1934,36 @@ pub struct PaymentMethodDataWalletInfo {/// Email address associated with the wallet (e.g. PayPal email)#[schema(value_type = Option<String>, example = "[email protected]")]pub email: Option<pii::Email>,+ /// Details specific to the wallet provider.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub provider_details: Option<WalletProviderDetails>,+}++#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]+pub enum WalletProviderDetails {+ PayPal(PaypalWalletInfo),+}++impl WalletProviderDetails {+ /// Merge provider details without erasing a saved identifier omitted by the response.+ pub fn merge(incoming: Option<Self>, saved: Option<Self>) -> Option<Self> {+ match (incoming, saved) {+ (Some(Self::PayPal(incoming)), Some(Self::PayPal(saved))) => {+ Some(Self::PayPal(PaypalWalletInfo {+ payer_id: incoming.payer_id.or(saved.payer_id),+ }))+ }+ (incoming, saved) => incoming.or(saved),+ }+ }+}++/// PayPal-specific wallet details. Email belongs to the shared wallet model.+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct PaypalWalletInfo {+ /// Unique identifier of the payer's PayPal account.+ #[schema(value_type = Option<String>, example = "7DY7FRMPQ8CT6")]+ pub payer_id: Option<hyperswitch_masking::Secret<String>>,}#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]@@ -1923,6 +1992,7 @@ impl From<payments::additional_info::WalletAdditionalDataForCard> for PaymentMetcard_exp_year: item.card_exp_year,auth_code: item.auth_code,email: item.email,+ provider_details: None,}}}@@ -1968,6 +2038,7 @@ impl From<payments::ApplepayPaymentMethod> for PaymentMethodDataWalletInfo {card_exp_year: item.card_exp_year,auth_code: item.auth_code,email: None,+ provider_details: None,}}}@@ -3825,6 +3896,10 @@ pub struct CustomerPaymentMethod {#[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))]pub card: Option<CardDetailFromLocker>,+ /// Saved wallet account details.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub wallets: Option<WalletPaymentMethodDataForClient>,+/// 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>,@@ -4800,6 +4875,9 @@ impl PaymentMethodSessionUpdateSavedPaymentMethod {} => bank_account_holder_name.is_some(),}}+ Some(PaymentMethodUpdateData::Wallet(wallet_update)) => {+ wallet_update.is_metadata_update()+ }None => false,}}diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 75154968ca..2cd3d226d8 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -5820,6 +5820,21 @@ pub struct PaypalRedirection {#[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]#[smithy(value_type = "Option<String>")]pub email: Option<Email>,+ /// PayPal payer identifier.+ #[schema(value_type = Option<String>, example = "7DY7FRMPQ8CT6")]+ #[smithy(value_type = "Option<String>")]+ pub payer_id: Option<Secret<String>>,+}++impl From<payment_methods::PaymentMethodDataWalletInfo> for PaypalRedirection {+ fn from(info: payment_methods::PaymentMethodDataWalletInfo) -> Self {+ Self {+ email: info.email,+ payer_id: info.provider_details.and_then(|details| match details {+ payment_methods::WalletProviderDetails::PayPal(info) => info.payer_id,+ }),+ }+ }}#[derive(@@ -10716,6 +10731,8 @@ pub struct ConnectorMetadata {pub peachpayments: Option<PeachpaymentsData>,#[smithy(value_type = "Option<SantanderData>")]pub santander: Option<SantanderConnectorMetadataData>,+ #[smithy(value_type = "Option<PaypalConnectorMetadata>")]+ pub paypal: Option<PaypalConnectorMetadata>,#[smithy(value_type = "Option<WorldpayxmlData>")]pub worldpayxml: Option<WorldpayxmlData>,#[smithy(value_type = "Option<CheckoutData>")]@@ -10724,6 +10741,16 @@ pub struct ConnectorMetadata {pub stripe: Option<StripeConnectorMetadata>,}+/// PayPal-specific metadata supplied with a payment request.+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]+#[smithy(namespace = "com.hyperswitch.smithy.types")]+pub struct PaypalConnectorMetadata {+ /// FraudNet session identifier sent in the PAYPAL-CLIENT-METADATA-ID request header.+ #[schema(value_type = Option<String>)]+ #[smithy(value_type = "Option<String>")]+ pub paypal_client_metadata_id: Option<Secret<String>>,+}+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel)]#[smithy(namespace = "com.hyperswitch.smithy.types")]pub struct StripeConnectorMetadata {@@ -14352,6 +14379,7 @@ mod billing_from_payment_method_data {let paypal_wallet_payment_method_data =PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection {email: Some(test_email.clone()),+ payer_id: None,}));let billing_address = paypal_wallet_payment_method_datadiff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rsindex aa3c51e736..cae6ed28b5 100644--- a/crates/connector_configs/src/common_config.rs+++ b/crates/connector_configs/src/common_config.rs@@ -116,6 +116,7 @@ pub struct ApiModelMetaData {pub merchant_street_address: Option<String>,pub customer_service_phone_number: Option<String>,pub merchant_url: Option<String>,+ pub enable_stc: Option<bool>,}#[serde_with::skip_serializing_none]diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rsindex 24ba85dbb0..1166e320c9 100644--- a/crates/connector_configs/src/connector.rs+++ b/crates/connector_configs/src/connector.rs@@ -175,6 +175,7 @@ pub struct ConfigMetadata {pub three_ds_requestor_name: Option<InputData>,pub three_ds_requestor_id: Option<InputData>,pub pull_mechanism_for_external_3ds_enabled: Option<InputData>,+ pub enable_stc: Option<InputData>,pub klarna_region: Option<InputData>,pub region: Option<InputData>,pub pricing_type: Option<InputData>,diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.tomlindex 947140ff31..24fb859420 100644--- a/crates/connector_configs/toml/development.toml+++ b/crates/connector_configs/toml/development.toml@@ -4581,6 +4581,12 @@ label="Client Id"placeholder="Enter Client Id"required=truetype="Text"+[paypal.metadata.enable_stc]+name="enable_stc"+label="Enable fraud risk assessment - Set Transaction Context (STC)"+placeholder="Share sender profile data with PayPal's Risk-as-a-Service API so PayPal can evaluate transaction fraud risk when processing PayPal wallet payments"+required=false+type="Toggle"[paypal_payout][[paypal_payout.wallet]]diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.tomlindex 40c0edd623..6be4e8283e 100644--- a/crates/connector_configs/toml/production.toml+++ b/crates/connector_configs/toml/production.toml@@ -3968,6 +3968,12 @@ label="Client Id"placeholder="Enter Client Id"required=truetype="Text"+[paypal.metadata.enable_stc]+name="enable_stc"+label="Enable fraud risk assessment - Set Transaction Context (STC)"+placeholder="Share sender profile data with PayPal's Risk-as-a-Service API so PayPal can evaluate transaction fraud risk when processing PayPal wallet payments"+required=false+type="Toggle"[paypal_payout][[paypal_payout.wallet]]diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.tomlindex b8b8ba3d8f..cea6ee4f6c 100644--- a/crates/connector_configs/toml/sandbox.toml+++ b/crates/connector_configs/toml/sandbox.toml@@ -4554,6 +4554,12 @@ label="Client Id"placeholder="Enter Client Id"required=truetype="Text"+[paypal.metadata.enable_stc]+name="enable_stc"+label="Enable fraud risk assessment - Set Transaction Context (STC)"+placeholder="Share sender profile data with PayPal's Risk-as-a-Service API so PayPal can evaluate transaction fraud risk when processing PayPal wallet payments"+required=false+type="Toggle"[paypal_payout][[paypal_payout.wallet]]diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex 70e7942214..8b9b7b47dc 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -630,6 +630,7 @@ pub enum PaymentAttemptUpdate {updated_by: String,},ConfirmUpdate {+ setup_future_usage_applied: Option<storage_enums::FutureUsage>,amount: MinorUnit,currency: storage_enums::Currency,status: storage_enums::AttemptStatus,@@ -2694,6 +2695,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {active_frm_id: None,},PaymentAttemptUpdate::ConfirmUpdate {+ setup_future_usage_applied,amount,currency,authentication_type,@@ -2803,7 +2805,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {charges: None,issuer_error_code: None,issuer_error_message: None,- setup_future_usage_applied: None,+ setup_future_usage_applied,routing_approach,connector_request_reference_id,network_transaction_id,diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rsindex 7e55387d3d..ba0c6200fe 100644--- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs+++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs@@ -1532,6 +1532,7 @@ impl ConnectorSpecifications for Barclaycard {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => auth_type == common_enums::AuthenticationType::ThreeDs && request_data.is_card(),// No alternate flow for complete authorizeapi::CurrentFlowInfo::CompleteAuthorize { .. } => false,diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rsindex 224169e6d6..432d381808 100644--- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs@@ -2411,6 +2411,7 @@ impl ConnectorSpecifications for Cybersource {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => {if self.is_3ds_setup_required(&request_data, auth_type) {Some(api::AlternateFlow::PreAuthenticate)@@ -2431,6 +2432,7 @@ impl ConnectorSpecifications for Cybersource {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => self.is_3ds_setup_required(&request_data, auth_type),// No alternate flow for complete authorizeapi::CurrentFlowInfo::CompleteAuthorize { .. } => false,diff --git a/crates/hyperswitch_connectors/src/connectors/elavon_pg.rs b/crates/hyperswitch_connectors/src/connectors/elavon_pg.rsindex 6dc1f06326..6b3590e47e 100644--- a/crates/hyperswitch_connectors/src/connectors/elavon_pg.rs+++ b/crates/hyperswitch_connectors/src/connectors/elavon_pg.rs@@ -736,6 +736,7 @@ impl ConnectorSpecifications for ElavonPg {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }@@ -765,6 +766,7 @@ impl ConnectorSpecifications for ElavonPg {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/globalpayments_realex.rs b/crates/hyperswitch_connectors/src/connectors/globalpayments_realex.rsindex d83e5d6916..8423f3d7f3 100644--- a/crates/hyperswitch_connectors/src/connectors/globalpayments_realex.rs+++ b/crates/hyperswitch_connectors/src/connectors/globalpayments_realex.rs@@ -725,6 +725,7 @@ impl ConnectorSpecifications for GlobalpaymentsRealex {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => {auth_type.is_three_ds()&& request_data.is_card()diff --git a/crates/hyperswitch_connectors/src/connectors/ilixium.rs b/crates/hyperswitch_connectors/src/connectors/ilixium.rsindex 2c14dfcab4..d574b3a5d6 100644--- a/crates/hyperswitch_connectors/src/connectors/ilixium.rs+++ b/crates/hyperswitch_connectors/src/connectors/ilixium.rs@@ -677,6 +677,7 @@ impl ConnectorSpecifications for Ilixium {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/moneris.rs b/crates/hyperswitch_connectors/src/connectors/moneris.rsindex 6eea06562f..cea9d48f15 100644--- a/crates/hyperswitch_connectors/src/connectors/moneris.rs+++ b/crates/hyperswitch_connectors/src/connectors/moneris.rs@@ -923,6 +923,7 @@ impl ConnectorSpecifications for Moneris {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rsindex eb29ce074f..4a769388ce 100644--- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs@@ -1320,6 +1320,7 @@ impl ConnectorSpecifications for Nexixpay {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => {// Mandate payments should skip pre-authentication and go directly to authorizeif request_data.is_mandate_payment() {diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rsindex 5d8efa4f9d..f080732c06 100644--- a/crates/hyperswitch_connectors/src/connectors/nmi.rs+++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs@@ -1141,6 +1141,7 @@ impl ConnectorSpecifications for Nmi {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. } => false,api::CurrentFlowInfo::SetupMandate {diff --git a/crates/hyperswitch_connectors/src/connectors/nordea.rs b/crates/hyperswitch_connectors/src/connectors/nordea.rsindex b65e00407f..dd75f6f8e8 100644--- a/crates/hyperswitch_connectors/src/connectors/nordea.rs+++ b/crates/hyperswitch_connectors/src/connectors/nordea.rs@@ -1145,6 +1145,7 @@ impl ConnectorSpecifications for Nordea {api::CurrentFlowInfo::Authorize {auth_type: _,request_data,+ connector_meta_data: _,} => matches!(&request_data.payment_method_data,payment_method_data::PaymentMethodData::BankDebit(_)diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rsindex aa589bace6..5416d80fb8 100644--- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs+++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs@@ -1713,6 +1713,7 @@ impl ConnectorSpecifications for Nuvei {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. } => false,api::CurrentFlowInfo::SetupMandate {diff --git a/crates/hyperswitch_connectors/src/connectors/paydotcom.rs b/crates/hyperswitch_connectors/src/connectors/paydotcom.rsindex 7d38c11af7..fb9cb9c52f 100644--- a/crates/hyperswitch_connectors/src/connectors/paydotcom.rs+++ b/crates/hyperswitch_connectors/src/connectors/paydotcom.rs@@ -292,6 +292,7 @@ impl api::ConnectorSpecifications for Paydotcom {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => {auth_type.is_three_ds()&& request_data.is_card()@@ -320,6 +321,7 @@ impl api::ConnectorSpecifications for Paydotcom {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => {auth_type.is_three_ds()&& request_data.is_card()diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rsindex c75f4da754..fea682dfec 100644--- a/crates/hyperswitch_connectors/src/connectors/payme.rs+++ b/crates/hyperswitch_connectors/src/connectors/payme.rs@@ -1353,6 +1353,7 @@ impl ConnectorSpecifications for Payme {api::CurrentFlowInfo::Authorize {auth_type: _,request_data,+ connector_meta_data: _,} => matches!(&request_data.payment_method_data,PaymentMethodData::Card(_) | PaymentMethodData::Wallet(_)diff --git a/crates/hyperswitch_connectors/src/connectors/paynearme.rs b/crates/hyperswitch_connectors/src/connectors/paynearme.rsindex 233bb54272..d2373af8a1 100644--- a/crates/hyperswitch_connectors/src/connectors/paynearme.rs+++ b/crates/hyperswitch_connectors/src/connectors/paynearme.rs@@ -665,6 +665,7 @@ impl ConnectorSpecifications for Paynearme {api::CurrentFlowInfo::Authorize {auth_type: _,request_data,+ connector_meta_data: _,} => matches!(&request_data.payment_method_data,hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_)diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rsindex 609ebaa590..ddf47b476f 100644--- a/crates/hyperswitch_connectors/src/connectors/paypal.rs+++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs@@ -24,16 +24,16 @@ use hyperswitch_domain_models::{PaymentMethodToken, PostSessionTokens, SdkSessionUpdate, Session, SetupMandate, Void,},refunds::{Execute, RSync},- unified_authentication_service::PostAuthenticate,+ unified_authentication_service::{PostAuthenticate, PreAuthenticate},CompleteAuthorize, VerifyWebhookSource,},router_request_types::{AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,- PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsSessionData,- PaymentsSyncData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,- VerifyWebhookSourceRequestData,+ PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,+ PaymentsSessionData, PaymentsSyncData, RefundsData, ResponseId,+ SdkPaymentsSessionUpdateData, SetupMandateRequestData, VerifyWebhookSourceRequestData,},router_response_types::{ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,@@ -43,9 +43,10 @@ use hyperswitch_domain_models::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,PaymentsCompleteAuthorizeRouterData, PaymentsExtendAuthorizationRouterData,PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData,- PaymentsPostSessionTokensRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData,- RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,- SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData,+ PaymentsPostSessionTokensRouterData, PaymentsPreAuthenticateRouterData,+ PaymentsSessionRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,+ RefundSyncRouterData, RefundsRouterData, SdkSessionUpdateRouterData,+ SetupMandateRouterData, VerifyWebhookSourceRouterData,},};#[cfg(feature = "payouts")]@@ -68,9 +69,9 @@ use hyperswitch_interfaces::{types::{ExtendedAuthorizationType, IncrementalAuthorizationType, PaymentsAuthorizeType,PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPostAuthenticateType,- PaymentsPostSessionTokensType, PaymentsSessionType, PaymentsSyncType, PaymentsVoidType,- RefreshTokenType, RefundExecuteType, RefundSyncType, Response, SdkSessionUpdateType,- SetupMandateType, VerifyWebhookSourceType,+ PaymentsPostSessionTokensType, PaymentsPreAuthenticateType, PaymentsSessionType,+ PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType,+ Response, SdkSessionUpdateType, SetupMandateType, VerifyWebhookSourceType,},webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},};@@ -134,6 +135,20 @@ impl api::PayoutFulfill for Paypal {}impl api::PayoutSync for Paypal {}impl Paypal {+ fn get_client_metadata_id_header(+ metadata: Option<&api_models::payments::ConnectorMetadata>,+ ) -> Option<(String, Maskable<String>)> {+ metadata+ .and_then(|metadata| metadata.paypal.as_ref())+ .and_then(|paypal| paypal.paypal_client_metadata_id.as_ref())+ .map(|metadata_id| {+ (+ auth_headers::PAYPAL_CLIENT_METADATA_ID.to_string(),+ metadata_id.peek().clone().into_masked(),+ )+ })+ }+pub fn get_order_error_response(&self,res: Response,@@ -1197,7 +1212,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseDatareq: &PaymentsAuthorizeRouterData,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- self.build_headers(req, connectors)+ let mut headers = self.build_headers(req, connectors)?;+ if let Some(header) =+ Self::get_client_metadata_id_header(req.request.connector_intent_metadata.as_ref())+ {+ headers.push(header);+ }+ Ok(headers)}fn get_content_type(&self) -> &'static str {@@ -1542,6 +1563,113 @@ impl}}+impl api::PaymentsPreAuthenticate for Paypal {}++impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>+ for Paypal+{+ fn get_headers(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ connectors: &Connectors,+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {+ self.build_headers(req, connectors)+ }++ fn get_content_type(&self) -> &'static str {+ self.common_get_content_type()+ }++ fn get_url(+ &self,+ _req: &PaymentsPreAuthenticateRouterData,+ connectors: &Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!(+ "{}v1/risk/transaction-contexts",+ self.base_url(connectors)+ ))+ }++ fn get_request_body(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<RequestContent, errors::ConnectorError> {+ let connector_req = paypal::PaypalSetTransactionContextRequest::build(req)?;+ Ok(RequestContent::Json(Box::new(connector_req)))+ }++ fn build_request(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ connectors: &Connectors,+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {+ Ok(Some(+ RequestBuilder::new()+ .method(Method::Post)+ .url(&PaymentsPreAuthenticateType::get_url(+ self, req, connectors,+ )?)+ .attach_default_headers()+ .headers(PaymentsPreAuthenticateType::get_headers(+ self, req, connectors,+ )?)+ .set_body(PaymentsPreAuthenticateType::get_request_body(+ self, req, connectors,+ )?)+ .build(),+ ))+ }++ fn handle_response(+ &self,+ data: &PaymentsPreAuthenticateRouterData,+ event_builder: Option<&mut ConnectorEvent>,+ res: Response,+ ) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> {+ // The Set Transaction Context API can respond with an empty body or a body echoing back+ // the transaction context. Either way, the response contents are informational only -+ // the fraud risk assessment is performed by PayPal during payment authorization.+ let connector_response_reference_id = if res.response.is_empty() {+ None+ } else {+ let response: paypal::PaypalSetTransactionContextResponse = res+ .response+ .parse_struct("paypal PaypalSetTransactionContextResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ event_builder.map(|i| i.set_response_body(&response));+ router_env::logger::info!(connector_response=?response);+ response.tracking_id+ };++ Ok(PaymentsPreAuthenticateRouterData {+ response: Ok(PaymentsResponseData::TransactionResponse {+ resource_id: ResponseId::NoResponseId,+ redirection_data: Box::new(None),+ mandate_reference: Box::new(None),+ connector_metadata: None,+ network_txn_id: None,+ network_txn_link_id: None,+ connector_response_reference_id,+ incremental_authorization_allowed: None,+ authentication_data: None,+ charges: None,+ payment_account_reference: None,+ }),+ ..data.clone()+ })+ }++ fn get_error_response(+ &self,+ res: Response,+ event_builder: Option<&mut ConnectorEvent>,+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res, event_builder)+ }+}+impl api::PaymentsPostAuthenticate for Paypal {}impl ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>@@ -1638,7 +1766,13 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsRespreq: &PaymentsCompleteAuthorizeRouterData,connectors: &Connectors,) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {- self.build_headers(req, connectors)+ let mut headers = self.build_headers(req, connectors)?;+ if let Some(header) =+ Self::get_client_metadata_id_header(req.request.connector_intent_metadata.as_ref())+ {+ headers.push(header);+ }+ Ok(headers)}fn get_content_type(&self) -> &'static str {@@ -2727,6 +2861,34 @@ static PAYPAL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [];impl ConnectorSpecifications for Paypal {+ /// The Set Transaction Context (STC) call to PayPal's Risk-as-a-Service API is required+ /// as a pre-authentication step for paypal wallet payments (redirect, sdk and saved-token+ /// payments by a returning customer, where the payment method data is `MandatePayment`)+ /// when the merchant has opted in via `enable_stc` in the merchant connector account metadata.+ fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo) -> bool {+ match current_flow {+ api::CurrentFlowInfo::Authorize {+ request_data,+ connector_meta_data,+ auth_type: _,+ } => {+ // Match on payment method type so that both fresh paypal wallet+ // (PaypalRedirect / PaypalSdk) payments and returning-customer payments with a+ // saved paypal token (PaymentMethodData::MandatePayment) are covered.+ let is_paypal_pm = matches!(+ request_data.payment_method_type,+ Some(enums::PaymentMethodType::Paypal)+ );+ is_paypal_pm && paypal::is_stc_enabled(&connector_meta_data)+ }+ api::CurrentFlowInfo::CompleteAuthorize { .. }+ | api::CurrentFlowInfo::SetupMandate { .. }+ | api::CurrentFlowInfo::Psync { .. }+ | api::CurrentFlowInfo::UpdatePostConfirm { .. }+ | api::CurrentFlowInfo::ConnectorWebhookRegister { .. } => false,+ }+ }+fn is_post_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo) -> bool {match current_flow {api::CurrentFlowInfo::Authorize { .. } => false,diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rsindex 4afea21349..b322f56296 100644--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs@@ -41,9 +41,10 @@ use hyperswitch_domain_models::{types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,PaymentsExtendAuthorizationRouterData, PaymentsIncrementalAuthorizationRouterData,- PaymentsPostSessionTokensRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData,- RefreshTokenRouterData, RefundsRouterData, SdkSessionUpdateRouterData,- SetupMandateRouterData, VerifyWebhookSourceRouterData,+ PaymentsPostSessionTokensRouterData, PaymentsPreAuthenticateRouterData,+ PaymentsSessionRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,+ RefundsRouterData, SdkSessionUpdateRouterData, SetupMandateRouterData,+ VerifyWebhookSourceRouterData,},};#[cfg(feature = "payouts")]@@ -55,7 +56,7 @@ use hyperswitch_interfaces::{consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},errors,};-use hyperswitch_masking::{ExposeInterface, Secret};+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;use url::Url;@@ -98,6 +99,29 @@ impl GetRequestIncrementalAuthorization for PaymentsSyncData {}}+/// Connector level metadata for Paypal, validated at the time of merchant connector account+/// creation. Contains the `enable_stc` switch for the Set Transaction Context (STC)+/// preprocessing call (PayPal's Risk-as-a-Service API).+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct PaypalConnectorMetadataObject {+ pub enable_stc: Option<bool>,+}++impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for PaypalConnectorMetadataObject {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ meta_data: &Option<common_utils::pii::SecretSerdeValue>,+ ) -> Result<Self, Self::Error> {+ match meta_data {+ Some(metadata) => utils::to_connector_meta_from_secret::<Self>(Some(metadata.clone()))+ .change_context(errors::ConnectorError::InvalidConnectorConfig {+ config: "metadata",+ }),+ None => Ok(Self::default()),+ }+ }+}+#[derive(Debug, Serialize)]pub struct PaypalRouterData<T> {pub amount: StringMajorUnit,@@ -147,6 +171,7 @@ pub mod auth_headers {pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id";pub const PREFER: &str = "Prefer";pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id";+ pub const PAYPAL_CLIENT_METADATA_ID: &str = "PAYPAL-CLIENT-METADATA-ID";pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion";}@@ -482,6 +507,31 @@ pub struct CustomerRequestData {#[derive(Debug, Serialize, Deserialize)]pub struct BillingAgreementStruct {billing_agreement_id: Secret<String>,+ payment_initiator: PaymentInitiator,+}++#[derive(Debug, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum PaymentInitiator {+ Customer,+ Merchant,+}++impl From<Option<bool>> for PaymentInitiator {+ fn from(off_session: Option<bool>) -> Self {+ match off_session {+ Some(true) => Self::Merchant,+ Some(false) | None => Self::Customer,+ }+ }+}++#[derive(Debug, Serialize)]+pub struct PaypalVaultRequest {+ vault_id: Secret<String>,+ payment_initiator: PaymentInitiator,+ #[serde(skip_serializing_if = "Option::is_none")]+ attributes: Option<VaultRequestAttributes>,}impl BillingAgreementStruct {@@ -557,10 +607,32 @@ pub enum ShippingPreference {#[serde(untagged)]pub enum PaypalRedirectionRequest {PaypalRedirectionStruct(PaypalRedirectionStruct),- PaypalVaultStruct(VaultStruct),+ PaypalVaultStruct(PaypalVaultRequest),BillingAgreementStruct(BillingAgreementStruct),}+impl PaypalRedirectionRequest {+ fn from_mandate_id(+ source_payment_instrument_id: String,+ attributes: Option<VaultRequestAttributes>,+ off_session: Option<bool>,+ ) -> Self {+ let payment_initiator = PaymentInitiator::from(off_session);+ if BillingAgreementStruct::is_billing_agreement_id(&source_payment_instrument_id) {+ Self::BillingAgreementStruct(BillingAgreementStruct {+ billing_agreement_id: source_payment_instrument_id.into(),+ payment_initiator,+ })+ } else {+ Self::PaypalVaultStruct(PaypalVaultRequest {+ vault_id: source_payment_instrument_id.into(),+ payment_initiator,+ attributes,+ })+ }+ }+}+#[derive(Debug, Serialize)]pub struct PaypalRedirectionStruct {experience_context: ContextStruct,@@ -1306,26 +1378,17 @@ impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPayments}),))),enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal(- if BillingAgreementStruct::is_billing_agreement_id(&connector_mandate_id) {- PaypalRedirectionRequest::BillingAgreementStruct(- BillingAgreementStruct {- billing_agreement_id: connector_mandate_id.into(),- },- )- } else {- PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct {- vault_id: connector_mandate_id.into(),- attributes: item- .router_data- .get_optional_customer_id()- .as_ref()- .map(|customer_id| VaultRequestAttributes {- customer: Some(CustomerRequestData {- merchant_customer_id: Some(customer_id.clone()),- }),+ PaypalRedirectionRequest::from_mandate_id(+ connector_mandate_id,+ item.router_data.get_optional_customer_id().as_ref().map(+ |customer_id| VaultRequestAttributes {+ customer: Some(CustomerRequestData {+ merchant_customer_id: Some(customer_id.clone()),}),- })- },+ },+ ),+ item.router_data.request.off_session,+ ),))),enums::PaymentMethodType::Ach| enums::PaymentMethodType::Affirm@@ -2448,6 +2511,94 @@ pub struct PaypalMeta {pub order_id: Option<String>,}+// Keys of the sender profile data dictionary expected by PayPal's Risk-as-a-Service API+pub const STC_SENDER_ACCOUNT_ID: &str = "sender_account_id";+pub const STC_SENDER_FIRST_NAME: &str = "sender_first_name";+pub const STC_SENDER_LAST_NAME: &str = "sender_last_name";+pub const STC_SENDER_EMAIL: &str = "sender_email";+pub const STC_SENDER_PHONE: &str = "sender_phone";+pub const STC_SENDER_COUNTRY_CODE: &str = "sender_country_code";++/// Request for PayPal's Risk-as-a-Service Set Transaction Context (STC) API+/// Ref: https://developer.paypal.com/api/limited-release/raas/v1/#transaction-contexts_set+#[derive(Debug, Serialize)]+pub struct PaypalSetTransactionContextRequest {+ pub tracking_id: String,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub additional_data: Vec<PaypalAdditionalDataItem>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaypalAdditionalDataItem {+ pub key: String,+ pub value: Secret<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaypalSetTransactionContextResponse {+ pub tracking_id: Option<String>,+ pub additional_data: Option<Vec<PaypalAdditionalDataItem>>,+}++/// Whether the Set Transaction Context (STC) preprocessing call is enabled for the merchant+/// (via the `enable_stc` flag in the merchant connector account metadata).+pub fn is_stc_enabled(connector_meta_data: &Option<common_utils::pii::SecretSerdeValue>) -> bool {+ PaypalConnectorMetadataObject::try_from(connector_meta_data)+ .ok()+ .and_then(|metadata| metadata.enable_stc)+ .unwrap_or(false)+}++impl PaypalSetTransactionContextRequest {+ pub fn build(+ router_data: &PaymentsPreAuthenticateRouterData,+ ) -> Result<Self, error_stack::Report<errors::ConnectorError>> {+ let sender_account_id = router_data+ .customer_id+ .as_ref()+ .map(|customer_id| customer_id.get_string_repr().to_string());+ let sender_first_name = router_data.get_optional_billing_first_name();+ let sender_last_name = router_data.get_optional_billing_last_name();+ let sender_email = router_data+ .get_optional_billing_email()+ .or_else(|| router_data.request.email.clone());+ let sender_phone = router_data.get_optional_billing_phone_number();+ let sender_country_code = router_data.get_optional_billing_country();++ let mut additional_data = Vec::new();+ let mut push = |key: &str, value: Option<String>| {+ if let Some(value) = value.filter(|value| !value.is_empty()) {+ additional_data.push(PaypalAdditionalDataItem {+ key: key.to_string(),+ value: Secret::new(value),+ });+ }+ };+ push(STC_SENDER_ACCOUNT_ID, sender_account_id);+ push(+ STC_SENDER_FIRST_NAME,+ sender_first_name.map(|name| name.peek().clone()),+ );+ push(+ STC_SENDER_LAST_NAME,+ sender_last_name.map(|name| name.peek().clone()),+ );+ push(+ STC_SENDER_EMAIL,+ sender_email.map(|email| email.peek().clone()),+ );+ push(STC_SENDER_PHONE, sender_phone.map(|phone| phone.expose()));+ push(+ STC_SENDER_COUNTRY_CODE,+ sender_country_code.map(|country| country.to_string()),+ );+ Ok(Self {+ tracking_id: router_data.connector_request_reference_id.clone(),+ additional_data,+ })+ }+}+fn get_id_based_on_intent(intent: &PaypalPaymentIntent,purchase_unit: &PurchaseUnitItem,@@ -2651,6 +2802,10 @@ wherepayment_account_reference: None,}),connector_response,+ connector_returned_payment_method_details: get_connector_disclosed_paypal_details(+ item.data.payment_method_type,+ item.response.payer.as_ref(),+ ),sender_payment_instrument_id: item.response.payer@@ -3048,6 +3203,10 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaypalPaymentsSyncResponse, T, Paymentsitem.data.payment_method_type,item.response.payer.as_ref(),),+ connector_returned_payment_method_details: get_connector_disclosed_paypal_details(+ item.data.payment_method_type,+ item.response.payer.as_ref(),+ ),sender_payment_instrument_id: item.response.payer@@ -3424,7 +3583,28 @@ impl Payer {}}-/// Builds the connector response with the payer details received from paypal.+/// Discloses PayPal wallet details for the shared payment-method response update.+fn get_connector_disclosed_paypal_details(+ payment_method_type: Option<common_enums::PaymentMethodType>,+ payer: Option<&Payer>,+) -> Option<PaymentMethodData> {+ match (payment_method_type, payer) {+ (Some(common_enums::PaymentMethodType::Paypal), Some(payer))+ if payer.email_address.is_some() || payer.payer_id.is_some() =>+ {+ Some(PaymentMethodData::Wallet(WalletData::PaypalRedirect(+ hyperswitch_domain_models::payment_method_data::PaypalRedirection {+ email: payer.email_address.clone(),+ payer_id: payer.payer_id.clone(),+ },+ )))+ }+ _ => None,+ }+}++/// Builds the connector response with the payer details received from PayPal.+/// Reads email and the PayPal identifier only from `payer.email_address` and `payer.payer_id`./// This should only be populated for paypal wallet payments (PaypalRedirect and PaypalSdk/// flows, both of which use `PaymentMethodType::Paypal`), and not for payments processed/// via paypal as a card processor.diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe.rs b/crates/hyperswitch_connectors/src/connectors/paysafe.rsindex 070b62e7f4..d04f9d1ee6 100644--- a/crates/hyperswitch_connectors/src/connectors/paysafe.rs+++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs@@ -1245,6 +1245,7 @@ impl ConnectorSpecifications for Paysafe {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => {if self.is_3ds_setup_required(&request_data, auth_type) {Some(api::AlternateFlow::PreAuthenticate)@@ -1265,6 +1266,7 @@ impl ConnectorSpecifications for Paysafe {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => self.is_3ds_setup_required(&request_data, auth_type),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rsindex 6a843967af..644ad16962 100644--- a/crates/hyperswitch_connectors/src/connectors/redsys.rs+++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs@@ -1030,6 +1030,7 @@ impl ConnectorSpecifications for Redsys {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. } => false,api::CurrentFlowInfo::SetupMandate { .. } => false,@@ -1044,6 +1045,7 @@ impl ConnectorSpecifications for Redsys {api::CurrentFlowInfo::Authorize {auth_type,request_data,+ connector_meta_data: _,} => {// For Redsys in authorize flow, if we reached authentication_step// (controlled by should_continue_after_preauthenticate in pre_authentication_step),diff --git a/crates/hyperswitch_connectors/src/connectors/saferpay.rs b/crates/hyperswitch_connectors/src/connectors/saferpay.rsindex 4c074dcd84..9f1790098d 100644--- a/crates/hyperswitch_connectors/src/connectors/saferpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/saferpay.rs@@ -361,6 +361,7 @@ impl ConnectorSpecifications for Saferpay {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => auth_type == common_enums::AuthenticationType::ThreeDs && request_data.is_card(),api::CurrentFlowInfo::CompleteAuthorize { .. }| api::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rsindex aa0be07ece..09e78743f3 100644--- a/crates/hyperswitch_connectors/src/connectors/shift4.rs+++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs@@ -1008,6 +1008,7 @@ impl ConnectorSpecifications for Shift4 {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => auth_type.is_three_ds() && request_data.is_card(),// No alternate flow for complete authorize and SetupMandateapi::CurrentFlowInfo::SetupMandate { .. }diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rsindex 3b3d6ee1c8..d1870660da 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs@@ -1458,6 +1458,7 @@ impl ConnectorSpecifications for Trustpay {api::CurrentFlowInfo::Authorize {auth_type: _,request_data,+ connector_meta_data: _,} => matches!(&request_data.payment_method_data,payment_method_data::PaymentMethodData::Wallet(_)diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rsindex 8a0233c6e5..0ae798a38f 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs@@ -1594,6 +1594,7 @@ impl ConnectorSpecifications for Worldpayxml {api::CurrentFlowInfo::Authorize {request_data,auth_type,+ connector_meta_data: _,} => {// Googlepay would require 3ds if cryptogram is not present which indicates it is Fpanauth_type == common_enums::AuthenticationType::ThreeDsdiff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex 76857a8d0e..c4c095464b 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -2976,7 +2976,6 @@ default_imp_for_pre_authenticate_steps!(connectors::Paysafe,connectors::Payme,connectors::Payone,- connectors::Paypal,connectors::Paystack,connectors::Paytm,connectors::Payu,diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 61f9ac7569..76fde13405 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -1396,6 +1396,8 @@ pub struct CashappQr {}pub struct PaypalRedirection {/// paypal's email addresspub email: Option<Email>,+ /// PayPal payer identifier disclosed by the connector response.+ pub payer_id: Option<Secret<String>>,}#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]@@ -2957,6 +2959,7 @@ impl From<api_models::payments::WalletData> for WalletData {api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {Self::PaypalRedirect(PaypalRedirection {email: paypal_redirect_data.email,+ payer_id: paypal_redirect_data.payer_id,})}api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {@@ -4195,6 +4198,7 @@ pub fn get_applepay_wallet_info(card_exp_year,// To be populated after connector responseauth_code: None,+ provider_details: None,email: None,}}@@ -4219,6 +4223,7 @@ pub fn get_googlepay_wallet_info(card_exp_year,// to be populated after connector responseauth_code: None,+ provider_details: None,email: None,}}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 4747fb704c..9e31a9da8a 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -401,6 +401,9 @@ impl PaymentMethodUpdate {} => bank_account_holder_name.is_some(),}}+ Some(payment_methods::PaymentMethodUpdateData::Wallet(wallet_update)) => {+ wallet_update.is_metadata_update()+ }None => false,}}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 668aeea72c..79110ddaeb 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -48,7 +48,7 @@ use serde_json::Value;use time::PrimitiveDateTime;use url::Url;-#[cfg(all(feature = "v1", feature = "olap"))]+#[cfg(feature = "v1")]use super::PaymentIntent;#[cfg(feature = "v2")]use crate::{@@ -1818,6 +1818,17 @@ impl PaymentAttempt {#[cfg(feature = "v1")]impl PaymentAttempt {+ /// Uses the attempt's applied future usage, falling back to the intent only when absent.+ pub fn get_setup_future_usage_with_fallback(+ &self,+ payment_intent: &PaymentIntent,+ ) -> Option<storage_enums::FutureUsage> {+ match self.setup_future_usage_applied {+ Some(setup_future_usage) => Some(setup_future_usage),+ None => payment_intent.setup_future_usage,+ }+ }+/// Capture method actually used with the connector for this attempt.////// `capture_method` keeps what the payment requested; when the profile's@@ -2096,6 +2107,7 @@ pub enum PaymentAttemptUpdate {updated_by: String,},ConfirmUpdate {+ setup_future_usage_applied: Option<storage_enums::FutureUsage>,net_amount: NetAmount,currency: storage_enums::Currency,status: storage_enums::AttemptStatus,@@ -2447,6 +2459,7 @@ impl PaymentAttemptUpdate {updated_by,},Self::ConfirmUpdate {+ setup_future_usage_applied,net_amount,currency,status,@@ -2491,6 +2504,7 @@ impl PaymentAttemptUpdate {applied_overrides,active_frm_id,} => DieselPaymentAttemptUpdate::ConfirmUpdate {+ setup_future_usage_applied,amount: net_amount.get_order_amount(),currency,status,diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 025b0c4b98..20a35c0a83 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -46,6 +46,8 @@ pub enum CurrentFlowInfo {auth_type: storage_enums::AuthenticationType,/// The payment authorize request datarequest_data: Box<PaymentsAuthorizeData>,+ /// The metadata configured at the merchant connector account level+ connector_meta_data: Option<pii::SecretSerdeValue>,},/// CompleteAuthorize flow informationCompleteAuthorize {diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rsindex 8c2b7f8664..089169d23d 100644--- a/crates/hyperswitch_domain_models/src/vault.rs+++ b/crates/hyperswitch_domain_models/src/vault.rs@@ -270,6 +270,7 @@ impl PaymentMethodVaultingData {card_exp_month: Some(expiry_month.clone()),card_exp_year: Some(expiry_year.clone()),auth_code: None,+ provider_details: None,email: None,},};diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex b7bbb0509f..23c4a40f7b 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -438,6 +438,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::PaymentMethodListInstallmentPlan,api_models::payment_methods::PaymentMethodListInstallmentAmountDetails,api_models::payment_methods::PaymentMethodDataWalletInfo,+ api_models::payment_methods::WalletProviderDetails,+ api_models::payment_methods::PaypalWalletInfo,api_models::payment_methods::ResponsePaymentMethodsEnabled,api_models::payment_methods::ResponsePaymentMethodTypes,api_models::payment_methods::PaymentExperienceTypes,@@ -629,6 +631,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::BankRedirectBilling,api_models::payments::BankRedirectBilling,api_models::payments::ConnectorMetadata,+ api_models::payments::PaypalConnectorMetadata,api_models::payments::ConnectorMetadataResponse,api_models::payments::SantanderData,api_models::payments::SantanderJourneyName,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 8cb791f0a0..ff8e509e17 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -328,6 +328,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::PaymentMethodDeleteResponse,api_models::payment_methods::PaymentMethodUpdate,api_models::payment_methods::PaymentMethodUpdateData,+ api_models::payment_methods::WalletDetailUpdate,api_models::payment_methods::CardDetailFromLocker,api_models::payment_methods::PaymentMethodCreateData,api_models::payment_methods::BankDebitDetail,@@ -350,6 +351,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payment_methods::PaymentMethodGetTokenDetailsResponse,api_models::payment_methods::RawCardWithNTDetails,api_models::payment_methods::PaymentMethodDataWalletInfo,+ api_models::payment_methods::WalletProviderDetails,+ api_models::payment_methods::PaypalWalletInfo,api_models::payment_methods::WalletPaymentMethodData,api_models::merchant_connector_webhook_management::Scope,api_models::merchant_connector_webhook_management::ScopeIdentifier,@@ -524,6 +527,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::BankRedirectBilling,api_models::payments::BankRedirectBilling,api_models::payments::ConnectorMetadata,+ api_models::payments::PaypalConnectorMetadata,api_models::payments::ConnectorMetadataResponse,api_models::payments::SantanderData,api_models::payments::SantanderJourneyName,diff --git a/crates/payment_methods/src/client.rs b/crates/payment_methods/src/client.rsindex a3c5cbfe0d..bf84df9798 100644--- a/crates/payment_methods/src/client.rs+++ b/crates/payment_methods/src/client.rs@@ -32,7 +32,7 @@ pub use session::{#[cfg(feature = "v1")]pub use update::{BankDebitDetailUpdate, CardDetailUpdate, PaymentMethodUpdateData, UpdatePaymentMethod,- UpdatePaymentMethodV1Payload, UpdatePaymentMethodV1Request,+ UpdatePaymentMethodV1Payload, UpdatePaymentMethodV1Request, WalletDetailUpdate,};use crate::configs::ModularPaymentMethodServiceUrl;diff --git a/crates/payment_methods/src/client/create.rs b/crates/payment_methods/src/client/create.rsindex 9af61d2191..4e97d0b48a 100644--- a/crates/payment_methods/src/client/create.rs+++ b/crates/payment_methods/src/client/create.rs@@ -244,6 +244,7 @@ impl TryFrom<PaymentMethodData> for PaymentMethodCreateData {card_exp_month: None,card_exp_year: None,auth_code: None,+ provider_details: None,email: None,};@@ -271,6 +272,7 @@ impl TryFrom<PaymentMethodData> for PaymentMethodCreateData {card_exp_month: None,card_exp_year: None,auth_code: None,+ provider_details: None,email: None,};@@ -293,6 +295,7 @@ impl TryFrom<PaymentMethodData> for PaymentMethodCreateData {) => Ok(Self::Wallet(WalletPaymentMethodData::PayPal(Box::new(payments::PaypalRedirection {email: paypal.email,+ payer_id: paypal.payer_id,},)))),_ => Err(MicroserviceClientError {diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rsindex 1e16fbb80f..6d9162d61b 100644--- a/crates/payment_methods/src/client/update.rs+++ b/crates/payment_methods/src/client/update.rs@@ -4,8 +4,10 @@ use api_models::payment_methods::NetworkTokenResponse;use common_enums::{PaymentMethod, PaymentMethodType, StorageType};use common_utils::{id_type,+ pii::Email,request::{Method, RequestContent},};+use hyperswitch_domain_models::payment_method_data::{PaymentMethodData, WalletData};use hyperswitch_interfaces::micro_service::{MicroserviceClientError, MicroserviceClientErrorKind};use hyperswitch_masking::Secret;use serde::{Deserialize, Serialize};@@ -65,6 +67,39 @@ pub struct ModularPMUpdateRequest {pub enum PaymentMethodUpdateData {Card(CardDetailUpdate),BankDebit(BankDebitDetailUpdate),+ Wallet(WalletDetailUpdate),+}++/// Wallet update payload for the modular service.+#[derive(Debug, Serialize, Clone)]+#[serde(rename_all = "snake_case")]+pub enum WalletDetailUpdate {+ /// Disclosed PayPal account details. Omitted fields retain their stored values.+ PayPal {+ /// PayPal payer email address.+ #[serde(skip_serializing_if = "Option::is_none")]+ email: Option<Email>,+ /// PayPal payer identifier.+ #[serde(skip_serializing_if = "Option::is_none")]+ payer_id: Option<Secret<String>>,+ },+}++impl PaymentMethodUpdateData {+ /// Convert connector-disclosed details into an update when wallet fields are present.+ pub fn from_connector_details(method_data: &PaymentMethodData) -> Option<Self> {+ match method_data {+ PaymentMethodData::Wallet(WalletData::PaypalRedirect(details))+ if details.email.is_some() || details.payer_id.is_some() =>+ {+ Some(Self::Wallet(WalletDetailUpdate::PayPal {+ email: details.email.clone(),+ payer_id: details.payer_id.clone(),+ }))+ }+ _ => None,+ }+ }}/// Card update payload for the modular service.diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex aa5757d633..537ad0c99a 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -536,6 +536,9 @@ pub mod superposition {/// `should_call_pm_modular_service`: defaults to `true` for all merchants and can be set to/// `false` for specific merchants to force the SDK to skip tokenization.pub const SHOULD_PERFORM_SDK_VAULTING: &str = "vaulting.should_perform_sdk_vaulting";+ /// Override applied future usage for merchant and payment method scoped contexts.+ pub const SHOULD_OVERRIDE_SETUP_FUTURE_USAGE_TO_OFF_SESSION: &str =+ "payments.should_override_setup_future_usage_to_off_session";/// dynamic fields configuration key for sdk configpub const DYNAMIC_FIELDS: &str = "dynamic_fields";/// payout sync tracker configuration keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex ef57c8ff10..a61900f0fa 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -150,6 +150,20 @@ macro_rules! config {};}+/// Superposition-only override, scoped by processor merchant and payment method.+pub struct ShouldOverrideSetupFutureUsageToOffSession;++impl superposition::Config for ShouldOverrideSetupFutureUsageToOffSession {+ type Output = bool;+ type TargetingKey = id_type::MerchantId;+ const SUPERPOSITION_KEY: &'static str =+ superposition_consts::SHOULD_OVERRIDE_SETUP_FUTURE_USAGE_TO_OFF_SESSION;++ fn default_value() -> Self::Output {+ false+ }+}+config! {superposition_key = REQUIRES_CVV,output = bool,diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rsindex f40fea0df6..bc6975e20f 100644--- a/crates/router/src/core/connector_validation.rs+++ b/crates/router/src/core/connector_validation.rs@@ -492,6 +492,9 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {}api_enums::Connector::Paypal => {paypal::transformers::PaypalAuthType::try_from(self.auth_type)?;+ paypal::transformers::PaypalConnectorMetadataObject::try_from(+ self.connector_meta_data,+ )?;Ok(())}api_enums::Connector::Paysafe => {diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex b30936e06b..6ba432b832 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1125,10 +1125,10 @@ pub async fn retrieve_payment_method_with_token(.unwrap_or_default()}- storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {- payment_method: None,- payment_method_data: None,- payment_method_id: None,+ storage::PaymentTokenData::WalletToken(wallet_token) => storage::PaymentMethodDataWithId {+ payment_method: Some(enums::PaymentMethod::Wallet),+ payment_method_data: Some(domain::PaymentMethodData::MandatePayment),+ payment_method_id: Some(wallet_token.payment_method_id.clone()),},storage::PaymentTokenData::BankDebit(bank_debit) => {let customer_id = payment_intent.customer_id.as_ref().ok_or(@@ -4417,6 +4417,7 @@ impl PaymentMethodExt for payment_methods::PaymentMethodCreateData {card_exp_month: None,card_exp_year: None,auth_code: None,+ provider_details: None,email: data.email,},))@@ -5316,6 +5317,10 @@ fn build_payment_methods_additional_data_for_create(.or(vaulted_wallet_info.card_exp_year),auth_code: wallet_info.auth_code.or(vaulted_wallet_info.auth_code),email: wallet_info.email.or(vaulted_wallet_info.email),+ provider_details: payment_methods::WalletProviderDetails::merge(+ wallet_info.provider_details,+ vaulted_wallet_info.provider_details,+ ),},)}@@ -8524,6 +8529,21 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {fn validate(&self) -> RouterResult<()> {let payment_method = &self.payment_method;+ let is_paypal_payment_method = payment_method.payment_method_type+ == Some(enums::PaymentMethod::Wallet)+ && payment_method.payment_method_subtype == Some(enums::PaymentMethodType::Paypal);+ if matches!(+ self.request.payment_method_data,+ Some(payment_methods::PaymentMethodUpdateData::Wallet(+ payment_methods::WalletDetailUpdate::PayPal { .. }+ ))+ ) && !is_paypal_payment_method+ {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "PayPal wallet updates require a saved PayPal payment method".to_string(),+ }+ .into());+ }when(payment_method.status == enums::PaymentMethodStatus::Redacted,|| {@@ -8534,7 +8554,6 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {)?;Ok(())}-fn is_pm_metadata_changed_for_same_fingerprint(&self,vault_request_data: &domain::PaymentMethodVaultingData,@@ -8609,55 +8628,73 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {Option<domain::PaymentMethodVaultingData>,Option<pm_types::AddVaultResponse>,)> {- if !self.request.is_payment_method_metadata_update() {- return Ok((None, None));- }-- let pmd: domain::PaymentMethodVaultingData =- Box::pin(vault::retrieve_payment_method_from_vault(- self.state,- self.platform,- self.profile,- &self.payment_method,- ))- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve payment method from vault")?- .data;+ match (+ self.request.is_payment_method_metadata_update(),+ &self.request.payment_method_data,+ ) {+ // Wallet metadata is updated directly in the database without vault operations.+ (+ true | false,+ Some(payment_methods::PaymentMethodUpdateData::Wallet(+ payment_methods::WalletDetailUpdate::PayPal { .. },+ )),+ ) => Ok((None, None)),+ (true, Some(payment_methods::PaymentMethodUpdateData::Card(..)))+ | (true, Some(payment_methods::PaymentMethodUpdateData::BankDebit(..))) => {+ let pmd: domain::PaymentMethodVaultingData =+ Box::pin(vault::retrieve_payment_method_from_vault(+ self.state,+ self.platform,+ self.profile,+ &self.payment_method,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve payment method from vault")?+ .data;- let vault_request_data = self- .request- .payment_method_data- .clone()- .map(|payment_method_data| {- pm_transforms::generate_pm_vaulting_req_from_update_request(- pmd,- payment_method_data,- )- })- .transpose()- .change_context(errors::ApiErrorResponse::NotSupported {- message: "Payment method type not supported for update".to_string(),- })?- .ok_or(errors::ApiErrorResponse::MissingRequiredField {- field_name: "payment_method_data".into(),- })?;+ let vault_request_data = self+ .request+ .payment_method_data+ .clone()+ .map(|payment_method_data| {+ pm_transforms::generate_pm_vaulting_req_from_update_request(+ pmd,+ payment_method_data,+ )+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::NotSupported {+ message: "Payment method type not supported for update".to_string(),+ })?+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_method_data".into(),+ })?;- let is_metadata_changed_for_same_fingerprint =- self.is_pm_metadata_changed_for_same_fingerprint(&vault_request_data);+ let is_metadata_changed_for_same_fingerprint =+ self.is_pm_metadata_changed_for_same_fingerprint(&vault_request_data);- let locker = LockerType::from_micro_services_config(&self.state.conf.micro_services);+ let locker =+ LockerType::from_micro_services_config(&self.state.conf.micro_services);- locker- .validate_locker_operations_for_update(- self.state,- self.platform,- self.profile,- &self.payment_method,- &vault_request_data,- is_metadata_changed_for_same_fingerprint,+ locker+ .validate_locker_operations_for_update(+ self.state,+ self.platform,+ self.profile,+ &self.payment_method,+ &vault_request_data,+ is_metadata_changed_for_same_fingerprint,+ )+ .await+ }+ (+ false,+ Some(payment_methods::PaymentMethodUpdateData::Card(..))+ | Some(payment_methods::PaymentMethodUpdateData::BankDebit(..)),)- .await+ | (true | false, None) => Ok((None, None)),+ }}pub async fn update_payment_method_if_required(@@ -8769,10 +8806,45 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {.attach_printable("Failed to persist the promoted payment method in db")?}false => {- let pm_update = create_pm_additional_data_update(- vault_request_data+ let payment_methods_data = match self.request.payment_method_data.clone() {+ Some(payment_methods::PaymentMethodUpdateData::Wallet(update))+ if update.is_metadata_update() =>+ {+ let saved = self+ .payment_method+ .payment_method_data+ .clone()+ .map(|data| data.into_inner());+ let wallet_info = match saved {+ Some(domain::PaymentMethodsData::WalletDetails(info)) => info,+ None => payment_methods::PaymentMethodDataWalletInfo {+ last4: None,+ card_network: None,+ card_type: None,+ card_exp_month: None,+ card_exp_year: None,+ auth_code: None,+ email: None,+ provider_details: None,+ },+ _ => {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Saved payment method data is not wallet data"+ .to_string(),+ }+ .into());+ }+ };+ Some(domain::PaymentMethodsData::WalletDetails(+ update.apply_to(wallet_info),+ ))+ }+ _ => vault_request_data.as_ref()- .map(|vault_request_data| vault_request_data.get_payment_methods_data()),+ .map(|data| data.get_payment_methods_data()),+ };+ let pm_update = create_pm_additional_data_update(+ payment_methods_data,self.state,self.platform.get_provider().get_key_store(),vault_respdiff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 186f3e0f8e..11e1e8260d 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -13,8 +13,10 @@ use ::payment_methods::{use api_models::admin::PaymentMethodsEnabled;#[cfg(feature = "v1")]use api_models::payment_methods::{- PaymentMethodListIntentDataInput, PaymentMethodSubtypeSpecificDataForClient,- ResponsePaymentMethodsEnabledForClient,+ PaymentMethodDataWalletInfo, PaymentMethodListIntentDataInput,+ PaymentMethodSubtypeSpecificDataForClient, PaypalWalletInfo,+ ResponsePaymentMethodsEnabledForClient, WalletPaymentMethodDataForClient,+ WalletProviderDetails,};use api_models::{enums as api_enums,@@ -3091,18 +3093,111 @@ pub async fn update_customer_payment_method(}#[cfg(feature = "v1")]+pub(crate) fn get_paypal_wallet_info(+ connector_response: Option<&hyperswitch_domain_models::router_data::ConnectorResponseData>,+) -> Option<PaymentMethodDataWalletInfo> {+ match connector_response?.additional_payment_method_data.as_ref()? {+ hyperswitch_domain_models::router_data::AdditionalPaymentMethodConnectorResponse::Paypal {+ email,+ payer_id,+ } if email.is_some() || payer_id.is_some() => Some(PaymentMethodDataWalletInfo {+ last4: None,+ card_network: None,+ card_type: None,+ card_exp_month: None,+ card_exp_year: None,+ auth_code: None,+ email: email.clone(),+ provider_details: Some(WalletProviderDetails::PayPal(PaypalWalletInfo {+ payer_id: payer_id.clone(),+ })),+ }),+ _ => None,+ }+}++/// Prepares merged PayPal wallet data without fetching or updating the PM.+#[cfg(feature = "v1")]+pub async fn prepare_saved_wallet_data_from_connector_response(+ state: &routes::SessionState,+ platform: &domain::Platform,+ pm: &domain::PaymentMethod,+ connector_disclosed_details: &domain::PaypalRedirection,+) -> errors::RouterResult<Option<Encryption>> {+ match pm.get_payment_method_subtype() {+ Some(enums::PaymentMethodType::Paypal) => {+ match (+ connector_disclosed_details.email.as_ref(),+ connector_disclosed_details.payer_id.as_ref(),+ ) {+ (None, None) => Ok(None),+ (email, payer_id) => {+ let mut wallet_info = PaymentMethodDataWalletInfo {+ last4: None,+ card_network: None,+ card_type: None,+ card_exp_month: None,+ card_exp_year: None,+ auth_code: None,+ email: email.cloned(),+ provider_details: Some(WalletProviderDetails::PayPal(PaypalWalletInfo {+ payer_id: payer_id.cloned(),+ })),+ };+ let saved_data = pm+ .payment_method_data+ .as_ref()+ .map(|data| {+ data.get_inner()+ .peek()+ .clone()+ .parse_value::<domain::PaymentMethodsData>("PaymentMethodsData")+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse saved PayPal wallet data")?;++ if let Some(domain::PaymentMethodsData::WalletDetails(mut saved_wallet)) =+ saved_data+ {+ saved_wallet.email = wallet_info.email.or(saved_wallet.email);+ saved_wallet.provider_details = WalletProviderDetails::merge(+ wallet_info.provider_details,+ saved_wallet.provider_details,+ );+ wallet_info = saved_wallet;+ }++ let encrypted_data = core_utils::create_encrypted_data(+ &state.into(),+ platform.get_provider().get_key_store(),+ domain::PaymentMethodsData::WalletDetails(wallet_info),+ type_name!(payment_method::PaymentMethod),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt PayPal wallet data")?;++ Ok(Some(encrypted_data.into()))+ }+ }+ }+ Some(..) | None => Ok(None),+ }+}++#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]pub async fn prepare_payment_method_update_from_connector_details(state: &routes::SessionState,platform: &domain::Platform,pm: &domain::PaymentMethod,merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,- connector_disclosed_details: &hyperswitch_domain_models::payment_method_data::PaymentMethodData,+ connector_disclosed_details: &domain::PaymentMethodData,business_profile: &Profile,-) -> errors::CustomResult<storage::PaymentMethodUpdate, errors::ApiErrorResponse> {+) -> errors::RouterResult<storage::PaymentMethodUpdate> {match connector_disclosed_details {- hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(- bank_redirect_update,- ) => {+ domain::PaymentMethodData::BankRedirect(bank_redirect_update) => {prepare_bank_redirect_payment_method_update(state,platform,@@ -3113,6 +3208,33 @@ pub async fn prepare_payment_method_update_from_connector_details().await}+ domain::PaymentMethodData::Wallet(domain::WalletData::PaypalRedirect(details)) => {+ let payment_method_data =+ prepare_saved_wallet_data_from_connector_response(state, platform, pm, details)+ .await?;++ Ok(storage::PaymentMethodUpdate::AdditionalDataUpdate {+ payment_method_data,+ last_used_at: Some(common_utils::date_time::now()),+ last_modified_by: platform+ .get_initiator()+ .and_then(|initiator| initiator.to_created_by())+ .map(|initiator| initiator.to_string()),+ status: None,+ locker_id: None,+ locker_fingerprint_id: None,+ payment_method: None,+ payment_method_type: None,+ payment_method_issuer: None,+ network_token_requestor_reference_id: None,+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ metadata: None,+ connector_mandate_details: None,+ network_tokenization_data: None,+ connector_payment_method_details: Box::new(None),+ })+ }_ => Err(report!(errors::ApiErrorResponse::NotImplemented {message: errors::NotImplementedMessage::Reason("Payment method update from connector disclosed details".to_string(),@@ -6252,6 +6374,43 @@ fn filter_latest_wallet_methods(result}+/// Returns saved wallet display details for PayPal, the currently supported wallet subtype.+/// Other wallet subtypes and non-wallet payment method data return no display details.+#[cfg(feature = "v1")]+fn get_saved_wallet_details_for_client(+ pm: &domain::PaymentMethod,+) -> errors::RouterResult<Option<WalletPaymentMethodDataForClient>> {+ let payment_method_data = pm+ .payment_method_data+ .as_ref()+ .map(|data| {+ data.get_inner()+ .peek()+ .clone()+ .parse_value::<domain::PaymentMethodsData>("PaymentMethodsData")+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to parse saved wallet data")?;++ Ok(match payment_method_data {+ Some(domain::PaymentMethodsData::WalletDetails(info))+ if pm.get_payment_method_subtype() == Some(enums::PaymentMethodType::Paypal) =>+ {+ Some(WalletPaymentMethodDataForClient::PayPal(Box::new(+ info.into(),+ )))+ }+ Some(domain::PaymentMethodsData::WalletDetails(..))+ | Some(domain::PaymentMethodsData::Card(..))+ | Some(domain::PaymentMethodsData::BankDetails(..))+ | Some(domain::PaymentMethodsData::NetworkToken(..))+ | Some(domain::PaymentMethodsData::BankDebit(..))+ | Some(domain::PaymentMethodsData::BankRedirect(..))+ | None => None,+ })+}+#[cfg(feature = "v1")]pub async fn list_customer_payment_method(state: &routes::SessionState,@@ -6433,6 +6592,7 @@ pub async fn list_customer_payment_method(};// Need validation for enabled payment method ,querying MCAlet pma = api::CustomerPaymentMethod {+ wallets: get_saved_wallet_details_for_client(&pm)?,payment_token: parent_payment_method_token.to_owned(),payment_method_id: pm.payment_method_id.clone(),customer_id: pm.customer_id.clone().get_required_value("customer_id")?,diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex 2d1b9d2dc9..d87049bf0e 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -118,6 +118,7 @@ fn to_client_pm(pm: CustomerPaymentMethod) -> CustomerPaymentMethodForClient {let payment_method_data = pm.card.map(|card| CustomerPaymentMethodDataForClient::Card(Box::new(card)))+ .or_else(|| pm.wallets.map(CustomerPaymentMethodDataForClient::Wallet)).or_else(|| bank_redirect_data_for_client(pm.payment_method, pm.bank));CustomerPaymentMethodForClient {diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex ed0dc00b90..bc7fecb52c 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -721,7 +721,7 @@ pub fn generate_payment_method_response(}Some(common_enums::PaymentMethodType::Paypal) => Some(api::PaymentMethodResponseData::Wallet(WalletPaymentMethodData::PayPal(- Box::new(api_models::payments::PaypalRedirection { email: info.email }),+ Box::new(api_models::payments::PaypalRedirection::from(info)),)),),_ => None,@@ -1043,7 +1043,7 @@ implapi_enums::PaymentMethodType::Paypal => {Some(api_models::payment_methods::PaymentMethodListData::Wallet(WalletPaymentMethodData::PayPal(Box::new(- api_models::payments::PaypalRedirection { email: info.email },+ api_models::payments::PaypalRedirection::from(info),)),))}@@ -1152,7 +1152,7 @@ implapi_enums::PaymentMethodType::Paypal => {Some(api_models::payment_methods::PaymentMethodListData::Wallet(WalletPaymentMethodData::PayPal(Box::new(- api_models::payments::PaypalRedirection { email: info.email },+ api_models::payments::PaypalRedirection::from(info),)),))}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 515367fdd5..6c995cac6a 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -743,6 +743,7 @@ async fn restore_pre_call_state<F, D>(applied_offer_details: attempt.applied_offer_details.clone(),applied_overrides: attempt.applied_overrides.clone(),active_frm_id: attempt.active_frm_id.clone(),+ setup_future_usage_applied: attempt.setup_future_usage_applied,};let intent_update = storage::PaymentIntentUpdate::PGStatusUpdate {@@ -12543,76 +12544,16 @@ whereSome(api::MandateTransactionType::RecurringMandateTransaction),)| (None, true, None, Some(true), _) => {- if !has_token_data {- logger::debug!("euclid_routing: modular fallback token-MIT path selected");- }- logger::debug!("euclid_routing: performing routing for token-based MIT flow");- let payment_method_info = payment_data- .get_payment_method_info()- .get_required_value("payment_method_info")?- .clone();- let payment_method_data = payment_data.get_payment_method_data().cloned();- let retryable_connectors =- join_all(connectors.into_iter().map(|connector_routing_data| {- let payment_method = payment_method_info.clone();- let payment_method_data = payment_method_data.clone();- async move {- let action_types = get_all_action_types(- state,- is_payment_method_modular_allowed,- is_connector_agnostic_mit_enabled,- is_network_tokenization_enabled,- &payment_method.clone(),- payment_method_data.as_ref(),- connector_routing_data.connector_data.clone(),- )- .await;-- action_types- .into_iter()- .map(|action_type| api::ConnectorRoutingData {- connector_data: connector_routing_data.connector_data.clone(),- action_type: Some(action_type),- network: connector_routing_data.network.clone(),- })- .collect::<Vec<_>>()- }- }))- .await- .into_iter()- .flatten()- .collect::<Vec<_>>();-- let chosen_connector_routing_data = retryable_connectors- .first()- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)- .attach_printable("no eligible connector found for token-based MIT payment")?;-- let mandate_reference_id = get_mandate_reference_id(- chosen_connector_routing_data.action_type.clone(),- chosen_connector_routing_data.clone(),+ route_token_based_mandate_payment(+ state,payment_data,- &payment_method_info,- )?;-- routing_data.routed_through = Some(- chosen_connector_routing_data- .connector_data- .connector_name- .to_string(),- );-- routing_data.merchant_connector_id.clone_from(- &chosen_connector_routing_data- .connector_data- .merchant_connector_id,- );-- payment_data.set_mandate_id(mandates::MandateIds {- mandate_id: None,- mandate_reference_id,- });- Ok(ConnectorCallType::Retryable(retryable_connectors))+ routing_data,+ connectors,+ is_payment_method_modular_allowed,+ is_connector_agnostic_mit_enabled,+ is_network_tokenization_enabled,+ )+ .await}(None,@@ -12644,25 +12585,133 @@ where}}_ => {- helpers::override_setup_future_usage_to_on_session(state.store.as_ref(), payment_data)- .await?;+ // Saved wallets require a connector mandate even when off_session is not set.+ // Modular PayPal uses the fetched PM's mandate details without legacy token data.+ let is_saved_paypal_payment = has_token_data+ && payment_data.get_payment_attempt().payment_method+ == Some(storage_enums::PaymentMethod::Wallet)+ && payment_data.get_payment_attempt().payment_method_type+ == Some(storage_enums::PaymentMethodType::Paypal);+ if is_saved_paypal_payment {+ logger::debug!(+ "euclid_routing: connector mandate routing selected for saved wallet payment"+ );+ route_token_based_mandate_payment(+ state,+ payment_data,+ routing_data,+ connectors,+ is_payment_method_modular_allowed,+ is_connector_agnostic_mit_enabled,+ is_network_tokenization_enabled,+ )+ .await+ } else {+ helpers::override_setup_feature_usage(state, payment_data).await?;- let first_choice = connectors- .first()- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)- .attach_printable("no eligible connector found for payment")?- .clone();+ let first_choice = connectors+ .first()+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)+ .attach_printable("no eligible connector found for payment")?+ .clone();- routing_data.routed_through =- Some(first_choice.connector_data.connector_name.to_string());+ routing_data.routed_through =+ Some(first_choice.connector_data.connector_name.to_string());- routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id;+ routing_data.merchant_connector_id =+ first_choice.connector_data.merchant_connector_id;- Ok(ConnectorCallType::Retryable(connectors))+ Ok(ConnectorCallType::Retryable(connectors))+ }}}}+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn route_token_based_mandate_payment<F: Clone, D>(+ state: &SessionState,+ payment_data: &mut D,+ routing_data: &mut storage::RoutingData,+ connectors: Vec<api::ConnectorRoutingData>,+ is_payment_method_modular_allowed: bool,+ is_connector_agnostic_mit_enabled: Option<bool>,+ is_network_tokenization_enabled: bool,+) -> RouterResult<ConnectorCallType>+where+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,+{+ if payment_data.get_token_data().is_none() {+ logger::debug!("euclid_routing: modular fallback token-MIT path selected");+ }+ logger::debug!("euclid_routing: performing routing for token-based MIT flow");+ let payment_method_info = payment_data+ .get_payment_method_info()+ .get_required_value("payment_method_info")?+ .clone();+ let payment_method_data = payment_data.get_payment_method_data().cloned();+ let retryable_connectors = join_all(connectors.into_iter().map(|connector_routing_data| {+ let payment_method = payment_method_info.clone();+ let payment_method_data = payment_method_data.clone();+ async move {+ let action_types = get_all_action_types(+ state,+ is_payment_method_modular_allowed,+ is_connector_agnostic_mit_enabled,+ is_network_tokenization_enabled,+ &payment_method.clone(),+ payment_method_data.as_ref(),+ connector_routing_data.connector_data.clone(),+ )+ .await;++ action_types+ .into_iter()+ .map(|action_type| api::ConnectorRoutingData {+ connector_data: connector_routing_data.connector_data.clone(),+ action_type: Some(action_type),+ network: connector_routing_data.network.clone(),+ })+ .collect::<Vec<_>>()+ }+ }))+ .await+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();++ let chosen_connector_routing_data = retryable_connectors+ .first()+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)+ .attach_printable("no eligible connector found for token-based MIT payment")?;++ let mandate_reference_id = get_mandate_reference_id(+ chosen_connector_routing_data.action_type.clone(),+ chosen_connector_routing_data.clone(),+ payment_data,+ &payment_method_info,+ )?;++ routing_data.routed_through = Some(+ chosen_connector_routing_data+ .connector_data+ .connector_name+ .to_string(),+ );++ routing_data.merchant_connector_id.clone_from(+ &chosen_connector_routing_data+ .connector_data+ .merchant_connector_id,+ );++ payment_data.set_mandate_id(mandates::MandateIds {+ mandate_id: None,+ mandate_reference_id,+ });+ Ok(ConnectorCallType::Retryable(retryable_connectors))+}+#[cfg(feature = "v1")]pub fn get_mandate_reference_id<F: Clone, D>(action_type: Option<ActionType>,@@ -15945,6 +15994,12 @@ pub trait OperationSessionSetters<F> {setup_future_usage: storage_enums::FutureUsage,);+ #[cfg(feature = "v1")]+ fn set_setup_future_usage_applied_in_payment_attempt(+ &mut self,+ setup_future_usage: storage_enums::FutureUsage,+ );+#[cfg(feature = "v1")]fn set_straight_through_algorithm_in_payment_attempt(&mut self,@@ -16319,6 +16374,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {self.mandate_id = Some(mandate_id);}+ #[cfg(feature = "v1")]+ fn set_setup_future_usage_applied_in_payment_attempt(+ &mut self,+ setup_future_usage: storage_enums::FutureUsage,+ ) {+ self.payment_attempt.setup_future_usage_applied = Some(setup_future_usage);+ }+#[cfg(feature = "v1")]fn set_setup_future_usage_in_payment_intent(&mut self,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex cd4884ad39..476f1563a7 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -218,6 +218,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuSome(api_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),})}@@ -305,6 +306,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -416,6 +418,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAulet current_flow = Some(api_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),});Box::pin(access_token::add_access_token(state,@@ -440,6 +443,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAulet current_flow = api_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),};self.session_token = session_token::add_session_token_if_needed(self,@@ -486,6 +490,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -587,6 +592,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu_ => false,},api_models::enums::Connector::Shift4 => true,+ api_models::enums::Connector::Paypal => true,// Nuvei: never run the next leg after a failed initPaymentapi_models::enums::Connector::Nuvei => authorize_router_data.response.is_ok(),// Paysafe card + 3DS: PreAuthenticate mints the handle. When Paysafe returns no ACS@@ -636,6 +642,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -784,6 +791,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -846,6 +854,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -1003,6 +1012,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},) {logger::info!(@@ -1074,6 +1084,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuapi_interface::CurrentFlowInfo::Authorize {auth_type: self.auth_type,request_data: Box::new(self.request.clone()),+ connector_meta_data: self.connector_meta_data.clone(),},);if (connectordiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex d8b5b92a5b..3829738d2e 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -36,6 +36,8 @@ use common_utils::{use diesel_models::enums;// TODO : Evaluate all the helper functions ()use error_stack::{report, ResultExt};+#[cfg(feature = "v1")]+use external_services::superposition::Config;use futures::future::Either;#[cfg(feature = "v1")]use hyperswitch_domain_models::payments::payment_intent::CustomerData;@@ -80,6 +82,7 @@ use super::{use crate::core::mandate::helpers::MandateGenericData;#[cfg(feature = "v1")]use crate::core::{+ configs::dimension_config::ShouldOverrideSetupFutureUsageToOffSession,payments::{OperationSessionGetters, OperationSessionSetters},utils as core_utils,};@@ -9541,6 +9544,55 @@ where)}+/// Override the attempt's applied future usage during routing, preserving the intent's usage.+/// Missing or unavailable configuration+/// leaves the usage unchanged. Direct connector mandate support checks still run afterward.+#[cfg(feature = "v1")]+pub async fn override_setup_future_usage_to_off_session<F, D>(+ state: &SessionState,+ payment_data: &mut D,+) where+ F: Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,+{+ let payment_attempt = payment_data.get_payment_attempt();+ if let Some(payment_method) = payment_attempt.get_payment_method() {+ let merchant_id = &payment_data.get_payment_intent().processor_merchant_id;+ let context = setup_future_usage_override_context(+ merchant_id,+ payment_method,+ payment_attempt.get_payment_method_type(),+ );+ if ShouldOverrideSetupFutureUsageToOffSession::fetch(+ state.superposition_service.as_ref(),+ Some(&context),+ Some(merchant_id),+ )+ .await+ .unwrap_or_else(|_| ShouldOverrideSetupFutureUsageToOffSession::default_value())+ {+ logger::debug!("Override setup_future_usage_applied to off_session based on Superposition configuration");+ payment_data+ .set_setup_future_usage_applied_in_payment_attempt(enums::FutureUsage::OffSession);+ }+ }+}++fn setup_future_usage_override_context(+ merchant_id: &id_type::MerchantId,+ payment_method: enums::PaymentMethod,+ payment_method_type: Option<enums::PaymentMethodType>,+) -> external_services::superposition::ConfigContext {+ // Payment method dimensions use PascalCase values in the Superposition seed schema.+ let mut context = external_services::superposition::ConfigContext::new()+ .with("processor_merchant_id", merchant_id.get_string_repr())+ .with("payment_method", &format!("{payment_method:?}"));+ if let Some(payment_method_type) = payment_method_type {+ context = context.with("payment_method_type", &format!("{payment_method_type:?}"));+ }+ context+}+pub async fn config_skip_saving_wallet_at_connector(db: &dyn StorageInterface,merchant_id: &id_type::MerchantId,@@ -9564,6 +9616,20 @@ pub async fn config_skip_saving_wallet_at_connector(})}+/// Apply the off-session override before the merchant's on-session override.+#[cfg(feature = "v1")]+pub async fn override_setup_feature_usage<F, D>(+ state: &SessionState,+ payment_data: &mut D,+) -> CustomResult<(), errors::ApiErrorResponse>+where+ F: Clone,+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,+{+ override_setup_future_usage_to_off_session(state, payment_data).await;+ override_setup_future_usage_to_on_session(state.store.as_ref(), payment_data).await+}+#[cfg(feature = "v1")]pub async fn override_setup_future_usage_to_on_session<F, D>(db: &dyn StorageInterface,@@ -9573,7 +9639,10 @@ whereF: Clone,D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,{- if payment_data.get_payment_intent().setup_future_usage == Some(enums::FutureUsage::OffSession)+ if payment_data+ .get_payment_attempt()+ .get_setup_future_usage_with_fallback(payment_data.get_payment_intent())+ == Some(enums::FutureUsage::OffSession){let skip_saving_wallet_at_connector_optional = config_skip_saving_wallet_at_connector(db,@@ -9586,9 +9655,10 @@ wherepayment_data.get_payment_attempt().get_payment_method_type(){if skip_saving_wallet_at_connector.contains(&payment_method_type) {- logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate.");- payment_data- .set_setup_future_usage_in_payment_intent(enums::FutureUsage::OnSession);+ logger::debug!("Override setup_future_usage_applied from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate.");+ payment_data.set_setup_future_usage_applied_in_payment_attempt(+ enums::FutureUsage::OnSession,+ );}}};diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex f8201bd70c..8ba7d38a2c 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -398,11 +398,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>// An attempt created without setup_future_usage (create with confirm=false, then confirm// with off_session) picks it up from the intent, as new retry attempts do. Connector- // requests already use `setup_future_usage_applied.or(intent)`; this lets decisions made+ // requests use the same applied-usage fallback helper; this lets decisions made// before the connector call, such as connector customer creation, see the same value.- payment_attempt.setup_future_usage_applied = payment_attempt- .setup_future_usage_applied- .or(payment_intent.setup_future_usage);+ payment_attempt.setup_future_usage_applied =+ payment_attempt.get_setup_future_usage_with_fallback(&payment_intent);payment_intent.psd2_sca_exemption_type = request.psd2_sca_exemption_type@@ -702,7 +701,13 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>)});let (token_data, payment_method_info) = if is_modular_payment_method_flow {- (None, payment_method_info)+ // Saved wallets still need their token context for connector mandate routing.+ // Card tokens continue to be handled using the modular raw payment data.+ (+ prefetched_token_data+ .filter(|data| matches!(data, storage::PaymentTokenData::WalletToken(_))),+ payment_method_info,+ )} else {self.resolve_legacy_token_payment_method_context(state,@@ -1359,8 +1364,12 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for)?;if let Some(payment_method_ref) = self.get_payment_method_reference(req) {- let payment_method_ref_to_use = match req.payment_token.as_deref() {- Some(payment_token) if payment_token == payment_method_ref => {+ let (payment_method_ref_to_use, wallet_token_data) = match req+ .payment_token+ .as_deref()+ .filter(|payment_token| *payment_token == payment_method_ref)+ {+ Some(payment_token) => {// Best-effort: resolve the token to its stored payment_method_id. A// self-hosted vault token minted by the modular PM service is not present in// the legacy redis token store (different key), so a miss/error here is not@@ -1368,7 +1377,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for// resolve it, instead of failing the payment with "token invalid or expired".match helpers::retrieve_payment_token_data(state,- payment_method_ref.to_string(),+ payment_token.to_string(),req.payment_method,).await@@ -1376,36 +1385,56 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forOk(storage::PaymentTokenData::Permanent(card_token_data)| storage::PaymentTokenData::PermanentCard(card_token_data),- ) => card_token_data- .payment_method_id- .as_deref()- .unwrap_or(payment_method_ref)- .to_owned(),- Ok(_) => payment_method_ref.to_owned(),+ ) => (+ card_token_data+ .payment_method_id+ .as_deref()+ .unwrap_or(payment_method_ref)+ .to_owned(),+ None,+ ),+ Ok(storage::PaymentTokenData::WalletToken(data)) => (+ data.payment_method_id.clone(),+ Some(storage::PaymentTokenData::WalletToken(data)),+ ),+ Ok(+ storage::PaymentTokenData::Temporary(..)+ | storage::PaymentTokenData::TemporaryGeneric(..)+ | storage::PaymentTokenData::AuthBankDebit(..)+ | storage::PaymentTokenData::BankDebit(..)+ | storage::PaymentTokenData::BankRedirect(..),+ ) => (payment_method_ref.to_owned(), None),Err(err) => {logger::warn!(?err,payment_method_ref,"Failed to fetch payment token from payment server; falling back to PM Modular Service");- payment_method_ref.to_owned()+ (payment_method_ref.to_owned(), None)}}}- _ => payment_method_ref.to_owned(),+ None => (payment_method_ref.to_owned(), None),};logger::debug!("Organization is enabled for modular service, fetching payment method from PM Modular Service");- self.fetch_payment_method_from_modular_service(- state,- req,- platform,- profile_id,- &payment_method_ref_to_use,- )- .await?+ let fetch_data = self+ .fetch_payment_method_from_modular_service(+ state,+ req,+ platform,+ profile_id,+ &payment_method_ref_to_use,+ )+ .await?;+ // Keep saved-wallet context so pre-routing cannot bypass connector mandate+ // selection. PayPal's vault token is stored on the fetched payment method.+ operations::PaymentMethodFetchData {+ token_data: wallet_token_data,+ ..fetch_data+ }} else {operations::PaymentMethodFetchData::default()}@@ -1457,14 +1486,18 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forlogger::debug!("Payment method version is V2, fetching payment method from PM Modular Service");- self.fetch_payment_method_from_modular_service(- state,- req,- platform,- profile_id,- payment_method.get_id(),- )- .await?+ let mut fetch_data = self+ .fetch_payment_method_from_modular_service(+ state,+ req,+ platform,+ profile_id,+ payment_method.get_id(),+ )+ .await?;+ fetch_data.token_data = token_data+ .filter(|data| matches!(data, storage::PaymentTokenData::WalletToken(_)));+ fetch_data}Some(payment_method) => {// Reached when the modular flag is off OR the payment method's timestamps@@ -2922,6 +2955,9 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> form_db.update_payment_attempt_with_attempt_id(m_payment_data_payment_attempt,storage::PaymentAttemptUpdate::ConfirmUpdate {+ setup_future_usage_applied: payment_data+ .payment_attempt+ .setup_future_usage_applied,currency: payment_data.currency,status: attempt_status,payment_method,diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rsindex 1f95c9f41a..d2c2e448e2 100644--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs@@ -630,6 +630,9 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>.update_payment_attempt_with_attempt_id(payment_data.payment_attempt.clone(),storage::PaymentAttemptUpdate::ConfirmUpdate {+ setup_future_usage_applied: payment_data+ .payment_attempt+ .setup_future_usage_applied,currency: payment_data.currency,status: attempt_status,payment_method,diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex ab661e9dec..129e8c5d3d 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -293,9 +293,13 @@ where(None, None)};- // #2 - Fill payment method data for cards- let payment_method_data =- request_payment_method_data.and_then(|method_data| match method_data {+ // #2 - Fill request details, falling back to connector-disclosed PayPal data.+ let wallet_update = resp+ .connector_returned_payment_method_details+ .as_ref()+ .and_then(PaymentMethodUpdateData::from_connector_details);+ let payment_method_data = request_payment_method_data+ .and_then(|method_data| match method_data {domain::PaymentMethodData::CardToken(card) => {Some(PaymentMethodUpdateData::Card(CardDetailUpdate {card_holder_name: card.card_holder_name.clone(),@@ -314,7 +318,8 @@ where},)),_ => None,- });+ })+ .or(wallet_update);let acknowledgement_status =Some(common_enums::AcknowledgementStatus::Authenticated);@@ -511,7 +516,7 @@ where.and_then(|record| record.connector_mandate_status);let is_off_session = matches!(- payment_intent.setup_future_usage,+ payment_attempt.get_setup_future_usage_with_fallback(payment_intent),Some(common_enums::FutureUsage::OffSession));@@ -3973,7 +3978,7 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(storage_scheme: enums::MerchantStorageScheme,organization_id: &common_utils::id_type::OrganizationId,initiator: Option<&domain::Initiator>,- additional_payment_method_data: Option<+ connector_returned_payment_method_details: Option<&hyperswitch_domain_models::payment_method_data::PaymentMethodData,>,merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,@@ -3987,7 +3992,7 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(attempt_status,platform,business_profile,- additional_payment_method_data,+ connector_returned_payment_method_details,).await{@@ -4083,28 +4088,29 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(last_modified_by,};- let additional_data_update =- if let Some(payment_method_data_update) = additional_payment_method_data {- payment_methods::cards::prepare_payment_method_update_from_connector_details(- state,- platform,- &payment_method,- merchant_connector_id,- payment_method_data_update,- business_profile,- )- .await- .inspect_err(|error| {- logger::error!(- ?error,- payment_method_id = %id,- "Failed to prepare payment method details from PSync response"- );- })- .ok()- } else {- None- };+ let additional_data_update = if let Some(connector_returned_payment_method_details) =+ connector_returned_payment_method_details+ {+ payment_methods::cards::prepare_payment_method_update_from_connector_details(+ state,+ platform,+ &payment_method,+ merchant_connector_id,+ connector_returned_payment_method_details,+ business_profile,+ )+ .await+ .inspect_err(|error| {+ logger::error!(+ ?error,+ payment_method_id = %id,+ "Failed to prepare payment method details from PSync response"+ );+ })+ .ok()+ } else {+ None+ };let pm_update = combine_payment_method_updates(pm_update, additional_data_update);let compat_action = payment_methods::payment_method_modular_forward_compat_action(diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex bb3d21ce07..38360fb9d3 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -1500,11 +1500,8 @@ where}if connector_call_type.is_none() {- crate::core::payments::helpers::override_setup_future_usage_to_on_session(- &*state.store,- payment_data,- )- .await?;+ crate::core::payments::helpers::override_setup_feature_usage(state, payment_data)+ .await?;connector_call_type = Some(api::ConnectorCallType::PreDetermined(first_connector.clone(),diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 7d667816e9..2bcf3dab04 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -163,6 +163,7 @@ pub struct SavePaymentMethodData<Req> {payment_method_token: Option<types::PaymentMethodToken>,payment_method: PaymentMethod,attempt_status: common_enums::AttemptStatus,+ connector_response: Option<hyperswitch_domain_models::router_data::ConnectorResponseData>,}impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>>@@ -175,6 +176,7 @@ impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>payment_method_token: router_data.payment_method_token.clone(),payment_method: router_data.payment_method,attempt_status: router_data.status,+ connector_response: router_data.connector_response.clone(),}}}@@ -183,6 +185,7 @@ pub struct SavePaymentMethodDataResponse {pub payment_method_status: Option<common_enums::PaymentMethodStatus>,pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,}+#[cfg(feature = "v1")]#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]@@ -357,8 +360,8 @@ whereplatform.get_provider().get_key_store(),).await- .map_err(|e| {- logger::error!("Failed to update last used at: {:?}", e);+ .map_err(|error| {+ logger::error!(?error, "Failed to update last used at");}).ok();@@ -443,6 +446,16 @@ where) => Some(domain::PaymentMethodsData::WalletDetails(get_googlepay_wallet_info(googlepay, payment_method_token),)),+ (+ _,+ domain::PaymentMethodData::Wallet(+ domain::WalletData::PaypalRedirect(_)+ | domain::WalletData::PaypalSdk(_),+ ),+ ) => payment_methods::cards::get_paypal_wallet_info(+ save_payment_method_data.connector_response.as_ref(),+ )+ .map(domain::PaymentMethodsData::WalletDetails),(_, domain::PaymentMethodData::BankDebit(bank_debit_data)) => bank_debit_data.get_bank_debit_details().map(domain::PaymentMethodsData::BankDebit),@@ -1038,8 +1051,8 @@ whereplatform.get_provider().get_key_store(),).await- .map_err(|e| {- logger::error!("Failed to update last used at: {:?}", e);+ .map_err(|error| {+ logger::error!(?error, "Failed to update last used at");}).ok();resp.payment_method_id = customer_saved_pm.payment_method_id;diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 8852dba107..242158f2f3 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -448,6 +448,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(.and_then(|noon| noon.order_category.clone())});+ // v2 derives off_session purely from mandate presence (unchanged semantics).let is_off_session = get_off_session(payment_data.mandate_data.as_ref(), None);// Account funded transaction details are merchant supplied and are always read@@ -898,8 +899,7 @@ pub async fn construct_external_vault_proxy_payment_router_data_v1<'a>(.get_required_value("external vault proxy payment_method_data")?,setup_future_usage: payment_data.payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent),mandate_id: payment_data.mandate_id.clone(),off_session: None,setup_mandate_details: None,@@ -4390,6 +4390,8 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to parse recipient details")?.map(api_models::payments::MaskedRecipientDetails::from);+ let setup_future_usage =+ payment_attempt.get_setup_future_usage_with_fallback(&payment_intent);let payments_response = api::PaymentsResponse {// Populated only for server integrations, by the update-context enrichment.payment_method_list: None,@@ -4423,9 +4425,7 @@ wherecaptures: captures_response,mandate_id,mandate_data,- setup_future_usage: payment_attempt- .setup_future_usage_applied- .or(payment_intent.setup_future_usage),+ setup_future_usage,off_session: payment_intent.off_session,capture_on: None,capture_method: payment_attempt.capture_method,@@ -4834,6 +4834,7 @@ fn applied_offer_response(#[cfg(feature = "v1")]impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse {fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self {+ let setup_future_usage = pa.get_setup_future_usage_with_fallback(&pi);let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string);let capture_method_applied = pa.applied_overrides@@ -4918,7 +4919,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Paybusiness_label: pi.business_label,business_country: pi.business_country,business_sub_label: pa.business_sub_label,- setup_future_usage: pa.setup_future_usage_applied.or(pi.setup_future_usage),+ setup_future_usage,capture_method: pa.capture_method,capture_method_applied,authentication_type: pa.authentication_type,@@ -5399,6 +5400,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizcomplete_authorize_url,setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),mandate_id: payment_data.mandate_id.clone(),+ // v2 derives off_session purely from mandate presence (unchanged semantics).off_session: get_off_session(payment_data.mandate_id.as_ref(), None),customer_acceptance: None,setup_mandate_details: None,@@ -5455,6 +5457,31 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz}}+// Previous approach (reverted):+// The request's `off_session` is passed to the connector verbatim; mandate+// flows are validation-gated to carry `Some(true)` (see validate_recurring_mandate).+// This failed because token-MIT routing attaches a mandate internally without requiring+// an explicit off_session flag. Stripe rejected the resulting NTI MIT exemption with+// off_session unset, and the retry then failed because the payment token was consumed.+// Restore mandate-based inference while preserving explicit false and the saved-wallet+// flag, since reusing a wallet credential can still be customer-initiated.+#[cfg(feature = "v1")]+fn get_off_session(+ mandate_id: Option<&MandateIds>,+ off_session_flag: Option<bool>,+ token_data: Option<&storage::PaymentTokenData>,+) -> Option<bool> {+ match token_data {+ Some(storage::PaymentTokenData::WalletToken(_)) => off_session_flag,+ _ => match (mandate_id, off_session_flag) {+ (_, Some(false)) => Some(false),+ (Some(_), _) | (_, Some(true)) => Some(true),+ (None, None) => None,+ },+ }+}++#[cfg(feature = "v2")]fn get_off_session(mandate_id: Option<&MandateIds>,off_session_flag: Option<bool>,@@ -5635,6 +5662,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizlet is_off_session = get_off_session(payment_data.mandate_id.as_ref(),payment_data.payment_intent.off_session,+ payment_data.token_data.as_ref(),);let billing_descriptor = payment_data.payment_intent.get_billing_descriptor();@@ -5651,8 +5679,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizpayment_method_data: (payment_method_data.get_required_value("payment_method_data")?),setup_future_usage: payment_data.payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent),mandate_id: payment_data.mandate_id.clone(),off_session: is_off_session,setup_mandate_details: payment_data.setup_mandate.clone(),@@ -5803,6 +5830,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to parse feature metadata")?;+ let setup_future_usage = payment_data+ .payment_attempt+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent);+Ok(Self {amount,integrity_object: None,@@ -5831,10 +5862,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData.payment_attempt.connector_response_reference_id.clone(),- setup_future_usage: payment_data- .payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ setup_future_usage,feature_metadata,connector_mandate_id: payment_data.payment_attempt@@ -6408,8 +6436,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessshipping_cost: payment_data.payment_intent.shipping_cost,setup_future_usage: payment_data.payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent),router_return_url,})}@@ -7294,6 +7321,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequlet is_off_session = get_off_session(payment_data.mandate_id.as_ref(),payment_data.payment_intent.off_session,+ payment_data.token_data.as_ref(),);let billing_descriptor = payment_data.payment_intent.get_billing_descriptor();@@ -7321,8 +7349,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ.get_required_value("payment_method_data")?),setup_future_usage: payment_data.payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent),off_session: is_off_session,mandate_id: payment_data.mandate_id.clone(),setup_mandate_details: payment_data.setup_mandate,@@ -7512,6 +7539,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizlet is_off_session = get_off_session(payment_data.mandate_id.as_ref(),payment_data.payment_intent.off_session,+ payment_data.token_data.as_ref(),);let router_return_url = Some(helpers::create_redirect_url(@@ -7578,8 +7606,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizOk(Self {setup_future_usage: payment_data.payment_attempt- .setup_future_usage_applied- .or(payment_data.payment_intent.setup_future_usage),+ .get_setup_future_usage_with_fallback(&payment_data.payment_intent),mandate_id: payment_data.mandate_id.clone(),off_session: is_off_session,setup_mandate_details: payment_data.setup_mandate.clone(),diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex a6be83c9f8..9edfe2f665 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -548,6 +548,7 @@ impl ForeignTryFrom<payments_grpc::PaymentMethod> for domain_pm::PaymentMethodDaemail: paypal_redirect.and_then(|email| common_utils::pii::Email::try_from(email.expose()).ok()),+ payer_id: None,}),)),PaymentMethod::Crypto(crypto) => Some(Self::Crypto(domain_pm::CryptoData {@@ -1543,7 +1544,10 @@ pub fn reconstruct_payment_method_data_for_redirect_completion(Some(PaymentMethodType::Paypal) => Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(hyperswitch_domain_models::payment_method_data::WalletData::PaypalRedirect(- hyperswitch_domain_models::payment_method_data::PaypalRedirection { email },+ hyperswitch_domain_models::payment_method_data::PaypalRedirection {+ email,+ payer_id: None,+ },),),),diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 2aaf44ce49..3315827e27 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -110,6 +110,7 @@ impl ForeignFrom<&api_models::payments::ConnectorMetadata>santander: _,worldpayxml,stripe,+ paypal: _,} = metadata;fn to_snake_case_string<T: serde::Serialize>(value: T) -> Option<String> {serde_json::to_value(value)diff --git a/cypress-tests/cypress/e2e/configs/Payment/Checkout.js b/cypress-tests/cypress/e2e/configs/Payment/Checkout.jsindex 2de5d585ae..8e809d1ee5 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Checkout.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Checkout.js@@ -1055,6 +1055,7 @@ export const connectorDetails = {adyen: null,peachpayments: null,santander: null,+ paypal: null,worldpayxml: null,checkout: {purpose_of_payment: "wallet top-up",diff --git a/cypress-tests/cypress/e2e/configs/Payment/Peachpayments.js b/cypress-tests/cypress/e2e/configs/Payment/Peachpayments.jsindex 0671da577e..e6cc954d07 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Peachpayments.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Peachpayments.js@@ -728,6 +728,7 @@ export const connectorDetails = {card_on_file_transaction_type: "merchant_initiated_transaction",},santander: null,+ paypal: null,worldpayxml: null,checkout: null,stripe: null,diff --git a/cypress-tests/cypress/e2e/configs/Payment/Worldpayxml.js b/cypress-tests/cypress/e2e/configs/Payment/Worldpayxml.jsindex 13851331ea..05ebd5f17f 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Worldpayxml.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Worldpayxml.js@@ -688,6 +688,7 @@ export const connectorDetails = {adyen: null,peachpayments: null,santander: null,+ paypal: null,worldpayxml: {funding_transaction_type: "funds_transfer_me_to_me",payment_purpose: "family_support",