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(Googlepay): [Googlepay] InternalGateway flow (#14153)
Nithin Nd9492338b067
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 3ff53620e4..86c2bc6ccc 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -24537,6 +24537,14 @@}}},+ "GooglePayTokenizationSpecificationType": {+ "type": "string",+ "description": "The tokenization type sent to the Google Pay SDK.\n\nUnlike [`GooglePayTokenizationType`], this holds only the values Google itself understands:\nthe Hyperswitch-internal `INTERNAL_GATEWAY` marker is resolved into `PAYMENT_GATEWAY` during\nthe session flow before this is built, so it can never leak into an SDK response.",+ "enum": [+ "PAYMENT_GATEWAY",+ "DIRECT"+ ]+ },"GooglePayWalletData": {"type": "object","required": [@@ -24768,8 +24776,7 @@],"properties": {"type": {- "type": "string",- "description": "The token specification type(ex: PAYMENT_GATEWAY)"+ "$ref": "#/components/schemas/GooglePayTokenizationSpecificationType"},"parameters": {"$ref": "#/components/schemas/GpayTokenParameters"diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex d4598e8ec1..d11c4d5048 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -17012,6 +17012,14 @@}}},+ "GooglePayTokenizationSpecificationType": {+ "type": "string",+ "description": "The tokenization type sent to the Google Pay SDK.\n\nUnlike [`GooglePayTokenizationType`], this holds only the values Google itself understands:\nthe Hyperswitch-internal `INTERNAL_GATEWAY` marker is resolved into `PAYMENT_GATEWAY` during\nthe session flow before this is built, so it can never leak into an SDK response.",+ "enum": [+ "PAYMENT_GATEWAY",+ "DIRECT"+ ]+ },"GooglePayWalletData": {"type": "object","required": [@@ -17243,8 +17251,7 @@],"properties": {"type": {- "type": "string",- "description": "The token specification type(ex: PAYMENT_GATEWAY)"+ "$ref": "#/components/schemas/GooglePayTokenizationSpecificationType"},"parameters": {"$ref": "#/components/schemas/GpayTokenParameters"diff --git a/config/config.example.toml b/config/config.example.tomlindex 428030e429..333248ad98 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1186,6 +1186,9 @@ paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase use[google_pay_decrypt_keys]google_pay_root_signing_keys = "GOOGLE_PAY_ROOT_SIGNING_KEYS" # Base 64 Encoded Root Signing Keys provided by Google Pay (https://developers.google.com/pay/api/web/guides/resources/payment-data-cryptography)+google_pay_private_key = "GOOGLE_PAY_PRIVATE_KEY" # Base 64 Encoded PKCS#8 private key of the Hyperswitch registered Google Pay gateway, used by the INTERNAL_GATEWAY tokenization flow+google_pay_common_merchant_id = "GOOGLE_PAY_COMMON_MERCHANT_ID" # Google Pay Business Console merchant id used when an INTERNAL_GATEWAY merchant does not supply one of its own. Not a secret, it is sent to the SDK+google_pay_gateway_id = "GOOGLE_PAY_GATEWAY_ID" # Gateway identifier registered with Google, also used to derive the `gateway:<id>` recipient. google_pay_private_key, google_pay_gateway_id and google_pay_common_merchant_id must either all be set or all be unset[applepay_merchant_configs]# Run below command to get common merchant identifier for applepay in shelldiff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex d6e79085dc..312735e5de 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -48,6 +48,9 @@ paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase use[google_pay_decrypt_keys]google_pay_root_signing_keys = "GOOGLE_PAY_ROOT_SIGNING_KEYS" # Base 64 Encoded Root Signing Keys provided by Google Pay (https://developers.google.com/pay/api/web/guides/resources/payment-data-cryptography)+google_pay_private_key = "GOOGLE_PAY_PRIVATE_KEY" # Base 64 Encoded PKCS#8 private key of the Hyperswitch registered Google Pay gateway, used by the INTERNAL_GATEWAY tokenization flow+google_pay_common_merchant_id = "GOOGLE_PAY_COMMON_MERCHANT_ID" # Google Pay Business Console merchant id used when an INTERNAL_GATEWAY merchant does not supply one of its own. Not a secret, it is sent to the SDK+google_pay_gateway_id = "GOOGLE_PAY_GATEWAY_ID" # Gateway identifier registered with Google, also used to derive the `gateway:<id>` recipient. google_pay_private_key, google_pay_gateway_id and google_pay_common_merchant_id must either all be set or all be unset[applepay_merchant_configs]common_merchant_identifier = "APPLE_PAY_COMMON_MERCHANT_IDENTIFIER" # Refer to config.example.toml to learn how you can generate this valuediff --git a/config/development.toml b/config/development.tomlindex f5f8ebad92..0784564d27 100644--- a/config/development.toml+++ b/config/development.toml@@ -1361,6 +1361,9 @@ paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE"[google_pay_decrypt_keys]google_pay_root_signing_keys = "GOOGLE_PAY_ROOT_SIGNING_KEYS" # Base 64 Encoded Root Signing Keys provided by Google Pay (https://developers.google.com/pay/api/web/guides/resources/payment-data-cryptography)+google_pay_private_key = "GOOGLE_PAY_PRIVATE_KEY" # Base 64 Encoded PKCS#8 private key of the Hyperswitch registered Google Pay gateway, used by the INTERNAL_GATEWAY tokenization flow+google_pay_common_merchant_id = "GOOGLE_PAY_COMMON_MERCHANT_ID" # Google Pay Business Console merchant id used when an INTERNAL_GATEWAY merchant does not supply one of its own. Not a secret, it is sent to the SDK+google_pay_gateway_id = "GOOGLE_PAY_GATEWAY_ID" # Gateway identifier registered with Google, also used to derive the `gateway:<id>` recipient. google_pay_private_key, google_pay_gateway_id and google_pay_common_merchant_id must either all be set or all be unset[generic_link][generic_link.payment_method_collect]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 309e9d3ce8..5681c9b526 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -10131,6 +10131,44 @@ pub struct GpayTokenParameters {pub public_key: Option<Secret<String>>,}+/// The tokenization type sent to the Google Pay SDK.+///+/// Unlike [`GooglePayTokenizationType`], this holds only the values Google itself understands:+/// the Hyperswitch-internal `INTERNAL_GATEWAY` marker is resolved into `PAYMENT_GATEWAY` during+/// the session flow before this is built, so it can never leak into an SDK response.+#[derive(+ Debug,+ Clone,+ Copy,+ PartialEq,+ Eq,+ serde::Serialize,+ serde::Deserialize,+ ToSchema,+ strum::Display,+ strum::EnumString,+)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]+pub enum GooglePayTokenizationSpecificationType {+ PaymentGateway,+ Direct,+}++/// Resolves the caller-facing [`GooglePayTokenizationType`] into the SDK-side equivalent.+///+/// `INTERNAL_GATEWAY` is not a tokenization type Google understands: sessions served through it+/// go through Hyperswitch's own registered gateway, which the SDK knows as `PAYMENT_GATEWAY`.+impl From<GooglePayTokenizationType> for GooglePayTokenizationSpecificationType {+ fn from(tokenization_type: GooglePayTokenizationType) -> Self {+ match tokenization_type {+ GooglePayTokenizationType::Direct => Self::Direct,+ GooglePayTokenizationType::PaymentGateway+ | GooglePayTokenizationType::InternalGateway => Self::PaymentGateway,+ }+ }+}+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema, SmithyModel,)]@@ -10138,8 +10176,8 @@ pub struct GpayTokenParameters {pub struct GpayTokenizationSpecification {/// The token specification type(ex: PAYMENT_GATEWAY)#[serde(rename = "type")]- #[smithy(value_type = "String")]- pub token_specification_type: String,+ #[smithy(value_type = "GooglePayTokenizationSpecificationType")]+ pub token_specification_type: GooglePayTokenizationSpecificationType,/// The parameters for the token specification Google Pay#[smithy(value_type = "GpayTokenParameters")]pub parameters: GpayTokenParameters,@@ -10680,18 +10718,25 @@ pub struct GooglePayMerchantInfo {pub struct GooglePayTokenizationSpecification {#[serde(rename = "type")]pub tokenization_type: GooglePayTokenizationType,+ /// Absent for `INTERNAL_GATEWAY`, where the merchant supplies no key material at all.+ #[serde(default)]pub parameters: GooglePayTokenizationParameters,}-#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)]+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display,+)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]pub enum GooglePayTokenizationType {PaymentGateway,Direct,+ /// Hyperswitch-internal marker: the token is encrypted to Hyperswitch's own registered+ /// gateway key. Never sent to Google as-is; resolved to `PAYMENT_GATEWAY` in the session flow.+ InternalGateway,}-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]pub struct GooglePayTokenizationParameters {pub gateway: Option<String>,pub public_key: Option<Secret<String>>,diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rsindex 805051b75b..342ff18a8d 100644--- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::{collections::HashMap, str::FromStr};use api_models::payments::SessionToken;use cards::NetworkToken;@@ -1581,8 +1581,8 @@ pub(crate) fn get_google_pay_session<F, T>(allowed_payment_methods: google_pay_init_result.allowed_payment_methods.into_iter()- .map(Into::into)- .collect(),+ .map(TryInto::try_into)+ .collect::<Result<Vec<_>, _>>()?,transaction_info: google_pay_init_result.transaction_info.into(),secrets: Some((*secrets).clone().into()),shipping_address_required: false,@@ -1622,13 +1622,15 @@ impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo {}}-impl From<GooglePayAllowedPaymentMethods> for api_models::payments::GpayAllowedPaymentMethods {- fn from(value: GooglePayAllowedPaymentMethods) -> Self {- Self {+impl TryFrom<GooglePayAllowedPaymentMethods> for api_models::payments::GpayAllowedPaymentMethods {+ type Error = error_stack::Report<errors::ConnectorError>;++ fn try_from(value: GooglePayAllowedPaymentMethods) -> Result<Self, Self::Error> {+ Ok(Self {payment_method_type: value.payment_method_type,parameters: value.parameters.into(),- tokenization_specification: value.tokenization_specification.into(),- }+ tokenization_specification: value.tokenization_specification.try_into()?,+ })}}@@ -1645,12 +1647,23 @@ impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMet}}-impl From<GpayTokenizationSpecification> for api_models::payments::GpayTokenizationSpecification {- fn from(value: GpayTokenizationSpecification) -> Self {- Self {- token_specification_type: value.token_specification_type,+impl TryFrom<GpayTokenizationSpecification>+ for api_models::payments::GpayTokenizationSpecification+{+ type Error = error_stack::Report<errors::ConnectorError>;++ fn try_from(value: GpayTokenizationSpecification) -> Result<Self, Self::Error> {+ Ok(Self {+ token_specification_type:+ api_models::payments::GooglePayTokenizationSpecificationType::from_str(+ &value.token_specification_type,+ )+ .change_context(errors::ConnectorError::ParsingFailed)+ .attach_printable(+ "unsupported google pay tokenization type received from trustpay",+ )?,parameters: value.parameters.into(),- }+ })}}diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rsindex bb2b53da58..d03befa823 100644--- a/crates/hyperswitch_domain_models/src/router_data.rs+++ b/crates/hyperswitch_domain_models/src/router_data.rs@@ -643,6 +643,9 @@ impl ApplePayPredecryptDataInternal {pub struct GooglePayPredecryptDataInternal {pub message_expiration: String,pub message_id: String,+ /// Present when the card was tokenized for a gateway, carrying the `gateway_merchant_id` that+ /// was sent to Google in the session response. Absent for `DIRECT` tokenization.+ pub gateway_merchant_id: Option<String>,#[serde(rename = "paymentMethod")]pub payment_method_type: String,pub payment_method_details: GooglePayPaymentMethodDetails,diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rsindex 05b1343b88..83986c4636 100644--- a/crates/hyperswitch_interfaces/src/configs.rs+++ b/crates/hyperswitch_interfaces/src/configs.rs@@ -149,6 +149,13 @@ impl MerchantConnectorAccountType {None}+ pub fn get_merchant_id(&self) -> Option<id_type::MerchantId> {+ match self {+ Self::DbVal(db_val) => Some(db_val.merchant_id.clone()),+ Self::CacheVal(_) => None,+ }+ }+pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {match self {Self::DbVal(db_val) => Some(db_val.get_id()),diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex f03683ebeb..0a08779b77 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -739,6 +739,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::GpayAllowedPaymentMethods,api_models::payments::GpayAllowedMethodsParameters,api_models::payments::GpayTokenizationSpecification,+ api_models::payments::GooglePayTokenizationSpecificationType,api_models::payments::GpayTokenParameters,api_models::payments::GpayTransactionInfo,api_models::payments::GpaySessionTokenResponse,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 7e2fa7cc90..ce8993edfa 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -609,6 +609,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::GpayAllowedPaymentMethods,api_models::payments::GpayAllowedMethodsParameters,api_models::payments::GpayTokenizationSpecification,+ api_models::payments::GooglePayTokenizationSpecificationType,api_models::payments::GpayTokenParameters,api_models::payments::GpayTransactionInfo,api_models::payments::GpaySessionTokenResponse,diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex eac6339697..911078934f 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -193,6 +193,33 @@ impl SecretsHandler for settings::PazeDecryptConfig {}}+#[async_trait::async_trait]+impl SecretsHandler for settings::GooglePayDecryptConfig {+ async fn convert_to_raw_secret(+ value: SecretStateContainer<Self, SecuredSecret>,+ secret_management_client: &dyn SecretManagementInterface,+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {+ let google_pay_decrypt_keys = value.get_inner();++ // The private key is the only secret managed value here. The root signing keys are+ // Google's public certificates, the gateway id is a plain identifier, and the common+ // merchant id is sent to the SDK in the session response, so none of them are fetched.+ let google_pay_private_key = google_pay_decrypt_keys+ .google_pay_private_key+ .clone()+ .async_map(|private_key| async move {+ secret_management_client.get_secret(private_key).await+ })+ .await+ .transpose()?;++ Ok(value.transition_state(|google_pay_decrypt_keys| Self {+ google_pay_private_key,+ ..google_pay_decrypt_keys+ }))+ }+}+#[async_trait::async_trait]impl SecretsHandler for settings::ApplepayMerchantConfigs {async fn convert_to_raw_secret(@@ -544,6 +571,20 @@ pub(crate) async fn fetch_raw_secrets(None};+ #[allow(clippy::expect_used)]+ let google_pay_decrypt_keys = if let Some(google_pay_keys) = conf.google_pay_decrypt_keys {+ Some(+ settings::GooglePayDecryptConfig::convert_to_raw_secret(+ google_pay_keys,+ secret_management_client,+ )+ .await+ .expect("Failed to decrypt google pay decrypt configs"),+ )+ } else {+ None+ };+#[allow(clippy::expect_used)]let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret(conf.applepay_merchant_configs,@@ -712,7 +753,7 @@ pub(crate) async fn fetch_raw_secrets(payouts: conf.payouts,applepay_decrypt_keys,paze_decrypt_keys,- google_pay_decrypt_keys: conf.google_pay_decrypt_keys,+ google_pay_decrypt_keys,multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors,applepay_merchant_configs,lock_settings: conf.lock_settings,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 902553f140..eb872e22fc 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -147,7 +147,7 @@ pub struct Settings<S: SecretState> {pub debit_routing_config: DebitRoutingConfig,pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,- pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>,+ pub google_pay_decrypt_keys: Option<SecretStateContainer<GooglePayDecryptConfig, S>>,pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>,pub lock_settings: LockSettings,@@ -1408,6 +1408,17 @@ pub struct PazeDecryptConfig {#[derive(Debug, Deserialize, Clone)]pub struct GooglePayDecryptConfig {pub google_pay_root_signing_keys: Secret<String>,+ /// Private key of Hyperswitch's own registered Google Pay gateway. Used by the+ /// `INTERNAL_GATEWAY` tokenization flow, where the merchant registers no key of its own.+ pub google_pay_private_key: Option<Secret<String>>,+ /// Google Pay Business Console merchant id used when an `INTERNAL_GATEWAY` merchant chooses+ /// not to supply one of its own. Not secret managed: it is sent to the SDK in the session+ /// response.+ pub google_pay_common_merchant_id: Option<Secret<String>>,+ /// Gateway identifier registered with Google, sent as+ /// `tokenizationSpecification.parameters.gateway` and used to derive the `gateway:<id>`+ /// recipient the token is signed against.+ pub google_pay_gateway_id: Option<String>,}#[derive(Debug, Deserialize, Clone, Default)]@@ -1653,7 +1664,7 @@ impl Settings<SecuredSecret> {self.google_pay_decrypt_keys.as_ref()- .map(|x| x.validate())+ .map(|x| x.get_inner().validate()).transpose()?;self.key_manager.get_inner().validate()?;diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 7782859933..3e2c0dfd11 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -279,6 +279,54 @@ impl super::settings::GooglePayDecryptConfig {"google_pay_root_signing_keys must not be empty".into(),))},+ )?;++ // The private key, gateway id and common merchant id together describe Hyperswitch's+ // registered Google Pay gateway: the key decrypts the token, the id derives the+ // `gateway:<id>` recipient it was signed against, and the common merchant id is sent to+ // the SDK for INTERNAL_GATEWAY merchants that do not supply one of their own. Either all+ // of them are configured or none is, otherwise the INTERNAL_GATEWAY flow raises a payment+ // sheet whose token cannot be decrypted.+ let internal_gateway_fields = [+ (+ "google_pay_private_key",+ self.google_pay_private_key.is_none(),+ ),+ (+ "google_pay_gateway_id",+ self.google_pay_gateway_id.is_none(),+ ),+ (+ "google_pay_common_merchant_id",+ self.google_pay_common_merchant_id.is_none(),+ ),+ ];+ let missing_fields = internal_gateway_fields+ .iter()+ .filter_map(|(field, is_missing)| is_missing.then_some(*field))+ .collect::<Vec<_>>();++ when(+ !missing_fields.is_empty() && missing_fields.len() != internal_gateway_fields.len(),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(format!(+ "google_pay_private_key, google_pay_gateway_id and \+ google_pay_common_merchant_id must either all be set or all be unset; \+ missing: {}",+ missing_fields.join(", ")+ )))+ },+ )?;++ when(+ self.google_pay_gateway_id+ .as_ref()+ .is_some_and(|gateway_id| gateway_id.trim().is_empty()),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "google_pay_gateway_id must not be empty".into(),+ ))+ },)}}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 63d668c3e3..e84860b6bd 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -286,6 +286,11 @@ pub(crate) const PROTOCOL: &str = "ECv2";/// Sender ID for Google Pay Decryptionpub(crate) const SENDER_ID: &[u8] = b"Google";+/// Prefix of the recipient identifier Google signs a gateway tokenized card against, i.e.+/// `gateway:<gateway id>`. Used by the `INTERNAL_GATEWAY` google pay flow, which derives the+/// recipient from configuration instead of taking it from the merchant.+pub(crate) const GOOGLE_PAY_GATEWAY_RECIPIENT_PREFIX: &str = "gateway:";+/// Default value for the number of attempts to retry fetching forex ratespub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3;diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex bd90cfc0de..a4c8c9d85a 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -270,6 +270,8 @@ pub enum GooglePayDecryptionError {DecryptedTokenExpired,#[error("Failed to parse the given value")]ParsingFailed,+ #[error("Gateway merchant id in the token does not match the merchant being paid")]+ InvalidGatewayMerchantId,}#[derive(Debug, Clone, thiserror::Error)]diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex b7915b3d5b..540e378f3c 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -7875,21 +7875,49 @@ async fn decrypt_google_pay_wallet_data(.clone(),payment_processing_details.google_pay_recipient_id.clone(),payment_processing_details.google_pay_private_key.clone(),+ // INTERNAL_GATEWAY additionally enforces that the decrypted token's+ // gatewayMerchantId matches the merchant being paid. Signature verification stays+ // off, and DIRECT recipients are merchant supplied and left unverified, as today.+ payment_processing_details.google_pay_tokenization_type,+ payment_processing_details+ .google_pay_gateway_merchant_id+ .clone(),).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("failed to create google pay token decryptor")?;+ let google_pay_token = google_pay_wallet_data+ .tokenization_data+ .get_encrypted_google_pay_token()+ .change_context(errors::ApiErrorResponse::InternalServerError)?+ .clone();+// should_verify_token is set to false to disable verification of tokenlet google_pay_data_internal = decryptor- .decrypt_token(- google_pay_wallet_data- .tokenization_data- .get_encrypted_google_pay_token()- .change_context(errors::ApiErrorResponse::InternalServerError)?- .clone(),- false,- )- .change_context(errors::ApiErrorResponse::InternalServerError)+ .decrypt_token(google_pay_token, false)+ .map_err(|error| {+ logger::warn!(?error, "failed to decrypt google pay token");+ let api_error = match error.current_context() {+ // The gateway merchant id carried by the token does not match the gateway+ // merchant id configured for the merchant (or is missing from either side).+ // Authorization was never attempted with the connector; this is a gateway+ // configuration mismatch, so report it as an invalid request instead of a+ // connector authorization failure.+ errors::GooglePayDecryptionError::InvalidGatewayMerchantId => {+ errors::ApiErrorResponse::InvalidRequestData {+ message: "Failed to decrypt the Google Pay token: gateway merchant id \+ in the token does not match the gateway merchant id \+ configured for the merchant"+ .to_string(),+ }+ }++ // Everything else, including a recipient that does not match the configured+ // gateway, is our own fault and stays a server error as it is today.+ _ => errors::ApiErrorResponse::InternalServerError,+ };+ error.change_context(api_error)+ }).attach_printable("failed to decrypt google pay token")?;Ok(common_types::payments::GPayPredecryptData::from(google_pay_data_internal,@@ -9276,10 +9304,12 @@ fn get_google_pay_connector_wallet_details(state: &SessionState,merchant_connector_account: &helpers::MerchantConnectorAccountType,) -> Option<GooglePayPaymentProcessingDetails> {- let google_pay_root_signing_keys = state+ let google_pay_decrypt_keys = state.conf.google_pay_decrypt_keys.as_ref()+ .map(|google_pay_keys| google_pay_keys.get_inner());+ let google_pay_root_signing_keys = google_pay_decrypt_keys.map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone());match merchant_connector_account.get_connector_wallets_details() {Some(wallet_details) => {@@ -9297,31 +9327,68 @@ fn get_google_pay_connector_wallet_details(|google_pay_wallet_details| {match google_pay_wallet_details.provider_details {api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => {- match (- merchant_details- .merchant_info- .tokenization_specification- .parameters- .private_key,- google_pay_root_signing_keys,- merchant_details- .merchant_info- .tokenization_specification- .parameters- .recipient_id,- ) {- (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => {- Some(GooglePayPaymentProcessingDetails {- google_pay_private_key,- google_pay_root_signing_keys,- google_pay_recipient_id- })- }- _ => {- logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id");- None+ let tokenization_specification = merchant_details.merchant_info.tokenization_specification;++ match tokenization_specification.tokenization_type {+ // The merchant registered no key of its own: the token is+ // encrypted to Hyperswitch's gateway key, and the recipient is+ // derived from the same gateway id that was sent to Google in+ // the session response.+ api_models::payments::GooglePayTokenizationType::InternalGateway => {+ let google_pay_gateway_id = google_pay_decrypt_keys+ .and_then(|google_pay_keys| google_pay_keys.google_pay_gateway_id.clone());+ let google_pay_private_key = google_pay_decrypt_keys+ .and_then(|google_pay_keys| google_pay_keys.google_pay_private_key.clone());+ // The same merchant id that was sent to Google as+ // gateway_merchant_id when the sheet was raised.+ let google_pay_gateway_merchant_id = merchant_connector_account+ .get_merchant_id()+ .map(|merchant_id| merchant_id.get_string_repr().to_owned());++ match (google_pay_private_key, google_pay_root_signing_keys, google_pay_gateway_id) {+ (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_gateway_id)) => {+ Some(GooglePayPaymentProcessingDetails {+ google_pay_private_key,+ google_pay_root_signing_keys,+ google_pay_recipient_id: Secret::new(format!(+ "{}{}",+ consts::GOOGLE_PAY_GATEWAY_RECIPIENT_PREFIX,+ google_pay_gateway_id+ )),+ google_pay_tokenization_type: api_models::payments::GooglePayTokenizationType::InternalGateway,+ google_pay_gateway_merchant_id,+ })+ }+ _ => {+ logger::warn!("One or more of the following fields are missing in google_pay_decrypt_keys for an INTERNAL_GATEWAY merchant: google_pay_private_key, google_pay_root_signing_keys, google_pay_gateway_id");+ None+ }}}+ // The connector decrypts the token, Hyperswitch never sees the card.+ api_models::payments::GooglePayTokenizationType::PaymentGateway => None,+ api_models::payments::GooglePayTokenizationType::Direct => {+ match (+ tokenization_specification.parameters.private_key,+ google_pay_root_signing_keys,+ tokenization_specification.parameters.recipient_id,+ ) {+ (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => {+ Some(GooglePayPaymentProcessingDetails {+ google_pay_private_key,+ google_pay_root_signing_keys,+ google_pay_recipient_id,+ google_pay_tokenization_type: api_models::payments::GooglePayTokenizationType::Direct,+ google_pay_gateway_merchant_id: None,+ })+ }+ _ => {+ logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id");+ None+ }+ }+ }+ }}}}@@ -9437,6 +9504,14 @@ pub struct GooglePayPaymentProcessingDetails {pub google_pay_private_key: Secret<String>,pub google_pay_root_signing_keys: Secret<String>,pub google_pay_recipient_id: Secret<String>,+ /// Tokenization type configured on the MCA. `INTERNAL_GATEWAY` additionally enforces that+ /// the decrypted token's `gatewayMerchantId` matches the merchant being paid; signature+ /// verification stays off, as it does for `DIRECT`, whose recipients are typed by the+ /// merchant and are therefore left unverified.+ pub google_pay_tokenization_type: api_models::payments::GooglePayTokenizationType,+ /// Hyperswitch merchant id sent to Google as `gateway_merchant_id`, checked against the+ /// decrypted token. Set for `INTERNAL_GATEWAY` only.+ pub google_pay_gateway_merchant_id: Option<String>,}#[cfg(feature = "v1")]#[derive(Clone, Debug)]diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex 03327f264a..62e9f7215e 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -1152,12 +1152,17 @@ async fn create_gpay_session_token(provider_details.clone();let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards(+ state,+ &router_data.merchant_id,cards,&gpay_info.merchant_info.tokenization_specification,is_billing_details_required,wallet_blocking_config,)?;+ let google_pay_merchant_id =+ resolve_google_pay_merchant_id(state, &gpay_info.merchant_info);+Ok(types::PaymentsSessionRouterData {response: Ok(types::PaymentsResponseData::SessionResponse {session_token: payment_types::SessionToken::GooglePay(Box::new(@@ -1165,7 +1170,7 @@ async fn create_gpay_session_token(payment_types::GooglePaySessionResponse {merchant_info: payment_types::GpayMerchantInfo {merchant_name: gpay_info.merchant_info.merchant_name,- merchant_id: gpay_info.merchant_info.merchant_id,+ merchant_id: google_pay_merchant_id,},allowed_payment_methods: vec![gpay_allowed_payment_methods],transaction_info,@@ -1302,6 +1307,8 @@ async fn create_gpay_session_token(pub(crate) const CARD: &str = "CARD";fn get_allowed_payment_methods_from_cards(+ state: &routes::SessionState,+ merchant_id: &common_utils::id_type::MerchantId,gpay_cards: payment_types::GpayAllowedMethodsParameters,gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification,is_billing_details_required: bool,@@ -1313,14 +1320,14 @@ fn get_allowed_payment_methods_from_cards(format: payment_types::GpayBillingAddressFormat::FULL,});- let protocol_version: Option<String> = gpay_token_specific_data- .parameters- .public_key- .as_ref()- .map(|_| PROTOCOL.to_string());-let allow_credit_cards = get_google_pay_card_type_restrictions(wallet_blocking_config);+ let tokenization_specification = resolve_google_pay_tokenization_specification(+ state,+ merchant_id,+ gpay_token_specific_data,+ )?;+Ok(payment_types::GpayAllowedPaymentMethods {parameters: payment_types::GpayAllowedMethodsParameters {billing_address_required: Some(is_billing_details_required),@@ -1329,32 +1336,139 @@ fn get_allowed_payment_methods_from_cards(..gpay_cards},payment_method_type: CARD.to_string(),- tokenization_specification: payment_types::GpayTokenizationSpecification {- token_specification_type: gpay_token_specific_data.tokenization_type.to_string(),- parameters: payment_types::GpayTokenParameters {- protocol_version,- public_key: gpay_token_specific_data.parameters.public_key.clone(),- gateway: gpay_token_specific_data.parameters.gateway.clone(),- gateway_merchant_id: gpay_token_specific_data- .parameters- .gateway_merchant_id- .clone()- .expose_option(),- stripe_publishable_key: gpay_token_specific_data- .parameters- .stripe_publishable_key- .clone()- .expose_option(),- stripe_version: gpay_token_specific_data- .parameters- .stripe_version- .clone()- .expose_option(),- },- },+ tokenization_specification,})}+/// Resolve the tokenization specification that is sent to the Google Pay SDK.+///+/// `INTERNAL_GATEWAY` is a Hyperswitch internal marker and is not a tokenization type Google+/// understands, so it is resolved here into a `PAYMENT_GATEWAY` specification pointing at+/// Hyperswitch's own registered gateway. The card is then encrypted to a key we hold, which is+/// what lets the merchant onboard without registering a keypair of its own.+///+/// `DIRECT` and `PAYMENT_GATEWAY` are passed through exactly as the merchant configured them.+fn resolve_google_pay_tokenization_specification(+ state: &routes::SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification,+) -> RouterResult<payment_types::GpayTokenizationSpecification> {+ match gpay_token_specific_data.tokenization_type {+ payment_types::GooglePayTokenizationType::InternalGateway => {+ // A missing gateway id is a hard error rather than a silent skip: the SDK would+ // otherwise raise a payment sheet whose token nothing can decrypt.+ let gateway = state+ .google_pay_gateway_id()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "google_pay_decrypt_keys.google_pay_gateway_id is not configured, cannot \+ serve an INTERNAL_GATEWAY google pay session",+ )?;++ Ok(payment_types::GpayTokenizationSpecification {+ token_specification_type:+ payment_types::GooglePayTokenizationSpecificationType::from(+ gpay_token_specific_data.tokenization_type,+ ),+ parameters: payment_types::GpayTokenParameters {+ gateway: Some(gateway),+ // The Hyperswitch merchant id keeps each merchant individually identifiable+ // in the token, which a fixed constant would not.+ gateway_merchant_id: Some(merchant_id.get_string_repr().to_owned()),+ // A gateway specification carries no public key, and therefore no protocol+ // version.+ protocol_version: None,+ public_key: None,+ stripe_publishable_key: None,+ stripe_version: None,+ },+ })+ }+ payment_types::GooglePayTokenizationType::Direct+ | payment_types::GooglePayTokenizationType::PaymentGateway => {+ let token_specification_type =+ payment_types::GooglePayTokenizationSpecificationType::from(+ gpay_token_specific_data.tokenization_type,+ );++ let protocol_version: Option<String> = gpay_token_specific_data+ .parameters+ .public_key+ .as_ref()+ .map(|_| PROTOCOL.to_string());++ Ok(payment_types::GpayTokenizationSpecification {+ token_specification_type,+ parameters: payment_types::GpayTokenParameters {+ protocol_version,+ public_key: gpay_token_specific_data.parameters.public_key.clone(),+ gateway: gpay_token_specific_data.parameters.gateway.clone(),+ gateway_merchant_id: gpay_token_specific_data+ .parameters+ .gateway_merchant_id+ .clone()+ .expose_option(),+ stripe_publishable_key: gpay_token_specific_data+ .parameters+ .stripe_publishable_key+ .clone()+ .expose_option(),+ stripe_version: gpay_token_specific_data+ .parameters+ .stripe_version+ .clone()+ .expose_option(),+ },+ })+ }+ }+}++/// Google Pay merchant id sent back to the SDK.+///+/// Under `INTERNAL_GATEWAY` the merchant chooses whether to register with the Google Pay Business+/// Console itself. If it did, its own id is used exactly as under `DIRECT`; if it did not, the+/// common Hyperswitch merchant id from config is substituted. Both are supported configurations.+///+/// Never applied to `DIRECT` or `PAYMENT_GATEWAY`: substituting our merchant id into a merchant's+/// own integration would change who Google treats as the merchant of record.+fn resolve_google_pay_merchant_id(+ state: &routes::SessionState,+ merchant_info: &payment_types::GooglePayMerchantInfo,+) -> Option<String> {+ match merchant_info.merchant_id.clone() {+ Some(merchant_id) => Some(merchant_id),+ None => match merchant_info.tokenization_specification.tokenization_type {+ payment_types::GooglePayTokenizationType::InternalGateway => {+ match state+ .conf+ .google_pay_decrypt_keys+ .as_ref()+ .and_then(|google_pay_keys| {+ google_pay_keys+ .get_inner()+ .google_pay_common_merchant_id+ .clone()+ })+ .map(|merchant_id| merchant_id.expose())+ {+ Some(common_merchant_id) => Some(common_merchant_id),+ None => {+ logger::warn!(+ "google_pay_common_merchant_id is not configured and the merchant \+ did not supply a merchant_id, the google pay sheet will be raised \+ without one"+ );+ None+ }+ }+ }+ payment_types::GooglePayTokenizationType::Direct+ | payment_types::GooglePayTokenizationType::PaymentGateway => None,+ },+ }+}+fn construct_stripe_publishable_key(gpay_token_specific_parameters: &payment_types::GpayTokenParameters,router_data: &types::PaymentsSessionRouterData,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 105440ede5..68a6340890 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -7421,6 +7421,13 @@ pub struct GooglePayTokenDecryptor {root_signing_keys: Vec<GooglePayRootSigningKey>,recipient_id: hyperswitch_masking::Secret<String>,private_key: PKey<openssl::pkey::Private>,+ /// Tokenization type the merchant configured on its MCA. `INTERNAL_GATEWAY` tokens get the+ /// additional `gatewayMerchantId` check after decryption; every other type keeps today's+ /// behaviour.+ tokenization_type: api_models::payments::GooglePayTokenizationType,+ /// Hyperswitch merchant id that was sent to Google as `gateway_merchant_id`. Set for+ /// `INTERNAL_GATEWAY` only, and checked against the decrypted token.+ gateway_merchant_id: Option<String>,}#[derive(Debug, Clone, serde::Deserialize)]@@ -7528,6 +7535,8 @@ impl GooglePayTokenDecryptor {root_keys: hyperswitch_masking::Secret<String>,recipient_id: hyperswitch_masking::Secret<String>,private_key: hyperswitch_masking::Secret<String>,+ tokenization_type: api_models::payments::GooglePayTokenizationType,+ gateway_merchant_id: Option<String>,) -> CustomResult<Self, errors::GooglePayDecryptionError> {// base64 decode the private keylet decoded_key = BASE64_ENGINE@@ -7554,6 +7563,8 @@ impl GooglePayTokenDecryptor {root_signing_keys: filtered_root_signing_keys,recipient_id,private_key,+ tokenization_type,+ gateway_merchant_id,})}@@ -7571,7 +7582,6 @@ impl GooglePayTokenDecryptor {.parse_struct("EncryptedData").change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;- // verify the signature if requiredif should_verify_signature {self.verify_signature(&encrypted_data)?;}@@ -7601,6 +7611,16 @@ impl GooglePayTokenDecryptor {.parse_struct("GooglePayPredecryptDataInternal").change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;+ // `gatewayMerchantId` only exists once the message is decrypted, so this half of the+ // INTERNAL_GATEWAY verification necessarily runs here rather than alongside the signature+ // checks above.+ if matches!(+ self.tokenization_type,+ api_models::payments::GooglePayTokenizationType::InternalGateway+ ) {+ self.verify_internal_gateway_merchant_id(&decrypted_data)?;+ }+// check the expiration date of the decrypted dataif matches!(@@ -7613,6 +7633,44 @@ impl GooglePayTokenDecryptor {}}+ /// Check that the decrypted token was minted for the merchant now being paid.+ ///+ /// Under `INTERNAL_GATEWAY` every merchant's card is encrypted to the same gateway key, so the+ /// key alone no longer separates one merchant from another. `gateway_merchant_id` is what+ /// does: Google echoes back the Hyperswitch merchant id that was sent in the session response,+ /// and a mismatch means the token belongs to a different merchant's payment.+ fn verify_internal_gateway_merchant_id(+ &self,+ decrypted_data: &hyperswitch_domain_models::router_data::GooglePayPredecryptDataInternal,+ ) -> CustomResult<(), errors::GooglePayDecryptionError> {+ let expected_gateway_merchant_id = self+ .gateway_merchant_id+ .as_ref()+ .ok_or(errors::GooglePayDecryptionError::InvalidGatewayMerchantId)+ .attach_printable(+ "gateway merchant id is not set on the decryptor for an INTERNAL_GATEWAY token",+ )?;++ let token_gateway_merchant_id = decrypted_data+ .gateway_merchant_id+ .as_ref()+ .ok_or(errors::GooglePayDecryptionError::InvalidGatewayMerchantId)+ .attach_printable(+ "decrypted INTERNAL_GATEWAY token does not carry a gateway merchant id",+ )?;++ if token_gateway_merchant_id != expected_gateway_merchant_id {+ logger::warn!(+ expected_gateway_merchant_id,+ token_gateway_merchant_id,+ "gateway merchant id in the token does not match the merchant"+ );+ Err(errors::GooglePayDecryptionError::InvalidGatewayMerchantId)+ .attach_printable("gateway merchant id in the token does not match the merchant")?;+ }++ Ok(())+ }// Verify the signature of the tokenfn verify_signature(&self,diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 81639eccad..10929cfbed 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -3,9 +3,9 @@ use std::{collections::HashMap, str::FromStr};use api_models::payments::{AdditionalCardInfo, AdditionalPaymentData, AmountInfo, ApplePayAddressParameters,ApplePayPaymentRequest, ApplePaySessionResponse, ApplepaySessionTokenResponse,- GooglePaySessionResponse, GpayAllowedMethodsParameters, GpayAllowedPaymentMethods,- GpayBillingAddressFormat, GpayBillingAddressParameters, GpayMerchantInfo,- GpaySessionTokenResponse, GpayShippingAddressParameters, GpayTokenParameters,+ GooglePaySessionResponse, GooglePayTokenizationSpecificationType, GpayAllowedMethodsParameters,+ GpayAllowedPaymentMethods, GpayBillingAddressFormat, GpayBillingAddressParameters,+ GpayMerchantInfo, GpaySessionTokenResponse, GpayShippingAddressParameters, GpayTokenParameters,GpayTokenizationSpecification, GpayTransactionInfo, NextActionCall, PaypalFlow,PaypalSessionTokenResponse, PaypalTransactionInfo, RecipientAccount, RecipientBankAccount,RecipientDetails, SdkNextAction, SecretInfoToInitiateSdk, SessionToken,@@ -7168,7 +7168,11 @@ impl transformers::ForeignTryFrom<payments_grpc::GpayTokenizationSpecification>value: payments_grpc::GpayTokenizationSpecification,) -> Result<Self, Self::Error> {Ok(Self {- token_specification_type: value.token_specification_type,+ token_specification_type: GooglePayTokenizationSpecificationType::from_str(+ &value.token_specification_type,+ )+ .change_context(UnifiedConnectorServiceError::ParsingFailed)+ .attach_printable("invalid gpay token_specification_type received from ucs")?,parameters: value.parameters.map(GpayTokenParameters::foreign_try_from)diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 98dad56122..14d805cf8d 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -219,6 +219,13 @@ impl SessionState {request_id: self.request_id.as_ref().map(|req_id| req_id.to_string()),}}+ /// Gateway identifier of Hyperswitch's own Google Pay gateway registration.+ pub fn google_pay_gateway_id(&self) -> Option<String> {+ self.conf+ .google_pay_decrypt_keys+ .as_ref()+ .and_then(|google_pay_keys| google_pay_keys.get_inner().google_pay_gateway_id.clone())+ }}pub trait SessionStateInfo {