Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(core): google pay decrypt flow (#6991)

Sakil Mostake0ec27d936fc
diff --git a/.deepsource.toml b/.deepsource.toml
index 3cac181614..8d0b3c501a 100644
--- a/.deepsource.toml
+++ b/.deepsource.toml
@@ -13,4 +13,4 @@ name = "rust"
enabled = true
[analyzers.meta]
-msrv = "1.78.0"
+msrv = "1.80.0"
diff --git a/Cargo.lock b/Cargo.lock
index 7583fb2eee..7e2ab6eccd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1528,6 +1528,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "base64-serde"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77c6d128af408d8ebd08331f0331cf2cf20d19e6c44a7aec58791641ecc8c0b5"
+
[[package]]
name = "base64-simd"
version = "0.8.0"
@@ -2044,6 +2050,7 @@ version = "0.1.0"
dependencies = [
"async-trait",
"base64 0.22.1",
+ "base64-serde",
"blake3",
"bytes 1.7.1",
"common_enums",
@@ -6581,6 +6588,7 @@ dependencies = [
"external_services",
"futures 0.3.30",
"hex",
+ "hkdf",
"http 0.2.12",
"hyper 0.14.30",
"hyperswitch_connectors",
@@ -6629,6 +6637,7 @@ dependencies = [
"serde_with",
"serial_test",
"sha1",
+ "sha2",
"storage_impl",
"strum 0.26.3",
"tera",
diff --git a/Cargo.toml b/Cargo.toml
index dc60c64f66..94e717c5b7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
resolver = "2"
members = ["crates/*"]
package.edition = "2021"
-package.rust-version = "1.78.0"
+package.rust-version = "1.80.0"
package.license = "Apache-2.0"
[workspace.dependencies]
diff --git a/INSTALL_dependencies.sh b/INSTALL_dependencies.sh
index e1d666b97a..bc7d502b35 100755
--- a/INSTALL_dependencies.sh
+++ b/INSTALL_dependencies.sh
@@ -9,7 +9,7 @@ if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
-RUST_MSRV="1.78.0"
+RUST_MSRV="1.80.0"
_DB_NAME="hyperswitch_db"
_DB_USER="db_user"
_DB_PASS="db_password"
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index b315800b08..447010178d 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -6875,6 +6875,11 @@
"type": "object",
"description": "This field contains the Paze certificates and credentials",
"nullable": true
+ },
+ "google_pay": {
+ "type": "object",
+ "description": "This field contains the Google Pay certificates and credentials",
+ "nullable": true
}
},
"additionalProperties": false
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 0aa2c898fc..fa631eee78 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -9523,6 +9523,11 @@
"type": "object",
"description": "This field contains the Paze certificates and credentials",
"nullable": true
+ },
+ "google_pay": {
+ "type": "object",
+ "description": "This field contains the Google Pay certificates and credentials",
+ "nullable": true
}
},
"additionalProperties": false
diff --git a/config/config.example.toml b/config/config.example.toml
index b76905eb53..c113d7abd5 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -607,6 +607,9 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" # Private key
paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365
paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem
+[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)
+
[applepay_merchant_configs]
# Run below command to get common merchant identifier for applepay in shell
#
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 8c846ff422..4e5fa3dba4 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -34,6 +34,9 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" # Private key
paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365
paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem
+[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)
+
[applepay_merchant_configs]
common_merchant_identifier = "APPLE_PAY_COMMON_MERCHANT_IDENTIFIER" # Refer to config.example.toml to learn how you can generate this value
merchant_cert = "APPLE_PAY_MERCHANT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate
diff --git a/config/development.toml b/config/development.toml
index 8209d49565..2b81123d87 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -671,6 +671,9 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY"
paze_private_key = "PAZE_PRIVATE_KEY"
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)
+
[generic_link]
[generic_link.payment_method_collect]
sdk_url = "http://localhost:9050/HyperLoader.js"
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 321ee5305f..e47f7826d5 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1468,6 +1468,10 @@ pub struct ConnectorWalletDetails {
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<Object>)]
pub paze: Option<pii::SecretSerdeValue>,
+ /// This field contains the Google Pay certificates and credentials
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub google_pay: Option<pii::SecretSerdeValue>,
}
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 2c8723857a..3a6fe000af 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -5984,6 +5984,57 @@ pub struct SessionTokenForSimplifiedApplePay {
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayWalletDetails {
+ pub google_pay: GooglePayDetails,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayDetails {
+ pub provider_details: GooglePayProviderDetails,
+}
+
+// Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails
+// GooglePayHyperSwitchDetails is not implemented yet
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(untagged)]
+pub enum GooglePayProviderDetails {
+ GooglePayMerchantDetails(GooglePayMerchantDetails),
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayMerchantDetails {
+ pub merchant_info: GooglePayMerchantInfo,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayMerchantInfo {
+ pub merchant_name: String,
+ pub tokenization_specification: GooglePayTokenizationSpecification,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayTokenizationSpecification {
+ #[serde(rename = "type")]
+ pub tokenization_type: GooglePayTokenizationType,
+ pub parameters: GooglePayTokenizationParameters,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum GooglePayTokenizationType {
+ PaymentGateway,
+ Direct,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayTokenizationParameters {
+ pub gateway: String,
+ pub public_key: Secret<String>,
+ pub private_key: Secret<String>,
+ pub recipient_id: Option<Secret<String>>,
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(tag = "wallet_name")]
#[serde(rename_all = "snake_case")]
diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rs
index 91cb93301a..0c0fb9d47a 100644
--- a/crates/cards/src/lib.rs
+++ b/crates/cards/src/lib.rs
@@ -35,7 +35,7 @@ impl<'de> Deserialize<'de> for CardSecurityCode {
}
}
-#[derive(Serialize)]
+#[derive(Clone, Debug, Serialize)]
pub struct CardExpirationMonth(StrongSecret<u8>);
impl CardExpirationMonth {
@@ -67,7 +67,7 @@ impl<'de> Deserialize<'de> for CardExpirationMonth {
}
}
-#[derive(Serialize)]
+#[derive(Clone, Debug, Serialize)]
pub struct CardExpirationYear(StrongSecret<u16>);
impl CardExpirationYear {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index c30c9ec9f1..2f5249ded5 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3675,3 +3675,13 @@ pub enum FeatureStatus {
NotSupported,
Supported,
}
+
+#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum GooglePayAuthMethod {
+ /// Contain pan data only
+ PanOnly,
+ /// Contain cryptogram data along with pan data
+ #[serde(rename = "CRYPTOGRAM_3DS")]
+ Cryptogram,
+}
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index dcdb4c760b..3d31c7a6a9 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -26,6 +26,7 @@ payment_methods_v2 = []
[dependencies]
async-trait = { version = "0.1.79", optional = true }
base64 = "0.22.0"
+base64-serde = "0.8.0"
blake3 = { version = "1.5.1", features = ["serde"] }
bytes = "1.6.0"
diesel = "2.2.3"
diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs
index 63ef30011f..06087f082e 100644
--- a/crates/common_utils/src/custom_serde.rs
+++ b/crates/common_utils/src/custom_serde.rs
@@ -203,8 +203,20 @@ pub mod timestamp {
/// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860>
pub mod json_string {
- use serde::de::{self, Deserialize, DeserializeOwned, Deserializer};
- use serde_json;
+ use serde::{
+ de::{self, Deserialize, DeserializeOwned, Deserializer},
+ ser::{self, Serialize, Serializer},
+ };
+
+ /// Serialize a type to json_string format
+ pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ T: Serialize,
+ S: Serializer,
+ {
+ let j = serde_json::to_string(value).map_err(ser::Error::custom)?;
+ j.serialize(serializer)
+ }
/// Deserialize a string which is in json format
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index 463ec3ee1b..fd0c935035 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -35,6 +35,8 @@ pub mod hashing;
#[cfg(feature = "metrics")]
pub mod metrics;
+pub use base64_serializer::Base64Serializer;
+
/// Date-time utilities.
pub mod date_time {
#[cfg(feature = "async_ext")]
@@ -296,6 +298,14 @@ pub trait DbConnectionParams {
}
}
+// Can't add doc comments for macro invocations, neither does the macro allow it.
+#[allow(missing_docs)]
+mod base64_serializer {
+ use base64_serde::base64_serde_type;
+
+ base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE);
+}
+
#[cfg(test)]
mod nanoid_tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
index 3602f77192..b33555a7c5 100644
--- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
@@ -962,6 +962,12 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>>
PaymentMethodToken::PazeDecrypt(_) => Err(
unimplemented_payment_method!("Paze", "Bank Of America"),
)?,
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!(
+ "Google Pay",
+ "Bank Of America"
+ ))?
+ }
},
None => {
let email = item.router_data.request.get_email()?;
@@ -2279,6 +2285,10 @@ impl TryFrom<(&SetupMandateRouterData, ApplePayWalletData)> for BankOfAmericaPay
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Bank Of America"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => Err(unimplemented_payment_method!(
+ "Google Pay",
+ "Bank Of America"
+ ))?,
},
None => PaymentInformation::from(&apple_pay_data),
};
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
index 5fc9cad4ff..b14ffc9c79 100644
--- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
@@ -24,7 +24,8 @@ use hyperswitch_domain_models::{
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
- ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData,
+ ConnectorResponseData, ErrorResponse, GooglePayDecryptedData, PaymentMethodToken,
+ RouterData,
},
router_flow_types::{
payments::Authorize,
@@ -196,9 +197,9 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: decrypt_data.application_primary_account_number,
- cryptogram: decrypt_data
- .payment_data
- .online_payment_cryptogram,
+ cryptogram: Some(
+ decrypt_data.payment_data.online_payment_cryptogram,
+ ),
transaction_type: TransactionType::ApplePay,
expiration_year,
expiration_month,
@@ -216,6 +217,9 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
+ }
},
None => (
PaymentInformation::ApplePayToken(Box::new(
@@ -233,15 +237,17 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
),
},
WalletData::GooglePay(google_pay_data) => (
- PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
- fluid_data: FluidData {
- value: Secret::from(
- consts::BASE64_ENGINE
- .encode(google_pay_data.tokenization_data.token),
- ),
- descriptor: None,
+ PaymentInformation::GooglePayToken(Box::new(
+ GooglePayTokenPaymentInformation {
+ fluid_data: FluidData {
+ value: Secret::from(
+ consts::BASE64_ENGINE
+ .encode(google_pay_data.tokenization_data.token),
+ ),
+ descriptor: None,
+ },
},
- })),
+ )),
Some(PaymentSolution::GooglePay),
),
WalletData::AliPayQr(_)
@@ -448,7 +454,7 @@ pub struct TokenizedCard {
number: Secret<String>,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
- cryptogram: Secret<String>,
+ cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
@@ -491,10 +497,16 @@ pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAP
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct GooglePayPaymentInformation {
+pub struct GooglePayTokenPaymentInformation {
fluid_data: FluidData,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePayPaymentInformation {
+ tokenized_card: TokenizedCard,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayTokenizedCard {
@@ -520,6 +532,7 @@ pub struct SamsungPayFluidDataValue {
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
+ GooglePayToken(Box<GooglePayTokenPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
@@ -588,6 +601,8 @@ pub enum TransactionType {
ApplePay,
#[serde(rename = "1")]
SamsungPay,
+ #[serde(rename = "1")]
+ GooglePay,
}
impl From<PaymentSolution> for String {
@@ -1645,7 +1660,7 @@ impl
PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: apple_pay_data.application_primary_account_number,
- cryptogram: apple_pay_data.payment_data.online_payment_cryptogram,
+ cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram),
transaction_type: TransactionType::ApplePay,
expiration_year,
expiration_month,
@@ -1707,7 +1722,7 @@ impl
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information =
- PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
+ PaymentInformation::GooglePayToken(Box::new(GooglePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token),
@@ -1736,6 +1751,92 @@ impl
}
}
+impl
+ TryFrom<(
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ Box<GooglePayDecryptedData>,
+ GooglePayWalletData,
+ )> for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, google_pay_decrypted_data, google_pay_data): (
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ Box<GooglePayDecryptedData>,
+ GooglePayWalletData,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let email = item
+ .router_data
+ .get_billing_email()
+ .or(item.router_data.request.get_email())?;
+ let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
+ let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
+
+ let payment_information =
+ PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
+ tokenized_card: TokenizedCard {
+ number: Secret::new(
+ google_pay_decrypted_data
+ .payment_method_details
+ .pan
+ .get_card_no(),
+ ),
+ cryptogram: google_pay_decrypted_data.payment_method_details.cryptogram,
+ transaction_type: TransactionType::GooglePay,
+ expiration_year: Secret::new(
+ google_pay_decrypted_data
+ .payment_method_details
+ .expiration_year
+ .four_digits(),
+ ),
+ expiration_month: Secret::new(
+ google_pay_decrypted_data
+ .payment_method_details
+ .expiration_month
+ .two_digits(),
+ ),
+ },
+ }));
+ let processing_information = ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::GooglePay),
+ Some(google_pay_data.info.card_network.clone()),
+ ))?;
+ let client_reference_information = ClientReferenceInformation::from(item);
+ let merchant_defined_information = item
+ .router_data
+ .request
+ .metadata
+ .clone()
+ .map(convert_metadata_to_merchant_defined_info);
+
+ let ucaf_collection_indicator =
+ match google_pay_data.info.card_network.to_lowercase().as_str() {
+ "mastercard" => Some("2".to_string()),
+ _ => None,
+ };
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ consumer_authentication_information: Some(CybersourceConsumerAuthInformation {
+ ucaf_collection_indicator,
+ cavv: None,
+ ucaf_authentication_data: None,
+ xid: None,
+ directory_server_transaction_id: None,
+ specification_version: None,
+ pa_specification_version: None,
+ veres_enrolled: None,
+ }),
+ merchant_defined_information,
+ })
+ }
+}
+
impl
TryFrom<(
&CybersourceRouterData<&PaymentsAuthorizeRouterData>,
@@ -1850,6 +1951,9 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => Err(
+ unimplemented_payment_method!("Google Pay", "Cybersource"),
+ )?,
},
None => {
let email = item
@@ -1917,7 +2021,31 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour
}
}
WalletData::GooglePay(google_pay_data) => {
- Self::try_from((item, google_pay_data))
+ match item.router_data.payment_method_token.clone() {
+ Some(payment_method_token) => match payment_method_token {
+ PaymentMethodToken::GooglePayDecrypt(decrypt_data) => {
+ Self::try_from((item, decrypt_data, google_pay_data))
+ }
+ PaymentMethodToken::Token(_) => {
+ Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Manual",
+ "Cybersource"
+ ))?
+ }
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Cybersource"))?
+ }
+ PaymentMethodToken::ApplePayDecrypt(_) => {
+ Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Simplified",
+ "Cybersource"
+ ))?
+ }
+ },
+ None => Self::try_from((item, google_pay_data)),
+ }
}
WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((item, samsung_pay_data))
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index 51fc23eee4..115079c7d0 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -500,6 +500,9 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Fiuu"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Fiuu"))?
+ }
}
}
WalletData::AliPayQr(_)
diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
index d64c2ed8ef..f09d30efc9 100644
--- a/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
@@ -437,7 +437,9 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
let payment_method_token = item.get_payment_method_token()?;
let customer_bank_account = match payment_method_token {
PaymentMethodToken::Token(token) => Ok(token),
- PaymentMethodToken::ApplePayDecrypt(_) | PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::ApplePayDecrypt(_)
+ | PaymentMethodToken::PazeDecrypt(_)
+ | PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
index 5a641327c9..fa2cb46c7b 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
@@ -175,6 +175,9 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Mollie"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Mollie"))?
+ }
}),
},
)))
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index 5abc93b3f8..ff3999aee6 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -272,6 +272,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Square"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Square"))?
+ }
},
amount_money: SquarePaymentsAmountData {
amount: item.request.amount,
diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index a675e3040e..327785d2fc 100644
--- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -85,6 +85,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Stax"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Stax"))?
+ }
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
@@ -105,6 +108,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Stax"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Stax"))?
+ }
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
index 6ce9a4d7aa..1a4d3ce8f9 100644
--- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
@@ -153,6 +153,9 @@ impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest {
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Wellsfargo"))?
+ }
},
None => (
PaymentInformation::ApplePayToken(Box::new(
@@ -1173,6 +1176,9 @@ impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for Wellsfargo
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
}
+ PaymentMethodToken::GooglePayDecrypt(_) => Err(
+ unimplemented_payment_method!("Google Pay", "Wellsfargo"),
+ )?,
},
None => {
let email = item.router_data.request.get_email()?;
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 8e4c79a965..322b4aa452 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -226,6 +226,7 @@ pub struct AccessToken {
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<ApplePayPredecryptData>),
+ GooglePayDecrypt(Box<GooglePayDecryptedData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
@@ -248,6 +249,27 @@ pub struct ApplePayCryptogramData {
pub eci_indicator: Option<String>,
}
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePayDecryptedData {
+ pub message_expiration: String,
+ pub message_id: String,
+ #[serde(rename = "paymentMethod")]
+ pub payment_method_type: String,
+ pub payment_method_details: GooglePayPaymentMethodDetails,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePayPaymentMethodDetails {
+ pub auth_method: common_enums::enums::GooglePayAuthMethod,
+ pub expiration_month: cards::CardExpirationMonth,
+ pub expiration_year: cards::CardExpirationYear,
+ pub pan: cards::CardNumber,
+ pub cryptogram: Option<Secret<String>>,
+ pub eci_indicator: Option<String>,
+}
+
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDecryptedData {
diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs
index 0bd28c3af9..7f7c18094a 100644
--- a/crates/masking/src/secret.rs
+++ b/crates/masking/src/secret.rs
@@ -156,3 +156,10 @@ where
SecretValue::default().into()
}
}
+
+// Required by base64-serde to serialize Secret of Vec<u8> which contains the base64 decoded value
+impl AsRef<[u8]> for Secret<Vec<u8>> {
+ fn as_ref(&self) -> &[u8] {
+ self.peek().as_slice()
+ }
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index db65482628..7db0273d2e 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -68,6 +68,7 @@ encoding_rs = "0.8.33"
error-stack = "0.4.1"
futures = "0.3.30"
hex = "0.4.3"
+hkdf = "0.12.4"
http = "0.2.12"
hyper = "0.14.28"
infer = "0.15.0"
@@ -104,6 +105,7 @@ serde_repr = "0.1.19"
serde_urlencoded = "0.7.1"
serde_with = "3.7.0"
sha1 = { version = "0.10.6" }
+sha2 = "0.10.8"
strum = { version = "0.26", features = ["derive"] }
tera = "1.19.1"
thiserror = "1.0.58"
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 7b74aca764..f51a785eaa 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -199,6 +199,24 @@ 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();
+
+ let google_pay_root_signing_keys = secret_management_client
+ .get_secret(google_pay_decrypt_keys.google_pay_root_signing_keys.clone())
+ .await?;
+
+ Ok(value.transition_state(|_| Self {
+ google_pay_root_signing_keys,
+ }))
+ }
+}
+
#[async_trait::async_trait]
impl SecretsHandler for settings::ApplepayMerchantConfigs {
async fn convert_to_raw_secret(
@@ -420,6 +438,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,
@@ -512,6 +544,7 @@ pub(crate) async fn fetch_raw_secrets(
payouts: conf.payouts,
applepay_decrypt_keys,
paze_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.rs
index fa3d004aad..d721a4db96 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -99,6 +99,7 @@ pub struct Settings<S: SecretState> {
pub payout_method_filters: ConnectorFilters,
pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,
pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,
+ 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,
@@ -758,6 +759,11 @@ pub struct PazeDecryptConfig {
pub paze_private_key_passphrase: Secret<String>,
}
+#[derive(Debug, Deserialize, Clone)]
+pub struct GooglePayDecryptConfig {
+ pub google_pay_root_signing_keys: Secret<String>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LockerBasedRecipientConnectorList {
@@ -911,6 +917,11 @@ impl Settings<SecuredSecret> {
.map(|x| x.get_inner().validate())
.transpose()?;
+ self.google_pay_decrypt_keys
+ .as_ref()
+ .map(|x| x.get_inner().validate())
+ .transpose()?;
+
self.key_manager.get_inner().validate()?;
#[cfg(feature = "email")]
self.email
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 7040998ccf..11aa4e0cf5 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -257,6 +257,21 @@ impl super::settings::PazeDecryptConfig {
}
}
+impl super::settings::GooglePayDecryptConfig {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::fp_utils::when;
+
+ when(
+ self.google_pay_root_signing_keys.is_default_or_empty(),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "google_pay_root_signing_keys must not be empty".into(),
+ ))
+ },
+ )
+ }
+}
+
impl super::settings::KeyManagerConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 00624ce0f9..5dd6db5aa2 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -1598,6 +1598,9 @@ impl
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
+ }
},
transaction: transaction_body,
},
@@ -1699,6 +1702,9 @@ fn get_braintree_redirect_form(
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
+ }
},
bin: match card_details {
domain::PaymentMethodData::Card(card_details) => {
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index cd758fffb6..bb38ef7483 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -307,6 +307,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
+ }
},
})),
domain::WalletData::ApplePay(_) => {
@@ -336,6 +339,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
+ }
}
}
domain::WalletData::AliPayQr(_)
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index cd8ba814eb..7e50f7f40e 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -729,6 +729,9 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Payme"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Payme"))?
+ }
};
Ok(Self {
buyer_email,
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 48736c00e7..6085277988 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1840,6 +1840,9 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(crate::unimplemented_payment_method!("Paze", "Stripe"))?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))?
+ }
};
Some(StripePaymentMethodData::Wallet(
StripeWallet::ApplepayPayment(ApplepayPayment {
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 96321d0979..b4c1c1c2c0 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -244,6 +244,60 @@ pub enum PazeDecryptionError {
CertificateParsingFailed,
}
+#[derive(Debug, thiserror::Error)]
+pub enum GooglePayDecryptionError {
+ #[error("Recipient ID not found")]
+ RecipientIdNotFound,
+ #[error("Invalid expiration time")]
+ InvalidExpirationTime,
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed,
+ #[error("Failed to decrypt input data")]
+ DecryptionFailed,
+ #[error("Failed to deserialize input data")]
+ DeserializationFailed,
+ #[error("Certificate parsing failed")]
+ CertificateParsingFailed,
+ #[error("Key deserialization failure")]
+ KeyDeserializationFailed,
+ #[error("Failed to derive a shared ephemeral key")]
+ DerivingSharedEphemeralKeyFailed,
+ #[error("Failed to derive a shared secret key")]
+ DerivingSharedSecretKeyFailed,
+ #[error("Failed to parse the tag")]
+ ParsingTagError,
+ #[error("HMAC verification failed")]
+ HmacVerificationFailed,
+ #[error("Failed to derive Elliptic Curve key")]
+ DerivingEcKeyFailed,
+ #[error("Failed to Derive Public key")]
+ DerivingPublicKeyFailed,
+ #[error("Failed to Derive Elliptic Curve group")]
+ DerivingEcGroupFailed,
+ #[error("Failed to allocate memory for big number")]
+ BigNumAllocationFailed,
+ #[error("Failed to get the ECDSA signature")]
+ EcdsaSignatureFailed,
+ #[error("Failed to verify the signature")]
+ SignatureVerificationFailed,
+ #[error("Invalid signature is provided")]
+ InvalidSignature,
+ #[error("Failed to parse the Signed Key")]
+ SignedKeyParsingFailure,
+ #[error("The Signed Key is expired")]
+ SignedKeyExpired,
+ #[error("Failed to parse the ECDSA signature")]
+ EcdsaSignatureParsingFailed,
+ #[error("Invalid intermediate signature is provided")]
+ InvalidIntermediateSignature,
+ #[error("Invalid protocol version")]
+ InvalidProtocolVersion,
+ #[error("Decrypted Token has expired")]
+ DecryptedTokenExpired,
+ #[error("Failed to parse the given value")]
+ ParsingFailed,
+}
+
#[cfg(feature = "detailed_errors")]
pub mod error_stack_parsing {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e9d3c01378..5b8988dace 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3080,7 +3080,61 @@ where
paze_decrypted_data,
))))
}
- _ => Ok(None),
+ TokenizationAction::DecryptGooglePayToken(payment_processing_details) => {
+ let google_pay_data = match payment_data.get_payment_method_data() {
+ Some(domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(
+ wallet_data,
+ ))) => {
+ let decryptor = helpers::GooglePayTokenDecryptor::new(
+ payment_processing_details
+ .google_pay_root_signing_keys
+ .clone(),
+ payment_processing_details.google_pay_recipient_id.clone(),
+ payment_processing_details.google_pay_private_key.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to create google pay token decryptor")?;
+
+ // should_verify_token is set to false to disable verification of token
+ Some(
+ decryptor
+ .decrypt_token(wallet_data.tokenization_data.token.clone(), false)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to decrypt google pay token")?,
+ )
+ }
+ Some(payment_method_data) => {
+ logger::info!(
+ "Invalid payment_method_data found for Google Pay Decrypt Flow: {:?}",
+ payment_method_data.get_payment_method()
+ );
+ None
+ }
+ None => {
+ logger::info!("No payment_method_data found for Google Pay Decrypt Flow");
+ None
+ }
+ };
+
+ let google_pay_predecrypt = google_pay_data
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to get GooglePayDecryptedData in response")?;
+
+ Ok(Some(PaymentMethodToken::GooglePayDecrypt(Box::new(
+ google_pay_predecrypt,
+ ))))
+ }
+ TokenizationAction::ConnectorToken(_) => {
+ logger::info!("Invalid tokenization action found for decryption flow: ConnectorToken",);
+ Ok(None)
+ }
+ token_action => {
+ logger::info!(
+ "Invalid tokenization action found for decryption flow: {:?}",
+ token_action
+ );
+ Ok(None)
+ }
}
}
@@ -4052,6 +4106,64 @@ fn check_apple_pay_metadata(
})
}
+fn get_google_pay_connector_wallet_details(
+ state: &SessionState,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+) -> Option<GooglePayPaymentProcessingDetails> {
+ let google_pay_root_signing_keys =
+ state
+ .conf
+ .google_pay_decrypt_keys
+ .as_ref()
+ .map(|google_pay_keys| {
+ google_pay_keys
+ .get_inner()
+ .google_pay_root_signing_keys
+ .clone()
+ });
+ match (
+ google_pay_root_signing_keys,
+ merchant_connector_account.get_connector_wallets_details(),
+ ) {
+ (Some(google_pay_root_signing_keys), Some(wallet_details)) => {
+ let google_pay_wallet_details = wallet_details
+ .parse_value::<api_models::payments::GooglePayWalletDetails>(
+ "GooglePayWalletDetails",
+ )
+ .map_err(|error| {
+ logger::warn!(?error, "Failed to Parse Value to GooglePayWalletDetails")
+ });
+
+ google_pay_wallet_details
+ .ok()
+ .map(
+ |google_pay_wallet_details| {
+ match google_pay_wallet_details
+ .google_pay
+ .provider_details {
+ api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => {
+ GooglePayPaymentProcessingDetails {
+ google_pay_private_key: merchant_details
+ .merchant_info
+ .tokenization_specification
+ .parameters
+ .private_key,
+ google_pay_root_signing_keys,
+ google_pay_recipient_id: merchant_details
+ .merchant_info
+ .tokenization_specification
+ .parameters
+ .recipient_id,
+ }
+ }
+ }
+ }
+ )
+ }
+ _ => None,
+ }
+}
+
fn is_payment_method_type_allowed_for_connector(
current_pm_type: Option<storage::enums::PaymentMethodType>,
pm_type_filter: Option<PaymentMethodTypeTokenFilter>,
@@ -4066,6 +4178,7 @@ fn is_payment_method_type_allowed_for_connector(
}
}
+#[allow(clippy::too_many_arguments)]
async fn decide_payment_method_tokenize_action(
state: &SessionState,
connector_name: &str,
@@ -4074,6 +4187,7 @@ async fn decide_payment_method_tokenize_action(
is_connector_tokenization_enabled: bool,
apple_pay_flow: Option<domain::ApplePayFlow>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<TokenizationAction> {
if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type {
// Paze generates a one time use network token which should not be tokenized in the connector or router.
@@ -4090,6 +4204,20 @@ async fn decide_payment_method_tokenize_action(
None => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Paze configs"),
}
+ } else if let Some(storage_enums::PaymentMethodType::GooglePay) = payment_method_type {
+ let google_pay_details =
+ get_google_pay_connector_wallet_details(state, merchant_connector_account);
+
+ match google_pay_details {
+ Some(wallet_details) => Ok(TokenizationAction::DecryptGooglePayToken(wallet_details)),
+ None => {
+ if is_connector_tokenization_enabled {
+ Ok(TokenizationAction::TokenizeInConnectorAndRouter)
+ } else {
+ Ok(TokenizationAction::TokenizeInRouter)
+ }
+ }
+ }
} else {
match pm_parent_token {
None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
@@ -4154,6 +4282,13 @@ pub struct PazePaymentProcessingDetails {
pub paze_private_key_passphrase: Secret<String>,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GooglePayPaymentProcessingDetails {
+ pub google_pay_private_key: Secret<String>,
+ pub google_pay_root_signing_keys: Secret<String>,
+ pub google_pay_recipient_id: Option<Secret<String>>,
+}
+
#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInRouter,
@@ -4164,6 +4299,7 @@ pub enum TokenizationAction {
DecryptApplePayToken(payments_api::PaymentProcessingDetails),
TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails),
DecryptPazeToken(PazePaymentProcessingDetails),
+ DecryptGooglePayToken(GooglePayPaymentProcessingDetails),
}
#[cfg(feature = "v2")]
@@ -4254,6 +4390,7 @@ where
is_connector_tokenization_enabled,
apple_pay_flow,
payment_method_type,
+ merchant_connector_account,
)
.await?;
@@ -4312,6 +4449,11 @@ where
TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => {
TokenizationAction::DecryptPazeToken(paze_payment_processing_details)
}
+ TokenizationAction::DecryptGooglePayToken(
+ google_pay_payment_processing_details,
+ ) => {
+ TokenizationAction::DecryptGooglePayToken(google_pay_payment_processing_details)
+ }
};
(payment_data.to_owned(), connector_tokenization_action)
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0d7a3b57fc..56667b0517 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -47,6 +47,7 @@ use openssl::{
};
#[cfg(feature = "v2")]
use redis_interface::errors::RedisError;
+use ring::hmac;
use router_env::{instrument, logger, tracing};
use uuid::Uuid;
use x509_parser::parse_x509_certificate;
@@ -5073,6 +5074,9 @@ async fn get_and_merge_apple_pay_metadata(
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
+ google_pay: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.google_pay.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
@@ -5091,6 +5095,9 @@ async fn get_and_merge_apple_pay_metadata(
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
+ google_pay: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.google_pay.clone()),
}
}
};
@@ -5427,6 +5434,543 @@ impl ApplePayData {
}
}
+pub(crate) const SENDER_ID: &[u8] = b"Google";
+pub(crate) const PROTOCOL: &str = "ECv2";
+
+// Structs for keys and the main decryptor
+pub struct GooglePayTokenDecryptor {
+ root_signing_keys: Vec<GooglePayRootSigningKey>,
+ recipient_id: Option<masking::Secret<String>>,
+ private_key: PKey<openssl::pkey::Private>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct EncryptedData {
+ signature: String,
+ intermediate_signing_key: IntermediateSigningKey,
+ protocol_version: GooglePayProtocolVersion,
+ #[serde(with = "common_utils::custom_serde::json_string")]
+ signed_message: GooglePaySignedMessage,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePaySignedMessage {
+ #[serde(with = "common_utils::Base64Serializer")]
+ encrypted_message: masking::Secret<Vec<u8>>,
+ #[serde(with = "common_utils::Base64Serializer")]
+ ephemeral_public_key: masking::Secret<Vec<u8>>,
+ #[serde(with = "common_utils::Base64Serializer")]
+ tag: masking::Secret<Vec<u8>>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IntermediateSigningKey {
+ signed_key: masking::Secret<String>,
+ signatures: Vec<masking::Secret<String>>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePaySignedKey {
+ key_value: masking::Secret<String>,
+ key_expiration: String,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GooglePayRootSigningKey {
+ key_value: masking::Secret<String>,
+ key_expiration: String,
+ protocol_version: GooglePayProtocolVersion,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
+pub enum GooglePayProtocolVersion {
+ #[serde(rename = "ECv2")]
+ EcProtocolVersion2,
+}
+
+// Check expiration date validity
+fn check_expiration_date_is_valid(
+ expiration: &str,
+) -> CustomResult<bool, errors::GooglePayDecryptionError> {
+ let expiration_ms = expiration
+ .parse::<i128>()
+ .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
+ // convert milliseconds to nanoseconds (1 millisecond = 1_000_000 nanoseconds) to create OffsetDateTime
+ let expiration_time =
+ time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000)
+ .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
+ let now = time::OffsetDateTime::now_utc();
+
+ Ok(expiration_time > now)
+}
+
+// Construct little endian format of u32
+fn get_little_endian_format(number: u32) -> Vec<u8> {
+ number.to_le_bytes().to_vec()
+}
+
+// Filter and parse the root signing keys based on protocol version and expiration time
+fn filter_root_signing_keys(
+ root_signing_keys: Vec<GooglePayRootSigningKey>,
+) -> CustomResult<Vec<GooglePayRootSigningKey>, errors::GooglePayDecryptionError> {
+ let filtered_root_signing_keys = root_signing_keys
+ .iter()
+ .filter(|key| {
+ key.protocol_version == GooglePayProtocolVersion::EcProtocolVersion2
+ && matches!(
+ check_expiration_date_is_valid(&key.key_expiration).inspect_err(
+ |err| logger::warn!(
+ "Failed to check expirattion due to invalid format: {:?}",
+ err
+ )
+ ),
+ Ok(true)
+ )
+ })
+ .cloned()
+ .collect::<Vec<GooglePayRootSigningKey>>();
+
+ logger::info!(
+ "Filtered {} out of {} root signing keys",
+ filtered_root_signing_keys.len(),
+ root_signing_keys.len()
+ );
+
+ Ok(filtered_root_signing_keys)
+}
+
+impl GooglePayTokenDecryptor {
+ pub fn new(
+ root_keys: masking::Secret<String>,
+ recipient_id: Option<masking::Secret<String>>,
+ private_key: masking::Secret<String>,
+ ) -> CustomResult<Self, errors::GooglePayDecryptionError> {
+ // base64 decode the private key
+ let decoded_key = BASE64_ENGINE
+ .decode(private_key.expose())
+ .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
+ // create a private key from the decoded key
+ let private_key = PKey::private_key_from_pkcs8(&decoded_key)
+ .change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
+ .attach_printable("cannot convert private key from decode_key")?;
+
+ // parse the root signing keys
+ let root_keys_vector: Vec<GooglePayRootSigningKey> = root_keys
+ .expose()
+ .parse_struct("GooglePayRootSigningKey")
+ .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
+
+ // parse and filter the root signing keys by protocol version
+ let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
+
+ Ok(Self {
+ root_signing_keys: filtered_root_signing_keys,
+ recipient_id,
+ private_key,
+ })
+ }
+
+ // Decrypt the Google pay token
+ pub fn decrypt_token(
+ &self,
+ data: String,
+ should_verify_signature: bool,
+ ) -> CustomResult<
+ hyperswitch_domain_models::router_data::GooglePayDecryptedData,
+ errors::GooglePayDecryptionError,
+ > {
+ // parse the encrypted data
+ let encrypted_data: EncryptedData = data
+ .parse_struct("EncryptedData")
+ .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
+
+ // verify the signature if required
+ if should_verify_signature {
+ self.verify_signature(&encrypted_data)?;
+ }
+
+ let ephemeral_public_key = encrypted_data.signed_message.ephemeral_public_key.peek();
+ let tag = encrypted_data.signed_message.tag.peek();
+ let encrypted_message = encrypted_data.signed_message.encrypted_message.peek();
+
+ // derive the shared key
+ let shared_key = self.get_shared_key(ephemeral_public_key)?;
+
+ // derive the symmetric encryption key and MAC key
+ let derived_key = self.derive_key(ephemeral_public_key, &shared_key)?;
+ // First 32 bytes for AES-256 and Remaining bytes for HMAC
+ let (symmetric_encryption_key, mac_key) = derived_key
+ .split_at_checked(32)
+ .ok_or(errors::GooglePayDecryptionError::ParsingFailed)?;
+
+ // verify the HMAC of the message
+ self.verify_hmac(mac_key, tag, encrypted_message)?;
+
+ // decrypt the message
+ let decrypted = self.decrypt_message(symmetric_encryption_key, encrypted_message)?;
+
+ // parse the decrypted data
+ let decrypted_data: hyperswitch_domain_models::router_data::GooglePayDecryptedData =
+ decrypted
+ .parse_struct("GooglePayDecryptedData")
+ .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
+
+ // check the expiration date of the decrypted data
+ if matches!(
+ check_expiration_date_is_valid(&decrypted_data.message_expiration),
+ Ok(true)
+ ) {
+ Ok(decrypted_data)
+ } else {
+ Err(errors::GooglePayDecryptionError::DecryptedTokenExpired.into())
+ }
+ }
+
+ // Verify the signature of the token
+ fn verify_signature(
+ &self,
+ encrypted_data: &EncryptedData,
+ ) -> CustomResult<(), errors::GooglePayDecryptionError> {
+ // check the protocol version
+ if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 {
+ return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into());
+ }
+
+ // verify the intermediate signing key
+ self.verify_intermediate_signing_key(encrypted_data)?;
+ // validate and fetch the signed key
+ let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?;
+ // verify the signature of the token
+ self.verify_message_signature(encrypted_data, &signed_key)
+ }
+
+ // Verify the intermediate signing key
+ fn verify_intermediate_signing_key(
+ &self,
+ encrypted_data: &EncryptedData,
+ ) -> CustomResult<(), errors::GooglePayDecryptionError> {
+ let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new();
+
+ // decode and parse the signatures
+ for signature in encrypted_data.intermediate_signing_key.signatures.iter() {
+ let signature = BASE64_ENGINE
+ .decode(signature.peek())
+ .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
+ let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
+ .change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?;
+ signatrues.push(ecdsa_signature);
+ }
+
+ // get the sender id i.e. Google
+ let sender_id = String::from_utf8(SENDER_ID.to_vec())
+ .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
+
+ // construct the signed data
+ let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification(
+ &sender_id,
+ PROTOCOL,
+ encrypted_data.intermediate_signing_key.signed_key.peek(),
+ )?;
+
+ // check if any of the signatures are valid for any of the root signing keys
+ for key in self.root_signing_keys.iter() {
+ // decode and create public key
+ let public_key = self
+ .load_public_key(key.key_value.peek())
+ .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
+ // fetch the ec key from public key
+ let ec_key = public_key
+ .ec_key()
+ .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
+
+ // hash the signed data
+ let message_hash = openssl::sha::sha256(&signed_data);
+
+ // verify if any of the signatures is valid against the given key
+ for signature in signatrues.iter() {
+ let result = signature.verify(&message_hash, &ec_key).change_context(
+ errors::GooglePayDecryptionError::SignatureVerificationFailed,
+ )?;
+
+ if result {
+ return Ok(());
+ }
+ }
+ }
+
+ Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into())
+ }
+
+ // Construct signed data for intermediate signing key verification
+ fn construct_signed_data_for_intermediate_signing_key_verification(
+ &self,
+ sender_id: &str,
+ protocol_version: &str,
+ signed_key: &str,
+ ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
+ let length_of_sender_id = u32::try_from(sender_id.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+ let length_of_protocol_version = u32::try_from(protocol_version.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+ let length_of_signed_key = u32::try_from(signed_key.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+
+ let mut signed_data: Vec<u8> = Vec::new();
+ signed_data.append(&mut get_little_endian_format(length_of_sender_id));
+ signed_data.append(&mut sender_id.as_bytes().to_vec());
+ signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
+ signed_data.append(&mut protocol_version.as_bytes().to_vec());
+ signed_data.append(&mut get_little_endian_format(length_of_signed_key));
+ signed_data.append(&mut signed_key.as_bytes().to_vec());
+
+ Ok(signed_data)
+ }
+
+ // Validate and parse signed key
+ fn validate_signed_key(
+ &self,
+ intermediate_signing_key: &IntermediateSigningKey,
+ ) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> {
+ let signed_key: GooglePaySignedKey = intermediate_signing_key
+ .signed_key
+ .clone()
+ .expose()
+ .parse_struct("GooglePaySignedKey")
+ .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
+ if !matches!(
+ check_expiration_date_is_valid(&signed_key.key_expiration),
+ Ok(true)
+ ) {
+ return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?;
+ }
+ Ok(signed_key)
+ }
+
+ // Verify the signed message
+ fn verify_message_signature(
+ &self,
+ encrypted_data: &EncryptedData,
+ signed_key: &GooglePaySignedKey,
+ ) -> CustomResult<(), errors::GooglePayDecryptionError> {
+ // create a public key from the intermediate signing key
+ let public_key = self.load_public_key(signed_key.key_value.peek())?;
+ // base64 decode the signature
+ let signature = BASE64_ENGINE
+ .decode(&encrypted_data.signature)
+ .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
+
+ // parse the signature using ECDSA
+ let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
+ .change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?;
+
+ // get the EC key from the public key
+ let ec_key = public_key
+ .ec_key()
+ .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
+
+ // get the sender id i.e. Google
+ let sender_id = String::from_utf8(SENDER_ID.to_vec())
+ .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
+
+ // serialize the signed message to string
+ let signed_message = serde_json::to_string(&encrypted_data.signed_message)
+ .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
+
+ // construct the signed data
+ let signed_data = self.construct_signed_data_for_signature_verification(
+ &sender_id,
+ PROTOCOL,
+ &signed_message,
+ )?;
+
+ // hash the signed data
+ let message_hash = openssl::sha::sha256(&signed_data);
+
+ // verify the signature
+ let result = ecdsa_signature
+ .verify(&message_hash, &ec_key)
+ .change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?;
+
+ if result {
+ Ok(())
+ } else {
+ Err(errors::GooglePayDecryptionError::InvalidSignature)?
+ }
+ }
+
+ // Fetch the public key
+ fn load_public_key(
+ &self,
+ key: &str,
+ ) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> {
+ // decode the base64 string
+ let der_data = BASE64_ENGINE
+ .decode(key)
+ .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
+
+ // parse the DER-encoded data as an EC public key
+ let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
+ .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
+
+ // wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL)
+ let public_key = PKey::from_ec_key(ec_key)
+ .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
+
+ Ok(public_key)
+ }
+
+ // Construct signed data for signature verification
+ fn construct_signed_data_for_signature_verification(
+ &self,
+ sender_id: &str,
+ protocol_version: &str,
+ signed_key: &str,
+ ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
+ let recipient_id = self
+ .recipient_id
+ .clone()
+ .ok_or(errors::GooglePayDecryptionError::RecipientIdNotFound)?
+ .expose();
+ let length_of_sender_id = u32::try_from(sender_id.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+ let length_of_recipient_id = u32::try_from(recipient_id.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+ let length_of_protocol_version = u32::try_from(protocol_version.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+ let length_of_signed_key = u32::try_from(signed_key.len())
+ .change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
+
+ let mut signed_data: Vec<u8> = Vec::new();
+ signed_data.append(&mut get_little_endian_format(length_of_sender_id));
+ signed_data.append(&mut sender_id.as_bytes().to_vec());
+ signed_data.append(&mut get_little_endian_format(length_of_recipient_id));
+ signed_data.append(&mut recipient_id.as_bytes().to_vec());
+ signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
+ signed_data.append(&mut protocol_version.as_bytes().to_vec());
+ signed_data.append(&mut get_little_endian_format(length_of_signed_key));
+ signed_data.append(&mut signed_key.as_bytes().to_vec());
+
+ Ok(signed_data)
+ }
+
+ // Derive a shared key using ECDH
+ fn get_shared_key(
+ &self,
+ ephemeral_public_key_bytes: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
+ let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1)
+ .change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?;
+
+ let mut big_num_context = openssl::bn::BigNumContext::new()
+ .change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?;
+
+ let ec_key = openssl::ec::EcPoint::from_bytes(
+ &group,
+ ephemeral_public_key_bytes,
+ &mut big_num_context,
+ )
+ .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
+
+ // create an ephemeral public key from the given bytes
+ let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key)
+ .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
+
+ // wrap the public key in a PKey
+ let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key)
+ .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
+
+ // perform ECDH to derive the shared key
+ let mut deriver = Deriver::new(&self.private_key)
+ .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
+
+ deriver
+ .set_peer(&ephemeral_pkey)
+ .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
+
+ let shared_key = deriver
+ .derive_to_vec()
+ .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
+
+ Ok(shared_key)
+ }
+
+ // Derive symmetric key and MAC key using HKDF
+ fn derive_key(
+ &self,
+ ephemeral_public_key_bytes: &[u8],
+ shared_key: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
+ // concatenate ephemeral public key and shared key
+ let input_key_material = [ephemeral_public_key_bytes, shared_key].concat();
+
+ // initialize HKDF with SHA-256 as the hash function
+ // Salt is not provided as per the Google Pay documentation
+ // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
+ let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material);
+
+ // derive 64 bytes for the output key (symmetric encryption + MAC key)
+ let mut output_key = vec![0u8; 64];
+ hkdf.expand(SENDER_ID, &mut output_key).map_err(|err| {
+ logger::error!(
+ "Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}",
+ err
+ );
+ report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed)
+ })?;
+
+ Ok(output_key)
+ }
+
+ // Verify the Hmac key
+ // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
+ fn verify_hmac(
+ &self,
+ mac_key: &[u8],
+ tag: &[u8],
+ encrypted_message: &[u8],
+ ) -> CustomResult<(), errors::GooglePayDecryptionError> {
+ let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, mac_key);
+ hmac::verify(&hmac_key, encrypted_message, tag)
+ .change_context(errors::GooglePayDecryptionError::HmacVerificationFailed)
+ }
+
+ // Method to decrypt the AES-GCM encrypted message
+ fn decrypt_message(
+ &self,
+ symmetric_key: &[u8],
+ encrypted_message: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
+ //initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process.
+ // zero iv is being passed as specified in Google Pay documentation
+ // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token
+ let iv = [0u8; 16];
+
+ // extract the tag from the end of the encrypted message
+ let tag = encrypted_message
+ .get(encrypted_message.len() - 16..)
+ .ok_or(errors::GooglePayDecryptionError::ParsingTagError)?;
+
+ // decrypt the message using AES-256-CTR
+ let cipher = Cipher::aes_256_ctr();
+ let decrypted_data = decrypt_aead(
+ cipher,
+ symmetric_key,
+ Some(&iv),
+ &[],
+ encrypted_message,
+ tag,
+ )
+ .change_context(errors::GooglePayDecryptionError::DecryptionFailed)?;
+
+ Ok(decrypted_data)
+ }
+}
+
pub fn decrypt_paze_token(
paze_wallet_data: PazeWalletData,
paze_private_key: masking::Secret<String>,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 84f848ef0a..ea81b8cb16 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -139,6 +139,11 @@ where
message: "Paze Decrypt token is not supported".to_string(),
})?
}
+ types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(errors::ApiErrorResponse::NotSupported {
+ message: "Google Pay Decrypt token is not supported".to_string(),
+ })?
+ }
};
Some((connector_name, token))
} else {
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 5baca7bb55..c11d54fc29 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -44,7 +44,8 @@ pub use hyperswitch_domain_models::{
router_data::{
AccessToken, AdditionalPaymentMethodConnectorResponse, ApplePayCryptogramData,
ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
- PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData,
+ GooglePayDecryptedData, GooglePayPaymentMethodDetails, PaymentMethodBalance,
+ PaymentMethodToken, RecurringMandatePaymentData, RouterData,
},
router_data_v2::{
AccessTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData,