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(router): Add support for confirm-intent external vault proxy flow (#8923)

Prasunna Soppa7f648379368b
diff --git a/Cargo.lock b/Cargo.lock
index 5ce7eff9c8..fdb8ceb970 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3540,7 +3540,7 @@ dependencies = [
[[package]]
name = "grpc-api-types"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=2263c96a70f2606475ab30e6f716b2773e1fd093#2263c96a70f2606475ab30e6f716b2773e1fd093"
+source = "git+https://github.com/juspay/connector-service?rev=aae51574fed25b0a7849e3832cff8904bc310cf5#aae51574fed25b0a7849e3832cff8904bc310cf5"
dependencies = [
"axum 0.8.4",
"error-stack 0.5.0",
@@ -6916,7 +6916,7 @@ dependencies = [
[[package]]
name = "rust-grpc-client"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=2263c96a70f2606475ab30e6f716b2773e1fd093#2263c96a70f2606475ab30e6f716b2773e1fd093"
+source = "git+https://github.com/juspay/connector-service?rev=aae51574fed25b0a7849e3832cff8904bc310cf5#aae51574fed25b0a7849e3832cff8904bc310cf5"
dependencies = [
"grpc-api-types",
]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index d757c6cfb6..91886de239 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2594,6 +2594,69 @@ pub struct PaymentMethodDataRequest {
pub billing: Option<Address>,
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)]
+pub struct ProxyPaymentMethodDataRequest {
+ /// This field is optional because, in case of saved cards we pass the payment_token
+ /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details
+ /// We have flattened it because to maintain backwards compatibility with the old API contract
+ #[serde(flatten)]
+ pub payment_method_data: Option<ProxyPaymentMethodData>,
+ /// billing details for the payment method.
+ /// This billing details will be passed to the processor as billing address.
+ /// If not passed, then payment.billing will be considered
+ pub billing: Option<Address>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum ProxyPaymentMethodData {
+ #[schema(title = "ProxyCardData")]
+ VaultDataCard(ProxyCardData),
+}
+
+#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct ProxyCardData {
+ /// The token which refers to the card number
+ #[schema(value_type = String, example = "token_card_number")]
+ pub card_number: Secret<String>,
+
+ /// The card's expiry month
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_month: Secret<String>,
+
+ /// The card's expiry year
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_year: Secret<String>,
+
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The CVC number for the card
+ #[schema(value_type = String, example = "242")]
+ pub card_cvc: Secret<String>,
+
+ /// The name of the issuer of card
+ #[schema(example = "chase")]
+ pub card_issuer: Option<String>,
+
+ /// The card network for the card
+ #[schema(value_type = Option<CardNetwork>, example = "Visa")]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ #[schema(example = "CREDIT")]
+ pub card_type: Option<String>,
+
+ #[schema(example = "INDIA")]
+ pub card_issuing_country: Option<String>,
+
+ #[schema(example = "JP_AMEX")]
+ pub bank_code: Option<String>,
+ /// The card holder's nick name
+ #[schema(value_type = Option<String>, example = "John Test")]
+ pub nick_name: Option<Secret<String>>,
+}
+
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodData {
@@ -5522,6 +5585,52 @@ pub struct ProxyPaymentsRequest {
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[cfg(feature = "v2")]
+pub struct ExternalVaultProxyPaymentsRequest {
+ /// The URL to which you want the user to be redirected after the completion of the payment operation
+ /// If this url is not passed, the url configured in the business profile will be used
+ #[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
+ pub return_url: Option<common_utils::types::Url>,
+
+ /// The payment instrument data to be used for the payment
+ pub payment_method_data: ProxyPaymentMethodDataRequest,
+
+ /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided
+ #[schema(value_type = PaymentMethod, example = "card")]
+ pub payment_method_type: api_enums::PaymentMethod,
+
+ /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided
+ #[schema(value_type = PaymentMethodType, example = "apple_pay")]
+ pub payment_method_subtype: api_enums::PaymentMethodType,
+
+ /// The shipping address for the payment. This will override the shipping address provided in the create-intent request
+ pub shipping: Option<Address>,
+
+ /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client.
+ #[schema(value_type = Option<CustomerAcceptance>)]
+ pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
+
+ /// Additional details required by 3DS 2.0
+ #[schema(value_type = Option<BrowserInformation>)]
+ pub browser_info: Option<common_utils::types::BrowserInformation>,
+
+ /// The payment_method_id to be associated with the payment
+ #[schema(value_type = Option<String>)]
+ pub payment_method_id: Option<id_type::GlobalPaymentMethodId>,
+
+ #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")]
+ pub payment_token: Option<String>,
+
+ /// Merchant connector details used to make payments.
+ #[schema(value_type = Option<MerchantConnectorAuthDetails>)]
+ pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
+
+ /// If true, returns stringified connector raw response body
+ pub return_raw_connector_response: Option<bool>,
+}
+
// This struct contains the union of fields in `PaymentsCreateIntentRequest` and
// `PaymentsConfirmIntentRequest`
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)]
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 062755496f..7aa5ccfb18 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -66,7 +66,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] }
http = "0.2.12"
url = { version = "2.5.4", features = ["serde"] }
quick-xml = { version = "0.31.0", features = ["serialize"] }
-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2263c96a70f2606475ab30e6f716b2773e1fd093", package = "rust-grpc-client" }
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "aae51574fed25b0a7849e3832cff8904bc310cf5", package = "rust-grpc-client" }
# First party crates
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
index 9a25bced2f..5aa68bdab1 100644
--- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
@@ -1,4 +1,4 @@
-use std::{collections::HashMap, ops::Deref};
+use std::{collections::HashMap, fmt::Debug, ops::Deref};
use api_models::{self, enums as api_enums, payments};
use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType};
@@ -2725,6 +2725,7 @@ where
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
+ //
item: ResponseRouterData<F, PaymentIntentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 27abb8bf5c..5126b4c653 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -42,7 +42,7 @@ use hyperswitch_domain_models::{
webhooks::VerifyWebhookSource,
AccessTokenAuthentication, Authenticate, AuthenticationConfirmation,
ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow,
- ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate,
+ ExternalVaultProxy, ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate,
},
router_request_types::{
authentication,
@@ -53,13 +53,13 @@ use hyperswitch_domain_models::{
},
AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,
- DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData,
- MandateRevokeRequestData, PaymentsApproveData, PaymentsCancelPostCaptureData,
- PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
- PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
- PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RetrieveFileRequestData,
- SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, UploadFileRequestData,
- VaultRequestData, VerifyWebhookSourceRequestData,
+ DefendDisputeRequestData, DisputeSyncData, ExternalVaultProxyPaymentsData,
+ FetchDisputesRequestData, MandateRevokeRequestData, PaymentsApproveData,
+ PaymentsCancelPostCaptureData, PaymentsIncrementalAuthorizationData,
+ PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
+ PaymentsRejectData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData,
+ RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData,
+ UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse,
@@ -117,10 +117,11 @@ use hyperswitch_interfaces::{
},
files::{FileUpload, RetrieveFile, UploadFile},
payments::{
- ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken,
- PaymentIncrementalAuthorization, PaymentPostCaptureVoid, PaymentPostSessionTokens,
- PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata, PaymentsCompleteAuthorize,
- PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing, TaxCalculation,
+ ConnectorCustomer, ExternalVaultProxyPaymentsCreateV1, PaymentApprove,
+ PaymentAuthorizeSessionToken, PaymentIncrementalAuthorization, PaymentPostCaptureVoid,
+ PaymentPostSessionTokens, PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata,
+ PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing,
+ PaymentsPreProcessing, TaxCalculation,
},
revenue_recovery::RevenueRecovery,
vault::{
@@ -6978,6 +6979,7 @@ default_imp_for_external_vault!(
connectors::Worldpayvantiv,
connectors::Worldpayxml,
connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
connectors::Vgs,
connectors::Volt,
connectors::Xendit,
@@ -7120,6 +7122,7 @@ default_imp_for_external_vault_insert!(
connectors::Worldpayvantiv,
connectors::Worldpayxml,
connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
connectors::Vgs,
connectors::Volt,
connectors::Xendit,
@@ -7262,6 +7265,7 @@ default_imp_for_external_vault_retrieve!(
connectors::Worldpayvantiv,
connectors::Worldpayxml,
connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
connectors::Vgs,
connectors::Volt,
connectors::Xendit,
@@ -7404,6 +7408,7 @@ default_imp_for_external_vault_delete!(
connectors::Worldpayvantiv,
connectors::Worldpayxml,
connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
connectors::Vgs,
connectors::Volt,
connectors::Xendit,
@@ -7545,6 +7550,7 @@ default_imp_for_external_vault_create!(
connectors::Worldpayvantiv,
connectors::Worldpayxml,
connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
connectors::Vgs,
connectors::Volt,
connectors::Xendit,
@@ -7693,6 +7699,149 @@ default_imp_for_connector_authentication_token!(
connectors::Zsl
);
+macro_rules! default_imp_for_external_vault_proxy_payments_create {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl ExternalVaultProxyPaymentsCreateV1 for $path::$connector {}
+ impl
+ ConnectorIntegration<
+ ExternalVaultProxy,
+ ExternalVaultProxyPaymentsData,
+ PaymentsResponseData,
+ > for $path::$connector
+ {}
+ )*
+ };
+}
+
+default_imp_for_external_vault_proxy_payments_create!(
+ connectors::Aci,
+ connectors::Adyen,
+ connectors::Adyenplatform,
+ connectors::Affirm,
+ connectors::Airwallex,
+ connectors::Amazonpay,
+ connectors::Archipel,
+ connectors::Authipay,
+ connectors::Authorizedotnet,
+ connectors::Bambora,
+ connectors::Bamboraapac,
+ connectors::Bankofamerica,
+ connectors::Barclaycard,
+ connectors::Billwerk,
+ connectors::Bitpay,
+ connectors::Blackhawknetwork,
+ connectors::Bluecode,
+ connectors::Bluesnap,
+ connectors::Braintree,
+ connectors::Breadpay,
+ connectors::Boku,
+ connectors::Cashtocode,
+ connectors::Celero,
+ connectors::Chargebee,
+ connectors::Checkbook,
+ connectors::Checkout,
+ connectors::Coinbase,
+ connectors::Coingate,
+ connectors::Cryptopay,
+ connectors::Custombilling,
+ connectors::Cybersource,
+ connectors::Datatrans,
+ connectors::Deutschebank,
+ connectors::Digitalvirgo,
+ connectors::Dlocal,
+ connectors::Dwolla,
+ connectors::Ebanx,
+ connectors::Elavon,
+ connectors::Facilitapay,
+ connectors::Fiserv,
+ connectors::Fiservemea,
+ connectors::Fiuu,
+ connectors::Flexiti,
+ connectors::Forte,
+ connectors::Getnet,
+ connectors::Globalpay,
+ connectors::Globepay,
+ connectors::Gocardless,
+ connectors::Gpayments,
+ connectors::Hipay,
+ connectors::Helcim,
+ connectors::HyperswitchVault,
+ connectors::Hyperwallet,
+ connectors::Iatapay,
+ connectors::Inespay,
+ connectors::Itaubank,
+ connectors::Jpmorgan,
+ connectors::Juspaythreedsserver,
+ connectors::Katapult,
+ connectors::Klarna,
+ connectors::Mifinity,
+ connectors::Mollie,
+ connectors::Moneris,
+ connectors::Mpgs,
+ connectors::Multisafepay,
+ connectors::Netcetera,
+ connectors::Nmi,
+ connectors::Nomupay,
+ connectors::Noon,
+ connectors::Nordea,
+ connectors::Novalnet,
+ connectors::Nexinets,
+ connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
+ connectors::Nuvei,
+ connectors::Paybox,
+ connectors::Payeezy,
+ connectors::Payload,
+ connectors::Payme,
+ connectors::Payone,
+ connectors::Paypal,
+ connectors::Paystack,
+ connectors::Paytm,
+ connectors::Payu,
+ connectors::Phonepe,
+ connectors::Placetopay,
+ connectors::Plaid,
+ connectors::Powertranz,
+ connectors::Prophetpay,
+ connectors::Rapyd,
+ connectors::Razorpay,
+ connectors::Recurly,
+ connectors::Redsys,
+ connectors::Riskified,
+ connectors::Santander,
+ connectors::Shift4,
+ connectors::Sift,
+ connectors::Silverflow,
+ connectors::Signifyd,
+ connectors::Stax,
+ connectors::Square,
+ connectors::Stripe,
+ connectors::Stripebilling,
+ connectors::Taxjar,
+ connectors::Threedsecureio,
+ connectors::Thunes,
+ connectors::Tokenio,
+ connectors::Trustpay,
+ connectors::Trustpayments,
+ connectors::Tsys,
+ connectors::UnifiedAuthenticationService,
+ connectors::Wise,
+ connectors::Worldline,
+ connectors::Worldpay,
+ connectors::Worldpayvantiv,
+ connectors::Worldpayxml,
+ connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
+ connectors::Vgs,
+ connectors::Volt,
+ connectors::Xendit,
+ connectors::Zen,
+ connectors::Zsl,
+ connectors::CtpMastercard
+);
+
#[cfg(feature = "dummy_connector")]
impl<const T: u8> PaymentsCompleteAuthorize for connectors::DummyConnector<T> {}
#[cfg(feature = "dummy_connector")]
@@ -8232,3 +8381,12 @@ impl<const T: u8>
> for connectors::DummyConnector<T>
{
}
+
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8> ExternalVaultProxyPaymentsCreateV1 for connectors::DummyConnector<T> {}
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8>
+ ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>
+ for connectors::DummyConnector<T>
+{
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index ba6f4e9d27..2d346a0e7c 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -18,9 +18,9 @@ use hyperswitch_domain_models::{
mandate_revoke::MandateRevoke,
payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
- CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PSync,
- PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing,
- Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
+ CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization,
+ PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens,
+ PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
},
refunds::{Execute, RSync},
revenue_recovery::{
@@ -39,11 +39,12 @@ use hyperswitch_domain_models::{
AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData,
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData,
- FetchDisputesRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
- PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
- PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
- PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
+ ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData,
+ PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
+ PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
+ PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
+ PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData,
UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData,
@@ -102,9 +103,9 @@ use hyperswitch_interfaces::{
},
files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2},
payments_v2::{
- ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
- PaymentAuthorizeV2, PaymentCaptureV2, PaymentCreateOrderV2,
- PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2,
+ ConnectorCustomerV2, ExternalVaultProxyPaymentsCreate, MandateSetupV2,
+ PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2,
+ PaymentCreateOrderV2, PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2,
PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2,
PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2,
PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2,
@@ -4386,3 +4387,146 @@ default_imp_for_new_connector_integration_external_vault!(
connectors::Zen,
connectors::Zsl
);
+
+macro_rules! default_imp_for_new_connector_integration_external_vault_proxy {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl ExternalVaultProxyPaymentsCreate for $path::$connector {}
+ impl
+ ConnectorIntegrationV2<
+ ExternalVaultProxy,
+ PaymentFlowData,
+ ExternalVaultProxyPaymentsData,
+ PaymentsResponseData> for $path::$connector
+ {}
+ )*
+ };
+}
+
+default_imp_for_new_connector_integration_external_vault_proxy!(
+ connectors::Aci,
+ connectors::Adyen,
+ connectors::Adyenplatform,
+ connectors::Affirm,
+ connectors::Airwallex,
+ connectors::Amazonpay,
+ connectors::Archipel,
+ connectors::Authipay,
+ connectors::Authorizedotnet,
+ connectors::Bambora,
+ connectors::Bamboraapac,
+ connectors::Bankofamerica,
+ connectors::Barclaycard,
+ connectors::Billwerk,
+ connectors::Bitpay,
+ connectors::Blackhawknetwork,
+ connectors::Bluecode,
+ connectors::Bluesnap,
+ connectors::Braintree,
+ connectors::Breadpay,
+ connectors::Boku,
+ connectors::Cashtocode,
+ connectors::Celero,
+ connectors::Chargebee,
+ connectors::Checkbook,
+ connectors::Checkout,
+ connectors::Coinbase,
+ connectors::Coingate,
+ connectors::Cryptopay,
+ connectors::Custombilling,
+ connectors::Cybersource,
+ connectors::Datatrans,
+ connectors::Deutschebank,
+ connectors::Digitalvirgo,
+ connectors::Dlocal,
+ connectors::Dwolla,
+ connectors::Ebanx,
+ connectors::Elavon,
+ connectors::Facilitapay,
+ connectors::Fiserv,
+ connectors::Fiservemea,
+ connectors::Fiuu,
+ connectors::Flexiti,
+ connectors::Forte,
+ connectors::Getnet,
+ connectors::Globalpay,
+ connectors::Globepay,
+ connectors::Gocardless,
+ connectors::Gpayments,
+ connectors::Hipay,
+ connectors::Helcim,
+ connectors::HyperswitchVault,
+ connectors::Hyperwallet,
+ connectors::Iatapay,
+ connectors::Inespay,
+ connectors::Itaubank,
+ connectors::Jpmorgan,
+ connectors::Juspaythreedsserver,
+ connectors::Katapult,
+ connectors::Klarna,
+ connectors::Mifinity,
+ connectors::Mollie,
+ connectors::Moneris,
+ connectors::Mpgs,
+ connectors::Multisafepay,
+ connectors::Netcetera,
+ connectors::Nmi,
+ connectors::Nomupay,
+ connectors::Noon,
+ connectors::Nordea,
+ connectors::Novalnet,
+ connectors::Nexinets,
+ connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
+ connectors::Nuvei,
+ connectors::Paybox,
+ connectors::Payeezy,
+ connectors::Payload,
+ connectors::Payme,
+ connectors::Payone,
+ connectors::Paypal,
+ connectors::Paystack,
+ connectors::Paytm,
+ connectors::Payu,
+ connectors::Phonepe,
+ connectors::Placetopay,
+ connectors::Plaid,
+ connectors::Powertranz,
+ connectors::Prophetpay,
+ connectors::Rapyd,
+ connectors::Razorpay,
+ connectors::Recurly,
+ connectors::Redsys,
+ connectors::Riskified,
+ connectors::Santander,
+ connectors::Shift4,
+ connectors::Sift,
+ connectors::Silverflow,
+ connectors::Signifyd,
+ connectors::Stax,
+ connectors::Square,
+ connectors::Stripe,
+ connectors::Stripebilling,
+ connectors::Taxjar,
+ connectors::Threedsecureio,
+ connectors::Thunes,
+ connectors::Tokenio,
+ connectors::Trustpay,
+ connectors::Trustpayments,
+ connectors::Tsys,
+ connectors::UnifiedAuthenticationService,
+ connectors::Wise,
+ connectors::Worldline,
+ connectors::Worldpay,
+ connectors::Worldpayvantiv,
+ connectors::Worldpayxml,
+ connectors::Wellsfargo,
+ connectors::Wellsfargopayout,
+ connectors::Vgs,
+ connectors::Volt,
+ connectors::Xendit,
+ connectors::Zen,
+ connectors::Zsl,
+ connectors::CtpMastercard
+);
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index af00270bb6..300f88c720 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -55,11 +55,11 @@ use hyperswitch_domain_models::{
},
router_request_types::{
AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject,
- CompleteAuthorizeData, ConnectorCustomerData, MandateRevokeRequestData,
- PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCaptureData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
- PaymentsSyncData, RefundIntegrityObject, RefundsData, ResponseId, SetupMandateRequestData,
- SyncIntegrityObject,
+ CompleteAuthorizeData, ConnectorCustomerData, ExternalVaultProxyPaymentsData,
+ MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData,
+ PaymentsPreProcessingData, PaymentsSyncData, RefundIntegrityObject, RefundsData,
+ ResponseId, SetupMandateRequestData, SyncIntegrityObject,
},
router_response_types::{CaptureSyncResponse, PaymentsResponseData},
types::{OrderDetailsWithAmount, SetupMandateRouterData},
@@ -6621,6 +6621,11 @@ impl SplitPaymentData for SetupMandateRequestData {
None
}
}
+impl SplitPaymentData for ExternalVaultProxyPaymentsData {
+ fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
+ None
+ }
+}
pub struct XmlSerializer;
impl XmlSerializer {
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 18c8b59ad7..de07d67f47 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -46,6 +46,11 @@ pub enum PaymentMethodData {
MobilePayment(MobilePaymentData),
}
+#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
+pub enum ExternalVaultPaymentMethodData {
+ Card(ExternalVaultCard),
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplePayFlow {
Simplified(api_models::payments::PaymentProcessingDetails),
@@ -133,6 +138,22 @@ pub struct Card {
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
+#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
+pub struct ExternalVaultCard {
+ pub card_number: Secret<String>,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub card_cvc: Secret<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<String>,
+ pub card_issuing_country: Option<String>,
+ pub bank_code: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+ pub card_holder_name: Option<Secret<String>>,
+ pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetailsForNetworkTransactionId {
pub card_number: cards::CardNumber,
@@ -886,6 +907,47 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
}
}
+impl From<api_models::payments::ProxyPaymentMethodData> for ExternalVaultPaymentMethodData {
+ fn from(api_model_payment_method_data: api_models::payments::ProxyPaymentMethodData) -> Self {
+ match api_model_payment_method_data {
+ api_models::payments::ProxyPaymentMethodData::VaultDataCard(card_data) => {
+ Self::Card(ExternalVaultCard::from(card_data))
+ }
+ }
+ }
+}
+impl From<api_models::payments::ProxyCardData> for ExternalVaultCard {
+ fn from(value: api_models::payments::ProxyCardData) -> Self {
+ let api_models::payments::ProxyCardData {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_holder_name,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ } = value;
+
+ Self {
+ card_number,
+ card_exp_month,
+ card_exp_year,
+ card_cvc,
+ card_issuer,
+ card_network,
+ card_type,
+ card_issuing_country,
+ bank_code,
+ nick_name,
+ card_holder_name,
+ co_badged_card_data: None,
+ }
+ }
+}
impl
From<(
api_models::payments::Card,
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 46e70079bc..36eece964f 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -880,6 +880,7 @@ where
pub mandate_data: Option<api_models::payments::MandateIds>,
pub payment_method: Option<payment_methods::PaymentMethod>,
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
+ pub external_vault_pmd: Option<payment_method_data::ExternalVaultPaymentMethodData>,
}
#[cfg(feature = "v2")]
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index a9d4456606..a1ff44f533 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -714,6 +714,101 @@ impl PaymentAttempt {
})
}
+ #[cfg(feature = "v2")]
+ pub async fn external_vault_proxy_create_domain_model(
+ payment_intent: &super::PaymentIntent,
+ cell_id: id_type::CellId,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ request: &api_models::payments::ExternalVaultProxyPaymentsRequest,
+ encrypted_data: DecryptedPaymentAttempt,
+ ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
+ let id = id_type::GlobalAttemptId::generate(&cell_id);
+ let intent_amount_details = payment_intent.amount_details.clone();
+ let attempt_amount_details = AttemptAmountDetails {
+ net_amount: intent_amount_details.order_amount,
+ amount_to_capture: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ amount_capturable: intent_amount_details.order_amount,
+ shipping_cost: None,
+ order_tax_amount: None,
+ };
+
+ let now = common_utils::date_time::now();
+ let payment_method_billing_address = encrypted_data
+ .payment_method_billing_address
+ .as_ref()
+ .map(|data| {
+ data.clone()
+ .deserialize_inner_value(|value| value.parse_value("Address"))
+ })
+ .transpose()
+ .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to decode billing address")?;
+ let connector_token = Some(diesel_models::ConnectorTokenDetails {
+ connector_mandate_id: None,
+ connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
+ consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
+ )),
+ });
+ let payment_method_type_data = payment_intent.get_payment_method_type();
+
+ let payment_method_subtype_data = payment_intent.get_payment_method_sub_type();
+ let authentication_type = payment_intent.authentication_type.unwrap_or_default();
+ Ok(Self {
+ payment_id: payment_intent.id.clone(),
+ merchant_id: payment_intent.merchant_id.clone(),
+ amount_details: attempt_amount_details,
+ status: common_enums::AttemptStatus::Started,
+ connector: None,
+ authentication_type,
+ created_at: now,
+ modified_at: now,
+ last_synced: None,
+ cancellation_reason: None,
+ browser_info: request.browser_info.clone(),
+ payment_token: None,
+ connector_metadata: None,
+ payment_experience: None,
+ payment_method_data: None,
+ routing_result: None,
+ preprocessing_step_id: None,
+ multiple_capture_count: None,
+ connector_response_reference_id: None,
+ updated_by: storage_scheme.to_string(),
+ redirection_data: None,
+ encoded_data: None,
+ merchant_connector_id: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ charges: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: request.customer_acceptance.clone().map(Secret::new),
+ profile_id: payment_intent.profile_id.clone(),
+ organization_id: payment_intent.organization_id.clone(),
+ payment_method_type: payment_method_type_data
+ .unwrap_or(common_enums::PaymentMethod::Card),
+ payment_method_id: request.payment_method_id.clone(),
+ connector_payment_id: None,
+ payment_method_subtype: payment_method_subtype_data
+ .unwrap_or(common_enums::PaymentMethodType::Credit),
+ authentication_applied: None,
+ external_reference_id: None,
+ payment_method_billing_address,
+ error: None,
+ connector_token_details: connector_token,
+ feature_metadata: None,
+ id,
+ card_discovery: None,
+ processor_merchant_id: payment_intent.merchant_id.clone(),
+ created_by: None,
+ connector_request_reference_id: None,
+ })
+ }
+
/// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
#[cfg(feature = "v2")]
pub async fn create_domain_model_using_record_request(
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index d3b6883571..f572ebc0a9 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -1317,6 +1317,241 @@ impl
}
}
+#[cfg(feature = "v2")]
+impl
+ TrackerPostUpdateObjects<
+ router_flow_types::ExternalVaultProxy,
+ router_request_types::ExternalVaultProxyPaymentsData,
+ payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ >
+ for RouterData<
+ router_flow_types::ExternalVaultProxy,
+ router_request_types::ExternalVaultProxyPaymentsData,
+ router_response_types::PaymentsResponseData,
+ >
+{
+ fn get_payment_intent_update(
+ &self,
+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ storage_scheme: common_enums::MerchantStorageScheme,
+ ) -> PaymentIntentUpdate {
+ let amount_captured = self.get_captured_amount(payment_data);
+ match self.response {
+ Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
+ status: common_enums::IntentStatus::from(
+ self.get_attempt_status_for_db_update(payment_data),
+ ),
+ amount_captured,
+ updated_by: storage_scheme.to_string(),
+ feature_metadata: None,
+ },
+ Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
+ status: {
+ let attempt_status = match error.attempt_status {
+ // Use the status sent by connector in error_response if it's present
+ Some(status) => status,
+ None => match error.status_code {
+ 500..=511 => common_enums::enums::AttemptStatus::Pending,
+ _ => common_enums::enums::AttemptStatus::Failure,
+ },
+ };
+ common_enums::IntentStatus::from(attempt_status)
+ },
+ amount_captured,
+ updated_by: storage_scheme.to_string(),
+ feature_metadata: None,
+ },
+ }
+ }
+
+ fn get_payment_attempt_update(
+ &self,
+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ storage_scheme: common_enums::MerchantStorageScheme,
+ ) -> PaymentAttemptUpdate {
+ let amount_capturable = self.get_amount_capturable(payment_data);
+
+ match self.response {
+ Ok(ref response_router_data) => match response_router_data {
+ router_response_types::PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data,
+ connector_metadata,
+ connector_response_reference_id,
+ ..
+ } => {
+ let attempt_status = self.get_attempt_status_for_db_update(payment_data);
+
+ let connector_payment_id = match resource_id {
+ router_request_types::ResponseId::NoResponseId => None,
+ router_request_types::ResponseId::ConnectorTransactionId(id)
+ | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),
+ };
+
+ PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(
+ payments::payment_attempt::ConfirmIntentResponseUpdate {
+ status: attempt_status,
+ connector_payment_id,
+ updated_by: storage_scheme.to_string(),
+ redirection_data: *redirection_data.clone(),
+ amount_capturable,
+ connector_metadata: connector_metadata.clone().map(Secret::new),
+ connector_token_details: response_router_data
+ .get_updated_connector_token_details(
+ payment_data
+ .payment_attempt
+ .connector_token_details
+ .as_ref()
+ .and_then(|token_details| {
+ token_details.get_connector_token_request_reference_id()
+ }),
+ ),
+ connector_response_reference_id: connector_response_reference_id
+ .clone(),
+ },
+ ))
+ }
+ router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {
+ todo!()
+ }
+ router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),
+ router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),
+ router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {
+ ..
+ } => todo!(),
+ router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),
+ router_response_types::PaymentsResponseData::ConnectorCustomerResponse {
+ ..
+ } => todo!(),
+ router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {
+ ..
+ } => todo!(),
+ router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {
+ todo!()
+ }
+ router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {
+ ..
+ } => todo!(),
+ router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {
+ todo!()
+ }
+ router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {
+ ..
+ } => {
+ todo!()
+ }
+ router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {
+ ..
+ } => todo!(),
+ },
+ Err(ref error_response) => {
+ let ErrorResponse {
+ code,
+ message,
+ reason,
+ status_code: _,
+ attempt_status: _,
+ connector_transaction_id,
+ network_decline_code,
+ network_advice_code,
+ network_error_message,
+ } = error_response.clone();
+
+ let attempt_status = match error_response.attempt_status {
+ // Use the status sent by connector in error_response if it's present
+ Some(status) => status,
+ None => match error_response.status_code {
+ 500..=511 => common_enums::enums::AttemptStatus::Pending,
+ _ => common_enums::enums::AttemptStatus::Failure,
+ },
+ };
+ let error_details = ErrorDetails {
+ code,
+ message,
+ reason,
+ unified_code: None,
+ unified_message: None,
+ network_advice_code,
+ network_decline_code,
+ network_error_message,
+ };
+
+ PaymentAttemptUpdate::ErrorUpdate {
+ status: attempt_status,
+ error: error_details,
+ amount_capturable,
+ connector_payment_id: connector_transaction_id,
+ updated_by: storage_scheme.to_string(),
+ }
+ }
+ }
+ }
+
+ fn get_attempt_status_for_db_update(
+ &self,
+ _payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ ) -> common_enums::AttemptStatus {
+ // For this step, consider whatever status was given by the connector module
+ // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount
+ self.status
+ }
+
+ fn get_amount_capturable(
+ &self,
+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ ) -> Option<MinorUnit> {
+ // Based on the status of the response, we can determine the amount capturable
+ let intent_status = common_enums::IntentStatus::from(self.status);
+ match intent_status {
+ common_enums::IntentStatus::Succeeded
+ | common_enums::IntentStatus::Failed
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::CancelledPostCapture
+ | common_enums::IntentStatus::Conflicted
+ | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
+ common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::Processing => None,
+ common_enums::IntentStatus::RequiresPaymentMethod
+ | common_enums::IntentStatus::RequiresConfirmation => None,
+ common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
+ let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
+ Some(total_amount)
+ }
+ common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
+ }
+ }
+
+ fn get_captured_amount(
+ &self,
+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
+ ) -> Option<MinorUnit> {
+ // Based on the status of the response, we can determine the amount that was captured
+ let intent_status = common_enums::IntentStatus::from(self.status);
+ match intent_status {
+ common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {
+ let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
+ Some(total_amount)
+ }
+ common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::Failed
+ | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
+ | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
+ common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::Processing => None,
+ common_enums::IntentStatus::RequiresPaymentMethod
+ | common_enums::IntentStatus::RequiresConfirmation => None,
+ common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()),
+ common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
+ }
+ }
+}
+
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
diff --git a/crates/hyperswitch_domain_models/src/router_data_v2.rs b/crates/hyperswitch_domain_models/src/router_data_v2.rs
index 60b6070da0..a843fa8867 100644
--- a/crates/hyperswitch_domain_models/src/router_data_v2.rs
+++ b/crates/hyperswitch_domain_models/src/router_data_v2.rs
@@ -9,8 +9,9 @@ pub use flow_common_types::FrmFlowData;
pub use flow_common_types::PayoutFlowData;
pub use flow_common_types::{
AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData,
- ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData,
- RefundFlowData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData,
+ ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData,
+ MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData,
+ WebhookSourceVerifyData,
};
use crate::router_data::{ConnectorAuthType, ErrorResponse};
diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
index 3fe6e85bda..686912c6dc 100644
--- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
@@ -166,3 +166,44 @@ pub struct BillingConnectorInvoiceSyncFlowData;
pub struct VaultConnectorFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
}
+
+#[derive(Debug, Clone)]
+pub struct ExternalVaultProxyFlowData {
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub connector_customer: Option<String>,
+ pub payment_id: String,
+ pub attempt_id: String,
+ pub status: common_enums::AttemptStatus,
+ pub payment_method: common_enums::PaymentMethod,
+ pub description: Option<String>,
+ pub address: PaymentAddress,
+ pub auth_type: common_enums::AuthenticationType,
+ pub connector_meta_data: Option<pii::SecretSerdeValue>,
+ pub amount_captured: Option<i64>,
+ // minor amount for amount framework
+ pub minor_amount_captured: Option<MinorUnit>,
+ pub access_token: Option<AccessToken>,
+ pub session_token: Option<String>,
+ pub reference_id: Option<String>,
+ pub payment_method_token: Option<PaymentMethodToken>,
+ pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>,
+ pub preprocessing_id: Option<String>,
+ /// This is the balance amount for gift cards or voucher
+ pub payment_method_balance: Option<PaymentMethodBalance>,
+
+ ///for switching between two different versions of the same connector
+ pub connector_api_version: Option<String>,
+ /// Contains a reference ID that should be sent in the connector request
+ pub connector_request_reference_id: String,
+
+ pub test_mode: Option<bool>,
+ pub connector_http_status_code: Option<u16>,
+ pub external_latency: Option<u128>,
+ /// Contains apple pay flow type simplified or manual
+ pub apple_pay_flow: Option<ApplePayFlow>,
+
+ /// This field is used to store various data regarding the response from connector
+ pub connector_response: Option<ConnectorResponseData>,
+ pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
+}
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
index 1129f52997..eece6330e3 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
@@ -82,3 +82,6 @@ pub struct CreateOrder;
#[derive(Debug, Clone)]
pub struct PaymentGetListAttempts;
+
+#[derive(Debug, Clone)]
+pub struct ExternalVaultProxy;
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 04c5b7194e..5730c23d6c 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -14,8 +14,10 @@ use serde_with::serde_as;
use super::payment_method_data::PaymentMethodData;
use crate::{
address,
- errors::api_error_response::ApiErrorResponse,
- mandates, payments,
+ errors::api_error_response::{ApiErrorResponse, NotImplementedMessage},
+ mandates,
+ payment_method_data::ExternalVaultPaymentMethodData,
+ payments,
router_data::{self, AccessTokenAuthenticationResponse, RouterData},
router_flow_types as flows, router_response_types as response_types,
vault::PaymentMethodVaultingData,
@@ -84,6 +86,104 @@ pub struct PaymentsAuthorizeData {
pub payment_channel: Option<common_enums::PaymentChannel>,
pub enable_partial_authorization: Option<bool>,
}
+
+#[derive(Debug, Clone)]
+pub struct ExternalVaultProxyPaymentsData {
+ pub payment_method_data: ExternalVaultPaymentMethodData,
+ /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
+ /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
+ /// ```text
+ /// get_original_amount()
+ /// get_surcharge_amount()
+ /// get_tax_on_surcharge_amount()
+ /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
+ /// ```
+ pub amount: i64,
+ pub order_tax_amount: Option<MinorUnit>,
+ pub email: Option<pii::Email>,
+ pub customer_name: Option<Secret<String>>,
+ pub currency: storage_enums::Currency,
+ pub confirm: bool,
+ pub statement_descriptor_suffix: Option<String>,
+ pub statement_descriptor: Option<String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ // Mandates
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub mandate_id: Option<api_models::payments::MandateIds>,
+ pub off_session: Option<bool>,
+ pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
+ pub setup_mandate_details: Option<mandates::MandateData>,
+ pub browser_info: Option<BrowserInformation>,
+ pub order_details: Option<Vec<OrderDetailsWithAmount>>,
+ pub order_category: Option<String>,
+ pub session_token: Option<String>,
+ pub enrolled_for_3ds: bool,
+ pub related_transaction_id: Option<String>,
+ pub payment_experience: Option<storage_enums::PaymentExperience>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub surcharge_details: Option<SurchargeDetails>,
+ pub customer_id: Option<id_type::CustomerId>,
+ pub request_incremental_authorization: bool,
+ pub metadata: Option<serde_json::Value>,
+ pub authentication_data: Option<AuthenticationData>,
+ pub request_extended_authorization:
+ Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
+
+ // New amount for amount frame work
+ pub minor_amount: MinorUnit,
+ /// Merchant's identifier for the payment/invoice. This will be sent to the connector
+ /// if the connector provides support to accept multiple reference ids.
+ /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
+ pub merchant_order_reference_id: Option<String>,
+ pub integrity_object: Option<AuthoriseIntegrityObject>,
+ pub shipping_cost: Option<MinorUnit>,
+ pub additional_payment_method_data: Option<AdditionalPaymentData>,
+ pub merchant_account_id: Option<Secret<String>>,
+ pub merchant_config_currency: Option<storage_enums::Currency>,
+ pub connector_testing_data: Option<pii::SecretSerdeValue>,
+ pub order_id: Option<String>,
+}
+
+// Note: Integrity traits for ExternalVaultProxyPaymentsData are not implemented
+// as they are not mandatory for this flow. The integrity_check field in RouterData
+// will use Ok(()) as default, similar to other flows.
+
+// Implement ConnectorCustomerData conversion for ExternalVaultProxy RouterData
+impl
+ TryFrom<
+ &RouterData<
+ flows::ExternalVaultProxy,
+ ExternalVaultProxyPaymentsData,
+ response_types::PaymentsResponseData,
+ >,
+ > for ConnectorCustomerData
+{
+ type Error = error_stack::Report<ApiErrorResponse>;
+
+ fn try_from(
+ data: &RouterData<
+ flows::ExternalVaultProxy,
+ ExternalVaultProxyPaymentsData,
+ response_types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ email: data.request.email.clone(),
+ payment_method_data: None, // External vault proxy doesn't use regular payment method data
+ description: None,
+ phone: None,
+ name: data.request.customer_name.clone(),
+ preprocessing_id: data.preprocessing_id.clone(),
+ split_payments: data.request.split_payments.clone(),
+ setup_future_usage: data.request.setup_future_usage,
+ customer_acceptance: data.request.customer_acceptance.clone(),
+ })
+ }
+}
#[derive(Debug, Clone)]
pub struct PaymentsPostSessionTokensData {
// amount here would include amount, surcharge_amount and shipping_cost
@@ -350,6 +450,21 @@ impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData {
}
}
+impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+
+ fn try_from(_data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
+ // TODO: External vault proxy payments should not use regular payment method tokenization
+ // This needs to be implemented separately for external vault flows
+ Err(ApiErrorResponse::NotImplemented {
+ message: NotImplementedMessage::Reason(
+ "External vault proxy tokenization not implemented".to_string(),
+ ),
+ }
+ .into())
+ }
+}
+
#[derive(Debug, Clone)]
pub struct CreateOrderRequestData {
pub minor_amount: MinorUnit,
@@ -367,6 +482,17 @@ impl TryFrom<PaymentsAuthorizeData> for CreateOrderRequestData {
}
}
+impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData {
+ type Error = error_stack::Report<ApiErrorResponse>;
+
+ fn try_from(data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ minor_amount: data.minor_amount,
+ currency: data.currency,
+ })
+ }
+}
+
#[derive(Debug, Clone)]
pub struct PaymentsPreProcessingData {
pub payment_method_data: Option<PaymentMethodData>,
diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs
index 6036bdcca5..bcca0ba12a 100644
--- a/crates/hyperswitch_domain_models/src/types.rs
+++ b/crates/hyperswitch_domain_models/src/types.rs
@@ -8,9 +8,9 @@ use crate::{
AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize,
AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync,
CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute,
- IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid,
- PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session,
- SetupMandate, UpdateMetadata, VerifyWebhookSource, Void,
+ ExternalVaultProxy, IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate,
+ PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing, RSync,
+ SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void,
},
router_request_types::{
revenue_recovery::{
@@ -24,9 +24,9 @@ use crate::{
},
AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,
- MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
- PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
+ ExternalVaultProxyPaymentsData, MandateRevokeRequestData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,
+ PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData,
@@ -46,6 +46,8 @@ pub use crate::{router_request_types::PayoutsData, router_response_types::Payout
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
+pub type ExternalVaultProxyPaymentsRouterData =
+ RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
@@ -162,3 +164,10 @@ pub type VaultRouterDataV2<F> = RouterDataV2<
VaultRequestData,
VaultResponseData,
>;
+
+pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2<
+ ExternalVaultProxy,
+ router_data_v2::flow_common_types::ExternalVaultProxyFlowData,
+ ExternalVaultProxyPaymentsData,
+ PaymentsResponseData,
+>;
diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs
index b923d85a9b..b901f28a19 100644
--- a/crates/hyperswitch_interfaces/src/api/payments.rs
+++ b/crates/hyperswitch_interfaces/src/api/payments.rs
@@ -8,15 +8,15 @@ use hyperswitch_domain_models::{
PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject,
SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
},
- CreateOrder,
+ CreateOrder, ExternalVaultProxy,
},
router_request_types::{
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
- CreateOrderRequestData, PaymentMethodTokenizationData, PaymentsApproveData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,
- PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
- PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
- PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
+ CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData,
+ PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData,
+ PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
+ PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
+ PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, TaxCalculationResponseData},
@@ -49,6 +49,7 @@ pub trait Payment:
+ PaymentPostSessionTokens
+ PaymentUpdateMetadata
+ PaymentsCreateOrder
+ + ExternalVaultProxyPaymentsCreateV1
{
}
@@ -181,3 +182,9 @@ pub trait PaymentsCreateOrder:
api::ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>
{
}
+
+/// trait ExternalVaultProxyPaymentsCreate
+pub trait ExternalVaultProxyPaymentsCreateV1:
+ api::ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>
+{
+}
diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs
index 63a876c212..ea4b6428c3 100644
--- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs
+++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs
@@ -4,17 +4,17 @@ use hyperswitch_domain_models::{
router_data_v2::PaymentFlowData,
router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
- CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PSync, PaymentMethodToken,
- PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject,
- SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
+ CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization, PSync,
+ PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing,
+ Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
},
router_request_types::{
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
- CreateOrderRequestData, PaymentMethodTokenizationData, PaymentsApproveData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,
- PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
- PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
- PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
+ CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData,
+ PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData,
+ PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
+ PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
+ PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, TaxCalculationResponseData},
@@ -210,6 +210,17 @@ pub trait PaymentsPostProcessingV2:
{
}
+/// trait ExternalVaultProxyPaymentsCreate
+pub trait ExternalVaultProxyPaymentsCreate:
+ ConnectorIntegrationV2<
+ ExternalVaultProxy,
+ PaymentFlowData,
+ ExternalVaultProxyPaymentsData,
+ PaymentsResponseData,
+>
+{
+}
+
/// trait PaymentV2
pub trait PaymentV2:
ConnectorCommon
@@ -236,5 +247,6 @@ pub trait PaymentV2:
+ PaymentPostSessionTokensV2
+ PaymentUpdateMetadataV2
+ PaymentCreateOrderV2
+ + ExternalVaultProxyPaymentsCreate
{
}
diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs
index d70b8e882a..23fb9e76bc 100644
--- a/crates/hyperswitch_interfaces/src/conversion_impls.rs
+++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs
@@ -11,8 +11,8 @@ use hyperswitch_domain_models::{
flow_common_types::{
AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData,
BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData,
- FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData,
- RevenueRecoveryRecordBackData, UasFlowData, VaultConnectorFlowData,
+ ExternalVaultProxyFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData,
+ RefundFlowData, RevenueRecoveryRecordBackData, UasFlowData, VaultConnectorFlowData,
WebhookSourceVerifyData,
},
RouterDataV2,
@@ -963,3 +963,124 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for VaultCon
})
}
}
+
+impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for ExternalVaultProxyFlowData {
+ fn from_old_router_data(
+ old_router_data: &RouterData<T, Req, Resp>,
+ ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
+ where
+ Self: Sized,
+ {
+ let resource_common_data = Self {
+ merchant_id: old_router_data.merchant_id.clone(),
+ customer_id: old_router_data.customer_id.clone(),
+ connector_customer: old_router_data.connector_customer.clone(),
+ payment_id: old_router_data.payment_id.clone(),
+ attempt_id: old_router_data.attempt_id.clone(),
+ status: old_router_data.status,
+ payment_method: old_router_data.payment_method,
+ description: old_router_data.description.clone(),
+ address: old_router_data.address.clone(),
+ auth_type: old_router_data.auth_type,
+ connector_meta_data: old_router_data.connector_meta_data.clone(),
+ amount_captured: old_router_data.amount_captured,
+ minor_amount_captured: old_router_data.minor_amount_captured,
+ access_token: old_router_data.access_token.clone(),
+ session_token: old_router_data.session_token.clone(),
+ reference_id: old_router_data.reference_id.clone(),
+ payment_method_token: old_router_data.payment_method_token.clone(),
+ recurring_mandate_payment_data: old_router_data.recurring_mandate_payment_data.clone(),
+ preprocessing_id: old_router_data.preprocessing_id.clone(),
+ payment_method_balance: old_router_data.payment_method_balance.clone(),
+ connector_api_version: old_router_data.connector_api_version.clone(),
+ connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
+ test_mode: old_router_data.test_mode,
+ connector_http_status_code: old_router_data.connector_http_status_code,
+ external_latency: old_router_data.external_latency,
+ apple_pay_flow: old_router_data.apple_pay_flow.clone(),
+ connector_response: old_router_data.connector_response.clone(),
+ payment_method_status: old_router_data.payment_method_status,
+ };
+ Ok(RouterDataV2 {
+ flow: std::marker::PhantomData,
+ tenant_id: old_router_data.tenant_id.clone(),
+ resource_common_data,
+ connector_auth_type: old_router_data.connector_auth_type.clone(),
+ request: old_router_data.request.clone(),
+ response: old_router_data.response.clone(),
+ })
+ }
+
+ fn to_old_router_data(
+ new_router_data: RouterDataV2<T, Self, Req, Resp>,
+ ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
+ where
+ Self: Sized,
+ {
+ let Self {
+ merchant_id,
+ customer_id,
+ connector_customer,
+ payment_id,
+ attempt_id,
+ status,
+ payment_method,
+ description,
+ address,
+ auth_type,
+ connector_meta_data,
+ amount_captured,
+ minor_amount_captured,
+ access_token,
+ session_token,
+ reference_id,
+ payment_method_token,
+ recurring_mandate_payment_data,
+ preprocessing_id,
+ payment_method_balance,
+ connector_api_version,
+ connector_request_reference_id,
+ test_mode,
+ connector_http_status_code,
+ external_latency,
+ apple_pay_flow,
+ connector_response,
+ payment_method_status,
+ } = new_router_data.resource_common_data;
+ let mut router_data = get_default_router_data(
+ new_router_data.tenant_id.clone(),
+ "external vault proxy",
+ new_router_data.request,
+ new_router_data.response,
+ );
+ router_data.merchant_id = merchant_id;
+ router_data.customer_id = customer_id;
+ router_data.connector_customer = connector_customer;
+ router_data.payment_id = payment_id;
+ router_data.attempt_id = attempt_id;
+ router_data.status = status;
+ router_data.payment_method = payment_method;
+ router_data.description = description;
+ router_data.address = address;
+ router_data.auth_type = auth_type;
+ router_data.connector_meta_data = connector_meta_data;
+ router_data.amount_captured = amount_captured;
+ router_data.minor_amount_captured = minor_amount_captured;
+ router_data.access_token = access_token;
+ router_data.session_token = session_token;
+ router_data.reference_id = reference_id;
+ router_data.payment_method_token = payment_method_token;
+ router_data.recurring_mandate_payment_data = recurring_mandate_payment_data;
+ router_data.preprocessing_id = preprocessing_id;
+ router_data.payment_method_balance = payment_method_balance;
+ router_data.connector_api_version = connector_api_version;
+ router_data.connector_request_reference_id = connector_request_reference_id;
+ router_data.test_mode = test_mode;
+ router_data.connector_http_status_code = connector_http_status_code;
+ router_data.external_latency = external_latency;
+ router_data.apple_pay_flow = apple_pay_flow;
+ router_data.connector_response = connector_response;
+ router_data.payment_method_status = payment_method_status;
+ Ok(router_data)
+ }
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 83629e53d0..fe4bd5e323 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -89,7 +89,7 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult
ring = "0.17.14"
rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] }
rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }
-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2263c96a70f2606475ab30e6f716b2773e1fd093", package = "rust-grpc-client" }
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "aae51574fed25b0a7849e3832cff8904bc310cf5", package = "rust-grpc-client" }
rustc-hash = "1.1.0"
rustls = "0.22"
rustls-pemfile = "2"
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0c0061e791..371f625a82 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1510,6 +1510,130 @@ where
Ok((payment_data, req, None, None))
}
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments, clippy::type_complexity)]
+#[instrument(skip_all, fields(payment_id, merchant_id))]
+pub async fn external_vault_proxy_for_payments_operation_core<F, Req, Op, FData, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ merchant_context: domain::MerchantContext,
+ profile: domain::Profile,
+ operation: Op,
+ req: Req,
+ get_tracker_response: operations::GetTrackerResponse<D>,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+ return_raw_connector_response: Option<bool>,
+) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
+where
+ F: Send + Clone + Sync,
+ Req: Send + Sync + Authenticate,
+ Op: Operation<F, Req, Data = D> + Send + Sync,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+
+ // To create connector flow specific interface data
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+
+ RouterData<F, FData, router_types::PaymentsResponseData>:
+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
+
+ // To perform router related operation for PaymentResponse
+ PaymentResponse: Operation<F, FData, Data = D>,
+ FData: Send + Sync + Clone,
+{
+ let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
+
+ // Get the trackers related to track the state of the payment
+ let operations::GetTrackerResponse { mut payment_data } = get_tracker_response;
+
+ let (_operation, customer) = operation
+ .to_domain()?
+ .get_customer_details(
+ state,
+ &mut payment_data,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
+ .attach_printable("Failed while fetching/creating customer")?;
+
+ // consume the req merchant_connector_id and set it in the payment_data
+ let connector = operation
+ .to_domain()?
+ .perform_routing(&merchant_context, &profile, state, &mut payment_data)
+ .await?;
+
+ let payment_data = match connector {
+ ConnectorCallType::PreDetermined(connector_data) => {
+ let (mca_type_details, updated_customer, router_data) =
+ call_connector_service_prerequisites(
+ state,
+ req_state.clone(),
+ &merchant_context,
+ connector_data.connector_data.clone(),
+ &operation,
+ &mut payment_data,
+ &customer,
+ call_connector_action.clone(),
+ None,
+ header_payload.clone(),
+ None,
+ &profile,
+ false,
+ false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
+ req.should_return_raw_response(),
+ )
+ .await?;
+
+ let router_data = call_unified_connector_service_for_external_proxy(
+ state,
+ req_state.clone(),
+ &merchant_context,
+ connector_data.connector_data.clone(),
+ &operation,
+ &mut payment_data,
+ &customer,
+ call_connector_action.clone(),
+ None, // schedule_time is not used in PreDetermined ConnectorCallType
+ header_payload.clone(),
+ #[cfg(feature = "frm")]
+ None,
+ &profile,
+ false,
+ false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
+ req.should_return_raw_response(),
+ mca_type_details,
+ router_data,
+ updated_customer,
+ )
+ .await?;
+ let payments_response_operation = Box::new(PaymentResponse);
+
+ payments_response_operation
+ .to_post_update_tracker()?
+ .update_tracker(
+ state,
+ payment_data,
+ router_data,
+ merchant_context.get_merchant_key_store(),
+ merchant_context.get_merchant_account().storage_scheme,
+ )
+ .await?
+ }
+ ConnectorCallType::Retryable(_) => todo!(),
+ ConnectorCallType::SessionMultiple(_) => todo!(),
+ ConnectorCallType::Skip => payment_data,
+ };
+
+ Ok((payment_data, req, None, None))
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
@@ -2162,6 +2286,85 @@ where
)
}
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+pub async fn external_vault_proxy_for_payments_core<F, Res, Req, Op, FData, D>(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_context: domain::MerchantContext,
+ profile: domain::Profile,
+ operation: Op,
+ req: Req,
+ payment_id: id_type::GlobalPaymentId,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+ return_raw_connector_response: Option<bool>,
+) -> RouterResponse<Res>
+where
+ F: Send + Clone + Sync,
+ Req: Send + Sync + Authenticate,
+ FData: Send + Sync + Clone,
+ Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone,
+ Req: Debug,
+ D: OperationSessionGetters<F>
+ + OperationSessionSetters<F>
+ + transformers::GenerateResponse<Res>
+ + Send
+ + Sync
+ + Clone,
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+
+ PaymentResponse: Operation<F, FData, Data = D>,
+
+ RouterData<F, FData, router_types::PaymentsResponseData>:
+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
+{
+ operation
+ .to_validate_request()?
+ .validate_request(&req, &merchant_context)?;
+
+ let get_tracker_response = operation
+ .to_get_tracker()?
+ .get_trackers(
+ &state,
+ &payment_id,
+ &req,
+ &merchant_context,
+ &profile,
+ &header_payload,
+ )
+ .await?;
+
+ let (payment_data, _req, connector_http_status_code, external_latency) =
+ external_vault_proxy_for_payments_operation_core::<_, _, _, _, _>(
+ &state,
+ req_state,
+ merchant_context.clone(),
+ profile.clone(),
+ operation.clone(),
+ req,
+ get_tracker_response,
+ call_connector_action,
+ header_payload.clone(),
+ return_raw_connector_response,
+ )
+ .await?;
+
+ payment_data.generate_response(
+ &state,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ &merchant_context,
+ &profile,
+ None,
+ )
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn record_attempt_core(
@@ -4686,6 +4889,71 @@ where
})
.await
}
+
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+pub async fn call_unified_connector_service_for_external_proxy<F, RouterDReq, ApiRequest, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ merchant_context: &domain::MerchantContext,
+ _connector: api::ConnectorData,
+ operation: &BoxedOperation<'_, F, ApiRequest, D>,
+ payment_data: &mut D,
+ customer: &Option<domain::Customer>,
+ _call_connector_action: CallConnectorAction,
+ _schedule_time: Option<time::PrimitiveDateTime>,
+ header_payload: HeaderPayload,
+ frm_suggestion: Option<storage_enums::FrmSuggestion>,
+ _business_profile: &domain::Profile,
+ _is_retry_payment: bool,
+ _should_retry_with_pan: bool,
+ _return_raw_connector_response: Option<bool>,
+ merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
+ mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
+ _updated_customer: Option<storage::CustomerUpdate>,
+) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
+where
+ F: Send + Clone + Sync,
+ RouterDReq: Send + Sync,
+
+ // To create connector flow specific interface data
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
+ RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
+{
+ record_time_taken_with(|| async {
+ (_, *payment_data) = operation
+ .to_update_tracker()?
+ .update_trackers(
+ state,
+ req_state,
+ payment_data.clone(),
+ customer.clone(),
+ merchant_context.get_merchant_account().storage_scheme,
+ None,
+ merchant_context.get_merchant_key_store(),
+ frm_suggestion,
+ header_payload.clone(),
+ )
+ .await?;
+
+ router_data
+ .call_unified_connector_service(
+ state,
+ merchant_connector_account_type_details.clone(),
+ merchant_context,
+ )
+ .await?;
+
+ Ok(router_data)
+ })
+ .await
+}
+
#[cfg(feature = "v1")]
// This function does not perform the tokenization action, as the payment method is not saved in this flow.
#[allow(clippy::too_many_arguments)]
@@ -4982,6 +5250,131 @@ where
Ok(router_data)
}
+
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+pub async fn call_connector_service_for_external_vault_proxy<F, RouterDReq, ApiRequest, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ merchant_context: &domain::MerchantContext,
+ connector: api::ConnectorData,
+ operation: &BoxedOperation<'_, F, ApiRequest, D>,
+ payment_data: &mut D,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+ business_profile: &domain::Profile,
+ return_raw_connector_response: Option<bool>,
+) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
+where
+ F: Send + Clone + Sync,
+ RouterDReq: Send + Sync,
+
+ // To create connector flow specific interface data
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
+ RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
+{
+ let stime_connector = Instant::now();
+
+ let merchant_connector_account =
+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
+ helpers::get_merchant_connector_account_v2(
+ state,
+ merchant_context.get_merchant_key_store(),
+ connector.merchant_connector_id.as_ref(),
+ )
+ .await?,
+ ));
+ operation
+ .to_domain()?
+ .populate_payment_data(
+ state,
+ payment_data,
+ merchant_context,
+ business_profile,
+ &connector,
+ )
+ .await?;
+
+ let mut router_data = payment_data
+ .construct_router_data(
+ state,
+ connector.connector.id(),
+ merchant_context,
+ &None,
+ &merchant_connector_account,
+ None,
+ None,
+ )
+ .await?;
+
+ // let add_access_token_result = router_data
+ // .add_access_token(
+ // state,
+ // &connector,
+ // merchant_context,
+ // payment_data.get_creds_identifier(),
+ // )
+ // .await?;
+
+ // router_data = router_data.add_session_token(state, &connector).await?;
+
+ // let mut should_continue_further = access_token::update_router_data_with_access_token_result(
+ // &add_access_token_result,
+ // &mut router_data,
+ // &call_connector_action,
+ // );
+ let should_continue_further = true;
+
+ let (connector_request, should_continue_further) = if should_continue_further {
+ router_data
+ .build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
+ .await?
+ } else {
+ (None, false)
+ };
+
+ (_, *payment_data) = operation
+ .to_update_tracker()?
+ .update_trackers(
+ state,
+ req_state,
+ payment_data.clone(),
+ None,
+ merchant_context.get_merchant_account().storage_scheme,
+ None,
+ merchant_context.get_merchant_key_store(),
+ None,
+ header_payload.clone(),
+ )
+ .await?;
+
+ let router_data = if should_continue_further {
+ router_data
+ .decide_flows(
+ state,
+ &connector,
+ call_connector_action,
+ connector_request,
+ business_profile,
+ header_payload.clone(),
+ return_raw_connector_response,
+ )
+ .await
+ } else {
+ Ok(router_data)
+ }?;
+
+ let etime_connector = Instant::now();
+ let duration_connector = etime_connector.saturating_duration_since(stime_connector);
+ tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
+
+ Ok(router_data)
+}
struct ApplePayWallet;
struct PazeWallet;
struct GooglePayWallet;
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 039dda3477..3a568a5639 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -4,6 +4,8 @@ pub mod cancel_flow;
pub mod cancel_post_capture_flow;
pub mod capture_flow;
pub mod complete_authorize_flow;
+#[cfg(feature = "v2")]
+pub mod external_proxy_flow;
pub mod incremental_authorization_flow;
pub mod post_session_tokens_flow;
pub mod psync_flow;
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index a51912e566..a90e6a5873 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -845,7 +845,7 @@ async fn call_unified_connector_service_authorize(
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
- payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(router_data)
+ payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*router_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
new file mode 100644
index 0000000000..636b3c23f7
--- /dev/null
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -0,0 +1,418 @@
+use async_trait::async_trait;
+use common_enums as enums;
+use error_stack::ResultExt;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
+#[cfg(feature = "v2")]
+use hyperswitch_domain_models::payments::PaymentConfirmData;
+use masking::ExposeInterface;
+use unified_connector_service_client::payments as payments_grpc;
+
+use super::{ConstructFlowSpecificData, Feature};
+use crate::{
+ core::{
+ errors::{ConnectorErrorExt, RouterResult},
+ mandate,
+ payments::{
+ self, access_token, customers, helpers, tokenization, transformers, PaymentData,
+ },
+ unified_connector_service,
+ },
+ logger,
+ routes::{metrics, SessionState},
+ services::{self, api::ConnectorValidation},
+ types::{
+ self, api, domain,
+ transformers::{ForeignFrom, ForeignTryFrom},
+ },
+ utils::OptionExt,
+};
+
+#[cfg(feature = "v2")]
+#[async_trait]
+impl
+ ConstructFlowSpecificData<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ > for PaymentConfirmData<api::ExternalVaultProxy>
+{
+ async fn construct_router_data<'a>(
+ &self,
+ state: &SessionState,
+ connector_id: &str,
+ merchant_context: &domain::MerchantContext,
+ customer: &Option<domain::Customer>,
+ merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+ ) -> RouterResult<
+ types::RouterData<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+ > {
+ Box::pin(
+ transformers::construct_external_vault_proxy_payment_router_data(
+ state,
+ self.clone(),
+ connector_id,
+ merchant_context,
+ customer,
+ merchant_connector_account,
+ merchant_recipient_data,
+ header_payload,
+ ),
+ )
+ .await
+ }
+}
+
+#[async_trait]
+impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
+ for types::ExternalVaultProxyPaymentsRouterData
+{
+ async fn decide_flows<'a>(
+ mut self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ call_connector_action: payments::CallConnectorAction,
+ connector_request: Option<services::Request>,
+ business_profile: &domain::Profile,
+ header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ return_raw_connector_response: Option<bool>,
+ ) -> RouterResult<Self> {
+ let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ logger::debug!(auth_type=?self.auth_type);
+ let mut auth_router_data = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &self,
+ call_connector_action.clone(),
+ connector_request,
+ return_raw_connector_response,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ // External vault proxy doesn't use integrity checks
+ auth_router_data.integrity_check = Ok(());
+ metrics::PAYMENT_COUNT.add(1, &[]);
+
+ Ok(auth_router_data)
+ }
+
+ async fn add_access_token<'a>(
+ &self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ merchant_context: &domain::MerchantContext,
+ creds_identifier: Option<&str>,
+ ) -> RouterResult<types::AddAccessTokenResult> {
+ access_token::add_access_token(state, connector, merchant_context, self, creds_identifier)
+ .await
+ }
+
+ async fn add_session_token<'a>(
+ self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ ) -> RouterResult<Self>
+ where
+ Self: Sized,
+ {
+ let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+ let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
+ &self,
+ types::AuthorizeSessionTokenData::foreign_from(&self),
+ ));
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ authorize_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+ let mut router_data = self;
+ router_data.session_token = resp.session_token;
+ Ok(router_data)
+ }
+
+ async fn add_payment_method_token<'a>(
+ &mut self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ tokenization_action: &payments::TokenizationAction,
+ should_continue_payment: bool,
+ ) -> RouterResult<types::PaymentMethodTokenResult> {
+ let request = self.request.clone();
+ tokenization::add_payment_method_token(
+ state,
+ connector,
+ tokenization_action,
+ self,
+ types::PaymentMethodTokenizationData::try_from(request)?,
+ should_continue_payment,
+ )
+ .await
+ }
+
+ async fn preprocessing_steps<'a>(
+ self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ ) -> RouterResult<Self> {
+ todo!()
+ }
+
+ async fn postprocessing_steps<'a>(
+ self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ ) -> RouterResult<Self> {
+ todo!()
+ }
+
+ async fn create_connector_customer<'a>(
+ &self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ ) -> RouterResult<Option<String>> {
+ customers::create_connector_customer(
+ state,
+ connector,
+ self,
+ types::ConnectorCustomerData::try_from(self)?,
+ )
+ .await
+ }
+
+ async fn build_flow_specific_connector_request(
+ &mut self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ call_connector_action: payments::CallConnectorAction,
+ ) -> RouterResult<(Option<services::Request>, bool)> {
+ match call_connector_action {
+ payments::CallConnectorAction::Trigger => {
+ connector
+ .connector
+ .validate_connector_against_payment_request(
+ self.request.capture_method,
+ self.payment_method,
+ self.request.payment_method_type,
+ )
+ .to_payment_failed_response()?;
+
+ // Check if the connector supports mandate payment
+ // if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
+ if self.request.setup_future_usage
+ == Some(diesel_models::enums::FutureUsage::OffSession)
+ && !self
+ .request
+ .payment_method_type
+ .and_then(|payment_method_type| {
+ state
+ .conf
+ .mandates
+ .supported_payment_methods
+ .0
+ .get(&enums::PaymentMethod::from(payment_method_type))
+ .and_then(|supported_pm_for_mandates| {
+ supported_pm_for_mandates.0.get(&payment_method_type).map(
+ |supported_connector_for_mandates| {
+ supported_connector_for_mandates
+ .connector_list
+ .contains(&connector.connector_name)
+ },
+ )
+ })
+ })
+ .unwrap_or(false)
+ {
+ // downgrade the setup future usage to on session
+ self.request.setup_future_usage =
+ Some(diesel_models::enums::FutureUsage::OnSession);
+ };
+
+ // External vault proxy doesn't use regular payment method validation
+ // Skip mandate payment validation for external vault proxy
+
+ let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
+ api::ExternalVaultProxy,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ metrics::EXECUTE_PRETASK_COUNT.add(
+ 1,
+ router_env::metric_attributes!(
+ ("connector", connector.connector_name.to_string()),
+ ("flow", format!("{:?}", api::ExternalVaultProxy)),
+ ),
+ );
+
+ logger::debug!(completed_pre_tasks=?true);
+
+ // External vault proxy always proceeds
+ Ok((
+ connector_integration
+ .build_request(self, &state.conf.connectors)
+ .to_payment_failed_response()?,
+ true,
+ ))
+ }
+ _ => Ok((None, true)),
+ }
+ }
+
+ async fn create_order_at_connector(
+ &mut self,
+ state: &SessionState,
+ connector: &api::ConnectorData,
+ should_continue_payment: bool,
+ ) -> RouterResult<Option<types::CreateOrderResult>> {
+ if connector
+ .connector_name
+ .requires_order_creation_before_payment(self.payment_method)
+ && should_continue_payment
+ {
+ let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
+ api::CreateOrder,
+ types::CreateOrderRequestData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
+
+ let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
+ Err(types::ErrorResponse::default());
+
+ let createorder_router_data =
+ helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
+ self.clone(),
+ request_data,
+ response_data,
+ );
+
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &createorder_router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ let create_order_resp = match resp.response {
+ Ok(res) => {
+ if let types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id } =
+ res
+ {
+ Ok(order_id)
+ } else {
+ Err(error_stack::report!(ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Unexpected response format from connector: {res:?}",
+ )))?
+ }
+ }
+ Err(error) => Err(error),
+ };
+
+ Ok(Some(types::CreateOrderResult {
+ create_order_result: create_order_resp,
+ }))
+ } else {
+ // If the connector does not require order creation, return None
+ Ok(None)
+ }
+ }
+
+ fn update_router_data_with_create_order_response(
+ &mut self,
+ create_order_result: types::CreateOrderResult,
+ ) {
+ match create_order_result.create_order_result {
+ Ok(order_id) => {
+ self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
+ self.response =
+ Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id });
+ }
+ Err(err) => {
+ self.response = Err(err.clone());
+ }
+ }
+ }
+
+ async fn call_unified_connector_service<'a>(
+ &mut self,
+ state: &SessionState,
+ #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
+ #[cfg(feature = "v2")]
+ merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
+ merchant_context: &domain::MerchantContext,
+ ) -> RouterResult<()> {
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let payment_authorize_request =
+ payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*self)
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct Payment Authorize Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ merchant_context,
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct request metadata")?;
+
+ let response = client
+ .payment_authorize(
+ payment_authorize_request,
+ connector_auth_metadata,
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to authorize payment")?;
+
+ let payment_authorize_response = response.into_inner();
+
+ let (status, router_data_response, status_code) =
+ unified_connector_service::handle_unified_connector_service_response_for_payment_authorize(
+ payment_authorize_response.clone(),
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ self.status = status;
+ self.response = router_data_response;
+ self.raw_connector_response = payment_authorize_response
+ .raw_connector_response
+ .map(masking::Secret::new);
+ self.connector_http_status_code = Some(status_code);
+
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 6a21d1b6d8..1c793209a7 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -49,6 +49,9 @@ pub mod payment_update_intent;
#[cfg(feature = "v2")]
pub mod proxy_payments_intent;
+#[cfg(feature = "v2")]
+pub mod external_vault_proxy_payment_intent;
+
#[cfg(feature = "v2")]
pub mod payment_get;
diff --git a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
new file mode 100644
index 0000000000..7e58dc95c1
--- /dev/null
+++ b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
@@ -0,0 +1,549 @@
+use api_models::payments::ExternalVaultProxyPaymentsRequest;
+use async_trait::async_trait;
+use common_enums::enums;
+use common_utils::types::keymanager::ToEncryptable;
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData, payments::PaymentConfirmData,
+};
+use hyperswitch_interfaces::api::ConnectorSpecifications;
+use masking::PeekInterface;
+use router_env::{instrument, tracing};
+
+use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest};
+use crate::{
+ core::{
+ errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payments::{
+ self,
+ operations::{self, ValidateStatusForOperation},
+ OperationSessionGetters, OperationSessionSetters,
+ },
+ },
+ routes::{app::ReqState, SessionState},
+ types::{
+ self,
+ api::{self, ConnectorCallType},
+ domain::{self, types as domain_types},
+ storage::{self, enums as storage_enums},
+ },
+ utils::OptionExt,
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct ExternalVaultProxyPaymentIntent;
+
+impl ValidateStatusForOperation for ExternalVaultProxyPaymentIntent {
+ /// Validate if the current operation can be performed on the current status of the payment intent
+ fn validate_status_for_operation(
+ &self,
+ intent_status: common_enums::IntentStatus,
+ ) -> Result<(), errors::ApiErrorResponse> {
+ match intent_status {
+ common_enums::IntentStatus::RequiresPaymentMethod
+ | common_enums::IntentStatus::Failed
+ | common_enums::IntentStatus::Processing => Ok(()),
+ common_enums::IntentStatus::Conflicted
+ | common_enums::IntentStatus::Succeeded
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::RequiresConfirmation
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable
+ | common_enums::IntentStatus::CancelledPostCapture
+ | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
+ | common_enums::IntentStatus::Expired => {
+ Err(errors::ApiErrorResponse::PaymentUnexpectedState {
+ current_flow: format!("{self:?}"),
+ field_name: "status".to_string(),
+ current_value: intent_status.to_string(),
+ states: ["requires_payment_method", "failed", "processing"].join(", "),
+ })
+ }
+ }
+ }
+}
+
+type BoxedConfirmOperation<'b, F> =
+ super::BoxedOperation<'b, F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>;
+
+impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest>
+ for &ExternalVaultProxyPaymentIntent
+{
+ type Data = PaymentConfirmData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<
+ &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync),
+ > {
+ Ok(*self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
+ > {
+ Ok(*self)
+ }
+ fn to_domain(
+ &self,
+ ) -> RouterResult<&(dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>)> {
+ Ok(*self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
+ > {
+ Ok(*self)
+ }
+}
+
+#[automatically_derived]
+impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest>
+ for ExternalVaultProxyPaymentIntent
+{
+ type Data = PaymentConfirmData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<
+ &(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync),
+ > {
+ Ok(self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
+ > {
+ Ok(self)
+ }
+ fn to_domain(
+ &self,
+ ) -> RouterResult<&dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>> {
+ Ok(self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
+ > {
+ Ok(self)
+ }
+}
+
+impl<F: Send + Clone + Sync>
+ ValidateRequest<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>
+ for ExternalVaultProxyPaymentIntent
+{
+ #[instrument(skip_all)]
+ fn validate_request<'a, 'b>(
+ &'b self,
+ _request: &ExternalVaultProxyPaymentsRequest,
+ merchant_context: &'a domain::MerchantContext,
+ ) -> RouterResult<operations::ValidateResult> {
+ let validate_result = operations::ValidateResult {
+ merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
+ storage_scheme: merchant_context.get_merchant_account().storage_scheme,
+ requeue: false,
+ };
+
+ Ok(validate_result)
+ }
+}
+
+#[async_trait]
+impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest>
+ for ExternalVaultProxyPaymentIntent
+{
+ #[instrument(skip_all)]
+ async fn get_trackers<'a>(
+ &'a self,
+ state: &'a SessionState,
+ payment_id: &common_utils::id_type::GlobalPaymentId,
+ request: &ExternalVaultProxyPaymentsRequest,
+ merchant_context: &domain::MerchantContext,
+ _profile: &domain::Profile,
+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
+
+ let payment_intent = db
+ .find_payment_intent_by_id(
+ key_manager_state,
+ payment_id,
+ merchant_context.get_merchant_key_store(),
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ self.validate_status_for_operation(payment_intent.status)?;
+
+ let cell_id = state.conf.cell_information.id.clone();
+
+ let batch_encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
+ domain_types::CryptoOperation::BatchEncrypt(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
+ payment_method_billing_address: None,
+ },
+ ),
+ ),
+ common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
+ merchant_context.get_merchant_key_store().key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details".to_string())?;
+
+ let encrypted_data =
+ hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details")?;
+
+ let payment_attempt = match payment_intent.active_attempt_id.clone() {
+ Some(ref active_attempt_id) => db
+ .find_payment_attempt_by_id(
+ key_manager_state,
+ merchant_context.get_merchant_key_store(),
+ active_attempt_id,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .attach_printable("Could not find payment attempt")?,
+
+ None => {
+ // TODO: Implement external vault specific payment attempt creation logic
+ let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
+ hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::external_vault_proxy_create_domain_model(
+ &payment_intent,
+ cell_id,
+ storage_scheme,
+ request,
+ encrypted_data
+ )
+ .await?;
+ db.insert_payment_attempt(
+ key_manager_state,
+ merchant_context.get_merchant_key_store(),
+ payment_attempt_domain_model,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not insert payment attempt")?
+ }
+ };
+
+ // TODO: Extract external vault specific token/credentials from request
+ let processor_payment_token = None; // request.external_vault_details.processor_payment_token.clone();
+
+ let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
+ payment_intent
+ .shipping_address
+ .clone()
+ .map(|address| address.into_inner()),
+ payment_intent
+ .billing_address
+ .clone()
+ .map(|address| address.into_inner()),
+ payment_attempt
+ .payment_method_billing_address
+ .clone()
+ .map(|address| address.into_inner()),
+ Some(true),
+ );
+
+ // TODO: Implement external vault specific mandate data handling
+ let mandate_data_input = api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: processor_payment_token.map(|token| {
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ api_models::payments::ConnectorMandateReferenceId::new(
+ Some(token),
+ None,
+ None,
+ None,
+ None,
+ ),
+ )
+ }),
+ };
+ let payment_method_data = request.payment_method_data.payment_method_data.clone().map(
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::from,
+ );
+
+ let payment_data = PaymentConfirmData {
+ flow: std::marker::PhantomData,
+ payment_intent,
+ payment_attempt,
+ payment_method_data: None, // TODO: Review for external vault
+ payment_address,
+ mandate_data: Some(mandate_data_input),
+ payment_method: None,
+ merchant_connector_details: None,
+ external_vault_pmd: payment_method_data,
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse { payment_data };
+
+ Ok(get_trackers_response)
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>
+ for ExternalVaultProxyPaymentIntent
+{
+ async fn get_customer_details<'a>(
+ &'a self,
+ _state: &SessionState,
+ _payment_data: &mut PaymentConfirmData<F>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
+ {
+ // TODO: Implement external vault specific customer details retrieval
+ Ok((Box::new(self), None))
+ }
+
+ #[instrument(skip_all)]
+ async fn make_pm_data<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_data: &mut PaymentConfirmData<F>,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ _key_store: &domain::MerchantKeyStore,
+ _customer: &Option<domain::Customer>,
+ _business_profile: &domain::Profile,
+ _should_retry_with_pan: bool,
+ ) -> RouterResult<(
+ BoxedConfirmOperation<'a, F>,
+ Option<PaymentMethodData>,
+ Option<String>,
+ )> {
+ // TODO: Implement external vault specific payment method data creation
+ Ok((Box::new(self), None, None))
+ }
+
+ #[instrument(skip_all)]
+ async fn populate_payment_data<'a>(
+ &'a self,
+ _state: &SessionState,
+ payment_data: &mut PaymentConfirmData<F>,
+ _merchant_context: &domain::MerchantContext,
+ _business_profile: &domain::Profile,
+ connector_data: &api::ConnectorData,
+ ) -> CustomResult<(), errors::ApiErrorResponse> {
+ let connector_request_reference_id = connector_data
+ .connector
+ .generate_connector_request_reference_id(
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ );
+ payment_data.set_connector_request_reference_id(Some(connector_request_reference_id));
+ Ok(())
+ }
+
+ async fn perform_routing<'a>(
+ &'a self,
+ merchant_context: &domain::MerchantContext,
+ business_profile: &domain::Profile,
+ state: &SessionState,
+ payment_data: &mut PaymentConfirmData<F>,
+ ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
+ payments::connector_selection(
+ state,
+ merchant_context,
+ business_profile,
+ payment_data,
+ None,
+ )
+ .await
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest>
+ for ExternalVaultProxyPaymentIntent
+{
+ #[instrument(skip_all)]
+ async fn update_trackers<'b>(
+ &'b self,
+ state: &'b SessionState,
+ _req_state: ReqState,
+ mut payment_data: PaymentConfirmData<F>,
+ _customer: Option<domain::Customer>,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ _updated_customer: Option<storage::CustomerUpdate>,
+ key_store: &domain::MerchantKeyStore,
+ _frm_suggestion: Option<api_models::enums::FrmSuggestion>,
+ _header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
+ where
+ F: 'b + Send,
+ {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let intent_status = common_enums::IntentStatus::Processing;
+ let attempt_status = common_enums::AttemptStatus::Pending;
+
+ let connector = payment_data
+ .payment_attempt
+ .connector
+ .clone()
+ .get_required_value("connector")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Connector is none when constructing response")?;
+
+ let merchant_connector_id = Some(
+ payment_data
+ .payment_attempt
+ .merchant_connector_id
+ .clone()
+ .get_required_value("merchant_connector_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Merchant connector id is none when constructing response")?,
+ );
+
+ let payment_intent_update =
+ hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
+ status: intent_status,
+ updated_by: storage_scheme.to_string(),
+ active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
+ };
+
+ let authentication_type = payment_data
+ .payment_intent
+ .authentication_type
+ .unwrap_or_default();
+
+ let connector_request_reference_id = payment_data
+ .payment_attempt
+ .connector_request_reference_id
+ .clone();
+
+ let connector_response_reference_id = payment_data
+ .payment_attempt
+ .connector_response_reference_id
+ .clone();
+
+ let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
+ status: attempt_status,
+ updated_by: storage_scheme.to_string(),
+ connector,
+ merchant_connector_id,
+ authentication_type,
+ connector_request_reference_id,
+ connector_response_reference_id,
+ };
+
+ let updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent.clone(),
+ payment_intent_update,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+
+ payment_data.payment_intent = updated_payment_intent;
+
+ let updated_payment_attempt = db
+ .update_payment_attempt(
+ key_manager_state,
+ key_store,
+ payment_data.payment_attempt.clone(),
+ payment_attempt_update,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment attempt")?;
+
+ payment_data.payment_attempt = updated_payment_attempt;
+
+ Ok((Box::new(self), payment_data))
+ }
+}
+
+#[cfg(feature = "v2")]
+#[async_trait]
+impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
+ for ExternalVaultProxyPaymentIntent
+{
+ async fn update_tracker<'b>(
+ &'b self,
+ state: &'b SessionState,
+ mut payment_data: PaymentConfirmData<F>,
+ response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> RouterResult<PaymentConfirmData<F>>
+ where
+ F: 'b + Send + Sync,
+ types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
+ F,
+ types::PaymentsAuthorizeData,
+ PaymentConfirmData<F>,
+ >,
+ {
+ use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
+
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let response_router_data = response;
+
+ let payment_intent_update =
+ response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
+ let payment_attempt_update =
+ response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
+
+ let updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent,
+ payment_intent_update,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+
+ let updated_payment_attempt = db
+ .update_payment_attempt(
+ key_manager_state,
+ key_store,
+ payment_data.payment_attempt,
+ payment_attempt_update,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment attempt")?;
+
+ payment_data.payment_intent = updated_payment_intent;
+ payment_data.payment_attempt = updated_payment_attempt;
+
+ // TODO: Add external vault specific post-update logic
+
+ Ok(payment_data)
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
index edffe30c14..c2f3e414fa 100644
--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs
@@ -275,6 +275,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir
mandate_data: None,
payment_method: None,
merchant_connector_details,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 29a1e43ec9..0ffc4f84da 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -2783,6 +2783,133 @@ impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentRe
}
}
+#[cfg(feature = "v2")]
+impl
+ Operation<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ > for PaymentResponse
+{
+ type Data =
+ PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
+ fn to_post_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ Self::Data,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ > + Send
+ + Sync),
+ > {
+ Ok(self)
+ }
+}
+
+#[cfg(feature = "v2")]
+impl
+ Operation<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ > for &PaymentResponse
+{
+ type Data =
+ PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
+ fn to_post_update_tracker(
+ &self,
+ ) -> RouterResult<
+ &(dyn PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ Self::Data,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ > + Send
+ + Sync),
+ > {
+ Ok(*self)
+ }
+}
+
+#[cfg(feature = "v2")]
+#[async_trait]
+impl
+ PostUpdateTracker<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ > for PaymentResponse
+{
+ async fn update_tracker<'b>(
+ &'b self,
+ state: &'b SessionState,
+ mut payment_data: PaymentConfirmData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ >,
+ response: types::RouterData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> RouterResult<
+ PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
+ >
+ where
+ types::RouterData<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
+ hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
+ hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
+ PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
+ >,
+ {
+ use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
+
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let response_router_data = response;
+
+ let payment_intent_update =
+ response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
+ let payment_attempt_update =
+ response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
+
+ let updated_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent,
+ payment_intent_update,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment intent")?;
+
+ let updated_payment_attempt = db
+ .update_payment_attempt(
+ key_manager_state,
+ key_store,
+ payment_data.payment_attempt,
+ payment_attempt_update,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update payment attempt")?;
+
+ payment_data.payment_intent = updated_payment_intent;
+ payment_data.payment_attempt = updated_payment_attempt;
+
+ // TODO: Add external vault specific post-update logic if needed
+
+ Ok(payment_data)
+ }
+}
+
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRequestData>
diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs
index 45c7cb18c3..c53aff42b5 100644
--- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs
+++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs
@@ -268,6 +268,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR
mandate_data: Some(mandate_data_input),
payment_method: None,
merchant_connector_details: None,
+ external_vault_pmd: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 41b5628147..a1be3e8501 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -24,6 +24,8 @@ use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_r
#[cfg(feature = "v2")]
use hyperswitch_interfaces::api::ConnectorSpecifications;
#[cfg(feature = "v2")]
+use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
+#[cfg(feature = "v2")]
use masking::PeekInterface;
use masking::{ExposeInterface, Maskable, Secret};
use router_env::{instrument, tracing};
@@ -181,6 +183,90 @@ where
Ok(router_data)
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn construct_external_vault_proxy_router_data_v2<'a>(
+ state: &'a SessionState,
+ merchant_account: &domain::MerchantAccount,
+ merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
+ payment_data: &hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>,
+ request: types::ExternalVaultProxyPaymentsData,
+ connector_request_reference_id: String,
+ connector_customer_id: Option<String>,
+ customer_id: Option<common_utils::id_type::CustomerId>,
+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+) -> RouterResult<
+ hyperswitch_domain_models::router_data_v2::RouterDataV2<
+ api::ExternalVaultProxy,
+ hyperswitch_domain_models::router_data_v2::ExternalVaultProxyFlowData,
+ types::ExternalVaultProxyPaymentsData,
+ types::PaymentsResponseData,
+ >,
+> {
+ use hyperswitch_domain_models::router_data_v2::{ExternalVaultProxyFlowData, RouterDataV2};
+
+ let auth_type = merchant_connector_account
+ .get_connector_account_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;
+
+ let external_vault_proxy_flow_data = ExternalVaultProxyFlowData {
+ merchant_id: merchant_account.get_id().clone(),
+ customer_id,
+ connector_customer: connector_customer_id,
+ payment_id: payment_data
+ .payment_attempt
+ .payment_id
+ .get_string_repr()
+ .to_owned(),
+ attempt_id: payment_data
+ .payment_attempt
+ .get_id()
+ .get_string_repr()
+ .to_owned(),
+ status: payment_data.payment_attempt.status,
+ payment_method: payment_data.payment_attempt.payment_method_type,
+ description: payment_data
+ .payment_intent
+ .description
+ .as_ref()
+ .map(|description| description.get_string_repr())
+ .map(ToOwned::to_owned),
+ address: payment_data.payment_address.clone(),
+ auth_type: payment_data.payment_attempt.authentication_type,
+ connector_meta_data: merchant_connector_account.get_metadata(),
+ amount_captured: None,
+ minor_amount_captured: None,
+ access_token: None,
+ session_token: None,
+ reference_id: None,
+ payment_method_token: None,
+ recurring_mandate_payment_data: None,
+ preprocessing_id: payment_data.payment_attempt.preprocessing_step_id.clone(),
+ payment_method_balance: None,
+ connector_api_version: None,
+ connector_request_reference_id,
+ test_mode: Some(true),
+ connector_http_status_code: None,
+ external_latency: None,
+ apple_pay_flow: None,
+ connector_response: None,
+ payment_method_status: None,
+ };
+
+ let router_data_v2 = RouterDataV2 {
+ flow: PhantomData,
+ tenant_id: state.tenant.tenant_id.clone(),
+ resource_common_data: external_vault_proxy_flow_data,
+ connector_auth_type: auth_type,
+ request,
+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
+ };
+
+ Ok(router_data_v2)
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
@@ -416,7 +502,183 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
Ok(router_data)
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn construct_external_vault_proxy_payment_router_data<'a>(
+ state: &'a SessionState,
+ payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>,
+ connector_id: &str,
+ merchant_context: &domain::MerchantContext,
+ customer: &'a Option<domain::Customer>,
+ merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
+ _merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
+) -> RouterResult<types::ExternalVaultProxyPaymentsRouterData> {
+ use masking::ExposeOptionInterface;
+ fp_utils::when(merchant_connector_account.is_disabled(), || {
+ Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
+ })?;
+
+ let auth_type = merchant_connector_account
+ .get_connector_account_details()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;
+
+ // TODO: Take Globalid and convert to connector reference id
+ let customer_id = customer
+ .to_owned()
+ .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone()))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Invalid global customer generated, not able to convert to reference id",
+ )?;
+
+ let connector_customer_id =
+ payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account);
+
+ let payment_method = payment_data.payment_attempt.payment_method_type;
+
+ let router_base_url = &state.base_url;
+ let attempt = &payment_data.payment_attempt;
+
+ let complete_authorize_url = Some(helpers::create_complete_authorize_url(
+ router_base_url,
+ attempt,
+ connector_id,
+ None,
+ ));
+
+ let webhook_url = match merchant_connector_account {
+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
+ merchant_connector_account,
+ ) => Some(helpers::create_webhook_url(
+ router_base_url,
+ &attempt.merchant_id,
+ merchant_connector_account.get_id().get_string_repr(),
+ )),
+ // TODO: Implement for connectors that require a webhook URL to be included in the request payload.
+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
+ };
+
+ let router_return_url = payment_data
+ .payment_intent
+ .create_finish_redirection_url(
+ router_base_url,
+ merchant_context
+ .get_merchant_account()
+ .publishable_key
+ .as_ref(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to construct finish redirection url")?
+ .to_string();
+
+ let connector_request_reference_id = payment_data
+ .payment_attempt
+ .connector_request_reference_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("connector_request_reference_id not found in payment_attempt")?;
+
+ let email = customer
+ .as_ref()
+ .and_then(|customer| customer.email.clone())
+ .map(pii::Email::from);
+
+ let browser_info = payment_data
+ .payment_attempt
+ .browser_info
+ .clone()
+ .map(types::BrowserInformation::from);
+ // TODO: few fields are repeated in both routerdata and request
+ let request = types::ExternalVaultProxyPaymentsData {
+ payment_method_data: payment_data
+ .external_vault_pmd
+ .clone()
+ .get_required_value("external vault proxy payment_method_data")?,
+ setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
+ mandate_id: payment_data.mandate_data.clone(),
+ off_session: None,
+ setup_mandate_details: None,
+ confirm: true,
+ statement_descriptor_suffix: None,
+ statement_descriptor: None,
+ capture_method: Some(payment_data.payment_intent.capture_method),
+ amount: payment_data
+ .payment_attempt
+ .amount_details
+ .get_net_amount()
+ .get_amount_as_i64(),
+ minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(),
+ order_tax_amount: None,
+ currency: payment_data.payment_intent.amount_details.currency,
+ browser_info,
+ email,
+ customer_name: None,
+ payment_experience: None,
+ order_details: None,
+ order_category: None,
+ session_token: None,
+ enrolled_for_3ds: true,
+ related_transaction_id: None,
+ payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
+ router_return_url: Some(router_return_url),
+ webhook_url,
+ complete_authorize_url,
+ customer_id: customer_id.clone(),
+ surcharge_details: None,
+ request_extended_authorization: None,
+ request_incremental_authorization: matches!(
+ payment_data
+ .payment_intent
+ .request_incremental_authorization,
+ RequestIncrementalAuthorization::True
+ ),
+ metadata: payment_data.payment_intent.metadata.clone().expose_option(),
+ authentication_data: None,
+ customer_acceptance: None,
+ split_payments: None,
+ merchant_order_reference_id: None,
+ integrity_object: None,
+ shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
+ additional_payment_method_data: None,
+ merchant_account_id: None,
+ merchant_config_currency: None,
+ connector_testing_data: None,
+ order_id: None,
+ };
+ let connector_mandate_request_reference_id = payment_data
+ .payment_attempt
+ .connector_token_details
+ .as_ref()
+ .and_then(|detail| detail.get_connector_token_request_reference_id());
+
+ // Construct RouterDataV2 for external vault proxy
+ let router_data_v2 = construct_external_vault_proxy_router_data_v2(
+ state,
+ merchant_context.get_merchant_account(),
+ merchant_connector_account,
+ &payment_data,
+ request,
+ connector_request_reference_id.clone(),
+ connector_customer_id.clone(),
+ customer_id.clone(),
+ header_payload.clone(),
+ )
+ .await?;
+
+ // Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait
+ let router_data = hyperswitch_domain_models::router_data_v2::flow_common_types::ExternalVaultProxyFlowData::to_old_router_data(router_data_v2)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Cannot construct router data for making the unified connector service call",
+ )?;
+
+ Ok(router_data)
+}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 2ef6e81eed..a7c329d039 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -355,6 +355,56 @@ pub fn build_unified_connector_service_payment_method(
}
}
+pub fn build_unified_connector_service_payment_method_for_external_proxy(
+ payment_method_data: hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,
+ payment_method_type: PaymentMethodType,
+) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> {
+ match payment_method_data {
+ hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
+ external_vault_card,
+ ) => {
+ let card_network = external_vault_card
+ .card_network
+ .clone()
+ .map(payments_grpc::CardNetwork::foreign_try_from)
+ .transpose()?;
+ let card_details = CardDetails {
+ card_number: external_vault_card.card_number.peek().to_string(),
+ card_exp_month: external_vault_card.card_exp_month.peek().to_string(),
+ card_exp_year: external_vault_card.card_exp_year.peek().to_string(),
+ card_cvc: external_vault_card.card_cvc.peek().to_string(),
+ card_holder_name: external_vault_card
+ .card_holder_name
+ .map(|name| name.expose()),
+ card_issuer: external_vault_card.card_issuer.clone(),
+ card_network: card_network.map(|card_network| card_network.into()),
+ card_type: external_vault_card.card_type.clone(),
+ bank_code: external_vault_card.bank_code.clone(),
+ nick_name: external_vault_card.nick_name.map(|n| n.expose()),
+ card_issuing_country_alpha2: external_vault_card.card_issuing_country.clone(),
+ };
+ let grpc_card_type = match payment_method_type {
+ PaymentMethodType::Credit => {
+ payments_grpc::card_payment_method_type::CardType::CreditProxy(card_details)
+ }
+ PaymentMethodType::Debit => {
+ payments_grpc::card_payment_method_type::CardType::DebitProxy(card_details)
+ }
+ _ => {
+ return Err(UnifiedConnectorServiceError::NotImplemented(format!(
+ "Unimplemented payment method subtype: {payment_method_type:?}"
+ ))
+ .into());
+ }
+ };
+ Ok(payments_grpc::PaymentMethod {
+ payment_method: Some(PaymentMethod::Card(CardPaymentMethodType {
+ card_type: Some(grpc_card_type),
+ })),
+ })
+ }
+ }
+}
pub fn build_unified_connector_service_auth_metadata(
#[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index c63fd4a4a6..6f50bc4a4a 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -9,9 +9,13 @@ use external_services::grpc_client::unified_connector_service::UnifiedConnectorS
use hyperswitch_connectors::utils::QrImage;
use hyperswitch_domain_models::{
router_data::{ErrorResponse, RouterData},
- router_flow_types::payments::{Authorize, PSync, SetupMandate},
+ router_flow_types::{
+ payments::{Authorize, PSync, SetupMandate},
+ ExternalVaultProxy,
+ },
router_request_types::{
- AuthenticationData, PaymentsAuthorizeData, PaymentsSyncData, SetupMandateRequestData,
+ AuthenticationData, ExternalVaultProxyPaymentsData, PaymentsAuthorizeData,
+ PaymentsSyncData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RedirectForm},
};
@@ -24,7 +28,7 @@ use unified_connector_service_client::payments::{
use url::Url;
use crate::{
- core::{errors, unified_connector_service::build_unified_connector_service_payment_method},
+ core::{errors, unified_connector_service},
types::transformers::ForeignTryFrom,
};
impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>
@@ -90,7 +94,130 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon
.request
.payment_method_type
.map(|payment_method_type| {
- build_unified_connector_service_payment_method(
+ unified_connector_service::build_unified_connector_service_payment_method(
+ router_data.request.payment_method_data.clone(),
+ payment_method_type,
+ )
+ })
+ .transpose()?;
+
+ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
+
+ let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?;
+
+ let browser_info = router_data
+ .request
+ .browser_info
+ .clone()
+ .map(payments_grpc::BrowserInformation::foreign_try_from)
+ .transpose()?;
+
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
+
+ let authentication_data = router_data
+ .request
+ .authentication_data
+ .clone()
+ .map(payments_grpc::AuthenticationData::foreign_try_from)
+ .transpose()?;
+
+ Ok(Self {
+ amount: router_data.request.amount,
+ currency: currency.into(),
+ payment_method,
+ return_url: router_data.request.router_return_url.clone(),
+ address: Some(address),
+ auth_type: auth_type.into(),
+ enrolled_for_3ds: router_data.request.enrolled_for_3ds,
+ request_incremental_authorization: router_data
+ .request
+ .request_incremental_authorization,
+ minor_amount: router_data.request.amount,
+ email: router_data
+ .request
+ .email
+ .clone()
+ .map(|e| e.expose().expose()),
+ browser_info,
+ access_token: None,
+ session_token: None,
+ order_tax_amount: router_data
+ .request
+ .order_tax_amount
+ .map(|order_tax_amount| order_tax_amount.get_amount_as_i64()),
+ customer_name: router_data
+ .request
+ .customer_name
+ .clone()
+ .map(|customer_name| customer_name.peek().to_owned()),
+ capture_method: capture_method.map(|capture_method| capture_method.into()),
+ webhook_url: router_data.request.webhook_url.clone(),
+ complete_authorize_url: router_data.request.complete_authorize_url.clone(),
+ setup_future_usage: None,
+ off_session: None,
+ customer_acceptance: None,
+ order_category: router_data.request.order_category.clone(),
+ payment_experience: None,
+ authentication_data,
+ request_extended_authorization: router_data
+ .request
+ .request_extended_authorization
+ .map(|request_extended_authorization| request_extended_authorization.is_true()),
+ merchant_order_reference_id: router_data.request.merchant_order_reference_id.clone(),
+ shipping_cost: router_data
+ .request
+ .shipping_cost
+ .map(|shipping_cost| shipping_cost.get_amount_as_i64()),
+ request_ref_id: Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ }),
+ connector_customer_id: router_data
+ .request
+ .customer_id
+ .as_ref()
+ .map(|id| id.get_string_repr().to_string()),
+ metadata: router_data
+ .request
+ .metadata
+ .as_ref()
+ .and_then(|val| val.as_object())
+ .map(|map| {
+ map.iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
+ .collect::<HashMap<String, String>>()
+ })
+ .unwrap_or_default(),
+ })
+ }
+}
+
+impl
+ ForeignTryFrom<
+ &RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>,
+ > for payments_grpc::PaymentServiceAuthorizeRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<
+ ExternalVaultProxy,
+ ExternalVaultProxyPaymentsData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+
+ let payment_method = router_data
+ .request
+ .payment_method_type
+ .map(|payment_method_type| {
+ unified_connector_service::build_unified_connector_service_payment_method_for_external_proxy(
router_data.request.payment_method_data.clone(),
payment_method_type,
)
@@ -206,7 +333,7 @@ impl ForeignTryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsR
.request
.payment_method_type
.map(|payment_method_type| {
- build_unified_connector_service_payment_method(
+ unified_connector_service::build_unified_connector_service_payment_method(
router_data.request.payment_method_data.clone(),
payment_method_type,
)
@@ -306,6 +433,17 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon
router_data: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+ let browser_info = router_data
+ .request
+ .browser_info
+ .clone()
+ .map(payments_grpc::BrowserInformation::foreign_try_from)
+ .transpose()?;
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
let mandate_reference = match &router_data.request.mandate_id {
Some(mandate) => match &mandate.mandate_reference_id {
@@ -329,19 +467,6 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon
}
};
- let capture_method = router_data
- .request
- .capture_method
- .map(payments_grpc::CaptureMethod::foreign_try_from)
- .transpose()?;
-
- let browser_info = router_data
- .request
- .browser_info
- .clone()
- .map(payments_grpc::BrowserInformation::foreign_try_from)
- .transpose()?;
-
Ok(Self {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 01455e9e17..69be6c6e81 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -698,6 +698,10 @@ impl Payments {
web::resource("/proxy-confirm-intent")
.route(web::post().to(payments::proxy_confirm_intent)),
)
+ .service(
+ web::resource("/confirm-intent/external-vault-proxy")
+ .route(web::post().to(payments::confirm_intent_with_external_vault_proxy)),
+ )
.service(
web::resource("/get-intent")
.route(web::get().to(payments::payments_get_intent)),
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 72f184be72..1136e9f84a 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -3062,6 +3062,90 @@ pub async fn proxy_confirm_intent(
.await
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))]
+pub async fn confirm_intent_with_external_vault_proxy(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<api_models::payments::ExternalVaultProxyPaymentsRequest>,
+ path: web::Path<common_utils::id_type::GlobalPaymentId>,
+) -> impl Responder {
+ use hyperswitch_domain_models::payments::PaymentConfirmData;
+
+ let flow = Flow::ProxyConfirmIntent;
+
+ // Extract the payment ID from the path
+ let global_payment_id = path.into_inner();
+ tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
+
+ // Parse and validate headers
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => {
+ return api::log_and_return_error_response(err);
+ }
+ };
+
+ // Prepare the internal payload
+ let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
+ global_payment_id: global_payment_id.clone(),
+ payload: json_payload.into_inner(),
+ };
+
+ // Determine the locking action, if required
+ let locking_action = internal_payload.get_locking_input(flow.clone());
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ internal_payload,
+ |state, auth: auth::AuthenticationData, req, req_state| {
+ let payment_id = req.global_payment_id;
+ let request = req.payload;
+
+ // Define the operation for proxy payments intent
+ let operation = payments::operations::external_vault_proxy_payment_intent::ExternalVaultProxyPaymentIntent;
+
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
+ domain::Context(auth.merchant_account, auth.key_store),
+ ));
+ // Call the core proxy logic
+ Box::pin(payments::external_vault_proxy_for_payments_core::<
+ api_types::ExternalVaultProxy,
+ api_models::payments::PaymentsResponse,
+ _,
+ _,
+ _,
+ PaymentConfirmData<api_types::ExternalVaultProxy>,
+ >(
+ state,
+ req_state,
+ merchant_context,
+ auth.profile,
+ operation,
+ request,
+ payment_id,
+ payments::CallConnectorAction::Trigger,
+ header_payload.clone(),
+ None,
+ ))
+ },
+ auth::api_or_client_auth(
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
+ global_payment_id,
+ )),
+ req.headers(),
+ ),
+ locking_action,
+ ))
+ .await
+}
+
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payment_status(
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 005f41f91c..461fe03bb7 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1135,6 +1135,9 @@ impl Authenticate for api_models::payments::PaymentsConfirmIntentRequest {
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::ProxyPaymentsRequest {}
+#[cfg(feature = "v2")]
+impl Authenticate for api_models::payments::ExternalVaultProxyPaymentsRequest {}
+
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsRequest {
fn get_client_secret(&self) -> Option<&String> {
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index f735c0e586..3055a25406 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -37,9 +37,10 @@ use hyperswitch_domain_models::router_flow_types::{
mandate_revoke::MandateRevoke,
payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture,
- CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization,
- InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing,
- Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
+ CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExternalVaultProxy,
+ IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostProcessing,
+ PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate,
+ UpdateMetadata, Void,
},
refunds::{Execute, RSync},
webhooks::VerifyWebhookSource,
@@ -71,10 +72,11 @@ pub use hyperswitch_domain_models::{
AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions,
CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData,
CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund,
- DirectChargeRefund, DisputeSyncData, FetchDisputesRequestData, MandateRevokeRequestData,
- MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,
- PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
+ DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData,
+ FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData,
+ PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
+ PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData,
@@ -132,6 +134,8 @@ use crate::{
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
+pub type ExternalVaultProxyPaymentsRouterData =
+ RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
pub type PaymentsPostProcessingRouterData =
@@ -1143,6 +1147,17 @@ impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
}
}
+impl ForeignFrom<&ExternalVaultProxyPaymentsRouterData> for AuthorizeSessionTokenData {
+ fn foreign_from(data: &ExternalVaultProxyPaymentsRouterData) -> Self {
+ Self {
+ amount_to_capture: data.amount_captured,
+ currency: data.request.currency,
+ connector_transaction_id: data.payment_id.clone(),
+ amount: Some(data.request.amount),
+ }
+ }
+}
+
pub trait Tokenizable {
fn set_session_token(&mut self, token: Option<String>);
}
@@ -1161,6 +1176,12 @@ impl Tokenizable for CompleteAuthorizeData {
fn set_session_token(&mut self, _token: Option<String>) {}
}
+impl Tokenizable for ExternalVaultProxyPaymentsData {
+ fn set_session_token(&mut self, token: Option<String>) {
+ self.session_token = token;
+ }
+}
+
impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
fn foreign_from(data: &SetupMandateRouterData) -> Self {
Self {
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 057a2d7920..4b3f448de1 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -37,10 +37,10 @@ pub use common_types::payments::{AcceptanceType, CustomerAcceptance, OnlineManda
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
- CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, InitPayment, PSync,
- PaymentCreateIntent, PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent,
- PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, RecordAttempt, Reject,
- SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
+ CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization,
+ InitPayment, PSync, PaymentCreateIntent, PaymentGetIntent, PaymentMethodToken,
+ PaymentUpdateIntent, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing,
+ RecordAttempt, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,