Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payment_v2): implement payments sync (#6464)
Narayan Bhat42bdf47fd295
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.jsonindex 84562b9934..1f3408cbd8 100644--- a/api-reference-v2/openapi_spec.json+++ b/api-reference-v2/openapi_spec.json@@ -14314,6 +14314,7 @@"type": "object","required": ["id",+ "status","amount_details","client_secret","capture_method",@@ -14331,6 +14332,9 @@"type": "string","description": "Global Payment Id for the payment"},+ "status": {+ "$ref": "#/components/schemas/IntentStatus"+ },"amount_details": {"$ref": "#/components/schemas/AmountDetailsResponse"},@@ -15049,56 +15053,11 @@},"PaymentsRetrieveRequest": {"type": "object",- "required": [- "resource_id",- "force_sync"- ],+ "description": "Request for Payment Status","properties": {- "resource_id": {- "type": "string",- "description": "The type of ID (ex: payment intent id, payment attempt id or connector txn id)"- },- "merchant_id": {- "type": "string",- "description": "The identifier for the Merchant Account.",- "nullable": true- },"force_sync": {"type": "boolean",- "description": "Decider to enable or disable the connector call for retrieve request"- },- "param": {- "type": "string",- "description": "The parameters passed to a retrieve request",- "nullable": true- },- "connector": {- "type": "string",- "description": "The name of the connector",- "nullable": true- },- "merchant_connector_details": {- "allOf": [- {- "$ref": "#/components/schemas/MerchantConnectorDetailsWrap"- }- ],- "nullable": true- },- "client_secret": {- "type": "string",- "description": "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK",- "nullable": true- },- "expand_captures": {- "type": "boolean",- "description": "If enabled provides list of captures linked to latest attempt",- "nullable": true- },- "expand_attempts": {- "type": "boolean",- "description": "If enabled provides list of attempts linked to payment intent",- "nullable": true+ "description": "A boolean used to indicate if the payment status should be fetched from the connector\nIf this is set to true, the status will be fetched from the connector"}}},diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex ab09a05d0b..a3e36a232d 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -177,6 +177,15 @@ impl ApiEventMetric for PaymentsConfirmIntentResponse {}}+#[cfg(feature = "v2")]+impl ApiEventMetric for super::PaymentsRetrieveResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payment {+ payment_id: self.id.clone(),+ })+ }+}+#[cfg(feature = "v1")]impl ApiEventMetric for PaymentsResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 2494952e7d..567d601c45 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -304,6 +304,10 @@ pub struct PaymentsIntentResponse {#[schema(value_type = String)]pub id: id_type::GlobalPaymentId,+ /// The status of the payment+ #[schema(value_type = IntentStatus, example = "succeeded")]+ pub status: common_enums::IntentStatus,+/// The amount details for the paymentpub amount_details: AmountDetailsResponse,@@ -4484,6 +4488,19 @@ pub struct PaymentsConfirmIntentRequest {pub browser_info: Option<common_utils::types::BrowserInformation>,}+// Serialize is implemented because, this will be serialized in the api events.+// Usually request types should not have serialize implemented.+//+/// Request for Payment Status+#[cfg(feature = "v2")]+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]+pub struct PaymentsRetrieveRequest {+ /// A boolean used to indicate if the payment status should be fetched from the connector+ /// If this is set to true, the status will be fetched from the connector+ #[serde(default)]+ pub force_sync: bool,+}+/// Error details for the payment#[cfg(feature = "v2")]#[derive(Debug, serde::Serialize, ToSchema)]@@ -4568,6 +4585,72 @@ pub struct PaymentsConfirmIntentResponse {pub error: Option<ErrorDetails>,}+// TODO: have a separate response for detailed, summarized+/// Response for Payment Intent Confirm+#[cfg(feature = "v2")]+#[derive(Debug, serde::Serialize, ToSchema)]+pub struct PaymentsRetrieveResponse {+ /// Unique identifier for the payment. This ensures idempotency for multiple payments+ /// that have been done by a single merchant.+ #[schema(+ min_length = 32,+ max_length = 64,+ example = "12345_pay_01926c58bc6e77c09e809964e72af8c8",+ value_type = String,+ )]+ pub id: id_type::GlobalPaymentId,++ #[schema(value_type = IntentStatus, example = "succeeded")]+ pub status: api_enums::IntentStatus,++ /// Amount related information for this payment and attempt+ pub amount: ConfirmIntentAmountDetailsResponse,++ /// The connector used for the payment+ #[schema(example = "stripe")]+ pub connector: Option<String>,++ /// It's a token used for client side verification.+ #[schema(value_type = String)]+ pub client_secret: common_utils::types::ClientSecret,++ /// Time when the payment was created+ #[schema(example = "2022-09-10T10:11:12Z")]+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub created: PrimitiveDateTime,++ /// The payment method information provided for making a payment+ #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)]+ #[serde(serialize_with = "serialize_payment_method_data_response")]+ pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>,++ /// The payment method type for this payment attempt+ #[schema(value_type = Option<PaymentMethod>, example = "wallet")]+ pub payment_method_type: Option<api_enums::PaymentMethod>,++ #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")]+ pub payment_method_subtype: Option<api_enums::PaymentMethodType>,++ /// A unique identifier for a payment provided by the connector+ #[schema(value_type = Option<String>, example = "993672945374576J")]+ pub connector_transaction_id: Option<String>,++ /// reference(Identifier) to the payment at connector side+ #[schema(value_type = Option<String>, example = "993672945374576J")]+ pub connector_reference_id: Option<String>,++ /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment+ #[schema(value_type = Option<String>)]+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,++ /// The browser information used for this payment+ #[schema(value_type = Option<BrowserInformation>)]+ pub browser_info: Option<common_utils::types::BrowserInformation>,++ /// Error details for the payment if any+ pub error: Option<ErrorDetails>,+}+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]#[cfg(feature = "v2")]pub struct PaymentStartRedirectionRequest {@@ -5081,6 +5164,7 @@ pub struct PaymentsResponseForm {pub order_id: String,}+#[cfg(feature = "v1")]#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]pub struct PaymentsRetrieveRequest {/// The type of ID (ex: payment intent id, payment attempt id or connector txn id)diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 4d2e117a88..6ddc47e499 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -1297,6 +1297,28 @@ pub enum IntentStatus {PartiallyCapturedAndCapturable,}+impl IntentStatus {+ /// Indicates whether the syncing with the connector should be allowed or not+ pub fn should_force_sync_with_connector(&self) -> bool {+ match self {+ // Confirm has not happened yet+ Self::RequiresConfirmation+ | Self::RequiresPaymentMethod+ // Once the status is success, failed or cancelled need not force sync with the connector+ | Self::Succeeded+ | Self::Failed+ | Self::Cancelled+ | Self::PartiallyCaptured+ | Self::RequiresCapture => false,+ Self::Processing+ | Self::RequiresCustomerAction+ | Self::RequiresMerchantAction+ | Self::PartiallyCapturedAndCapturable+ => true,+ }+ }+}+/// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete./// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment/// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rsindex 4fba749ef6..77ff9e8e71 100644--- a/crates/common_enums/src/transformers.rs+++ b/crates/common_enums/src/transformers.rs@@ -2,7 +2,10 @@ use std::fmt::{Display, Formatter};use serde::{Deserialize, Serialize};-use crate::enums::{Country, CountryAlpha2, CountryAlpha3, PaymentMethod, PaymentMethodType};+use crate::enums::{+ AttemptStatus, Country, CountryAlpha2, CountryAlpha3, IntentStatus, PaymentMethod,+ PaymentMethodType,+};impl Display for NumericCountryCodeParseError {fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {@@ -2065,6 +2068,41 @@ impl super::PresenceOfCustomerDuringPayment {}}+impl From<AttemptStatus> for IntentStatus {+ fn from(s: AttemptStatus) -> Self {+ match s {+ AttemptStatus::Charged | AttemptStatus::AutoRefunded => Self::Succeeded,++ AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation,+ AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod,++ AttemptStatus::Authorized => Self::RequiresCapture,+ AttemptStatus::AuthenticationPending | AttemptStatus::DeviceDataCollectionPending => {+ Self::RequiresCustomerAction+ }+ AttemptStatus::Unresolved => Self::RequiresMerchantAction,++ AttemptStatus::PartialCharged => Self::PartiallyCaptured,+ AttemptStatus::PartialChargedAndChargeable => Self::PartiallyCapturedAndCapturable,+ AttemptStatus::Started+ | AttemptStatus::AuthenticationSuccessful+ | AttemptStatus::Authorizing+ | AttemptStatus::CodInitiated+ | AttemptStatus::VoidInitiated+ | AttemptStatus::CaptureInitiated+ | AttemptStatus::Pending => Self::Processing,++ AttemptStatus::AuthenticationFailed+ | AttemptStatus::AuthorizationFailed+ | AttemptStatus::VoidFailed+ | AttemptStatus::RouterDeclined+ | AttemptStatus::CaptureFailed+ | AttemptStatus::Failure => Self::Failed,+ AttemptStatus::Voided => Self::Cancelled,+ }+ }+}+#[cfg(test)]mod tests {#![allow(clippy::unwrap_used)]diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rsindex ce2be52598..ef7a4b847c 100644--- a/crates/common_utils/src/types.rs+++ b/crates/common_utils/src/types.rs@@ -627,6 +627,16 @@ impl Url {pub fn get_string_repr(&self) -> &str {self.0.as_str()}++ /// wrap the url::Url in Url type+ pub fn wrap(url: url::Url) -> Self {+ Self(url)+ }++ /// Get the inner url+ pub fn into_inner(self) -> url::Url {+ self.0+ }}impl<DB> ToSql<sql_types::Text, DB> for Urldiff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rsindex 0bfa1434f6..7c5c3a8de1 100644--- a/crates/diesel_models/src/kv.rs+++ b/crates/diesel_models/src/kv.rs@@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize};#[cfg(feature = "v2")]use crate::payment_attempt::PaymentAttemptUpdateInternal;+#[cfg(feature = "v2")]+use crate::payment_intent::PaymentIntentUpdateInternal;use crate::{address::{Address, AddressNew, AddressUpdateInternal},customers::{Customer, CustomerNew, CustomerUpdateInternal},@@ -108,9 +110,16 @@ impl DBOperation {Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)),},Self::Update { updatable } => match *updatable {+ #[cfg(feature = "v1")]Updateable::PaymentIntentUpdate(a) => {DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))}+ #[cfg(feature = "v2")]+ Updateable::PaymentIntentUpdate(a) => DBResult::PaymentIntent(Box::new(+ a.orig+ .update(conn, PaymentIntentUpdateInternal::from(a.update_data))+ .await?,+ )),#[cfg(feature = "v1")]Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(a.orig.update_with_attempt_id(conn, a.update_data).await?,diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex e233cfe390..32ffcb545f 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -65,7 +65,6 @@ pub struct PaymentAttempt {pub amount_capturable: MinorUnit,pub updated_by: String,pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,- pub authentication_data: Option<pii::SecretSerdeValue>,pub encoded_data: Option<masking::Secret<String>>,pub unified_code: Option<String>,pub unified_message: Option<String>,@@ -89,6 +88,7 @@ pub struct PaymentAttempt {pub external_reference_id: Option<String>,pub tax_on_surcharge: Option<MinorUnit>,pub payment_method_billing_address: Option<common_utils::encryption::Encryption>,+ pub redirection_data: Option<RedirectForm>,pub connector_payment_data: Option<String>,pub id: id_type::GlobalAttemptId,pub shipping_cost: Option<MinorUnit>,@@ -255,7 +255,7 @@ pub struct PaymentAttemptNew {pub amount_capturable: MinorUnit,pub updated_by: String,pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,- pub authentication_data: Option<pii::SecretSerdeValue>,+ pub redirection_data: Option<RedirectForm>,pub encoded_data: Option<masking::Secret<String>>,pub unified_code: Option<String>,pub unified_message: Option<String>,@@ -770,7 +770,7 @@ pub struct PaymentAttemptUpdateInternal {pub updated_by: String,pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,pub connector: Option<String>,- pub authentication_data: Option<pii::SecretSerdeValue>,+ pub redirection_data: Option<RedirectForm>,// encoded_data: Option<String>,pub unified_code: Option<Option<String>>,pub unified_message: Option<Option<String>>,@@ -3283,6 +3283,55 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {}}+#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, diesel::AsExpression)]+#[diesel(sql_type = diesel::sql_types::Jsonb)]+pub enum RedirectForm {+ Form {+ endpoint: String,+ method: common_utils::request::Method,+ form_fields: std::collections::HashMap<String, String>,+ },+ Html {+ html_data: String,+ },+ BlueSnap {+ payment_fields_token: String,+ },+ CybersourceAuthSetup {+ access_token: String,+ ddc_url: String,+ reference_id: String,+ },+ CybersourceConsumerAuth {+ access_token: String,+ step_up_url: String,+ },+ Payme,+ Braintree {+ client_token: String,+ card_token: String,+ bin: String,+ },+ Nmi {+ amount: String,+ currency: common_enums::Currency,+ public_key: masking::Secret<String>,+ customer_vault_id: String,+ order_id: String,+ },+ Mifinity {+ initialization_token: String,+ },+ WorldpayDDCForm {+ endpoint: common_utils::types::Url,+ method: common_utils::request::Method,+ form_fields: std::collections::HashMap<String, String>,+ collection_id: Option<String>,+ },+}++common_utils::impl_to_sql_from_sql_json!(RedirectForm);+mod tests {#[test]diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex 65fa044478..1824804811 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -207,7 +207,7 @@ impl TaxDetails {}/// Get the default tax amount- fn get_default_tax_amount(&self) -> Option<MinorUnit> {+ pub fn get_default_tax_amount(&self) -> Option<MinorUnit> {self.default.as_ref().map(|default_tax_details| default_tax_details.order_tax_amount)@@ -358,8 +358,8 @@ pub enum PaymentIntentUpdate {/// Update the payment intent details on payment intent confirmation, before calling the connectorConfirmIntent {status: storage_enums::IntentStatus,- updated_by: String,active_attempt_id: common_utils::id_type::GlobalAttemptId,+ updated_by: String,},/// Update the payment intent details on payment intent confirmation, after calling the connectorConfirmIntentPostUpdate {@@ -738,19 +738,19 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {match payment_intent_update {PaymentIntentUpdate::ConfirmIntent {status,- updated_by,active_attempt_id,+ updated_by,} => Self {status: Some(status),+ active_attempt_id: Some(active_attempt_id),modified_at: common_utils::date_time::now(),updated_by,- active_attempt_id: Some(active_attempt_id),},PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {status: Some(status),+ active_attempt_id: None,modified_at: common_utils::date_time::now(),updated_by,- active_attempt_id: None,},}}diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rsindex 7141675c88..b52e3e2d33 100644--- a/crates/diesel_models/src/query/payment_attempt.rs+++ b/crates/diesel_models/src/query/payment_attempt.rs@@ -204,7 +204,10 @@ impl PaymentAttempt {}#[cfg(feature = "v2")]- pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {+ pub async fn find_by_id(+ conn: &PgPooledConn,+ id: &common_utils::id_type::GlobalAttemptId,+ ) -> StorageResult<Self> {generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn,dsl::id.eq(id.to_owned()),diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rsindex fb23fc6010..4f4099eca0 100644--- a/crates/diesel_models/src/query/payment_intent.rs+++ b/crates/diesel_models/src/query/payment_intent.rs@@ -7,9 +7,7 @@ use crate::schema::payment_intent::dsl;use crate::schema_v2::payment_intent::dsl;use crate::{errors,- payment_intent::{- PaymentIntent, PaymentIntentNew, PaymentIntentUpdate, PaymentIntentUpdateInternal,- },+ payment_intent::{self, PaymentIntent, PaymentIntentNew},PgPooledConn, StorageResult,};@@ -24,12 +22,12 @@ impl PaymentIntent {pub async fn update(self,conn: &PgPooledConn,- payment_intent: PaymentIntentUpdate,+ payment_intent_update: payment_intent::PaymentIntentUpdateInternal,) -> StorageResult<Self> {match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(conn,self.id.to_owned(),- PaymentIntentUpdateInternal::from(payment_intent),+ payment_intent_update,).await{@@ -53,14 +51,14 @@ impl PaymentIntent {pub async fn update(self,conn: &PgPooledConn,- payment_intent: PaymentIntentUpdate,+ payment_intent: payment_intent::PaymentIntentUpdate,) -> StorageResult<Self> {match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(conn,dsl::payment_id.eq(self.payment_id.to_owned()).and(dsl::merchant_id.eq(self.merchant_id.to_owned())),- PaymentIntentUpdateInternal::from(payment_intent),+ payment_intent::PaymentIntentUpdateInternal::from(payment_intent),).await{diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 617d6cf182..3bd31f5cbf 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -776,7 +776,6 @@ diesel::table! {updated_by -> Varchar,#[max_length = 32]merchant_connector_id -> Nullable<Varchar>,- authentication_data -> Nullable<Json>,encoded_data -> Nullable<Text>,#[max_length = 255]unified_code -> Nullable<Varchar>,@@ -814,6 +813,7 @@ diesel::table! {external_reference_id -> Nullable<Varchar>,tax_on_surcharge -> Nullable<Int8>,payment_method_billing_address -> Nullable<Bytea>,+ redirection_data -> Nullable<Jsonb>,#[max_length = 512]connector_payment_data -> Nullable<Varchar>,#[max_length = 64]diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex ed2388488e..f0719ba358 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -13,6 +13,8 @@ use rustc_hash::FxHashMap;use serde_json::Value;use super::behaviour;+#[cfg(feature = "v2")]+use crate::router_data;use crate::type_encryption::{crypto_operation, CryptoOperation};#[cfg(feature = "v1")]@@ -87,6 +89,22 @@ impl MerchantConnectorAccount {pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {self.id.clone()}++ pub fn is_disabled(&self) -> bool {+ self.disabled.unwrap_or(false)+ }++ pub fn get_connector_account_details(+ &self,+ ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>+ {+ use common_utils::ext_traits::ValueExt;++ self.connector_account_details+ .get_inner()+ .clone()+ .parse_value("ConnectorAuthType")+ }}#[cfg(feature = "v1")]diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex c1c32e08f4..8b4c351daa 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -290,7 +290,7 @@ pub struct PaymentIntent {pub setup_future_usage: storage_enums::FutureUsage,/// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis.pub client_secret: common_utils::types::ClientSecret,- /// The active attempt id for the payment intent. This is the payment attempt that is currently active for the payment intent.+ /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent.pub active_attempt_id: Option<id_type::GlobalAttemptId>,/// The order details for the payment.pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>,@@ -541,3 +541,17 @@ wherepub payment_attempt: PaymentAttempt,pub payment_method_data: Option<payment_method_data::PaymentMethodData>,}++#[cfg(feature = "v2")]+#[derive(Clone)]+pub struct PaymentStatusData<F>+where+ F: Clone,+{+ pub flow: PhantomData<F>,+ pub payment_intent: PaymentIntent,+ pub payment_attempt: Option<PaymentAttempt>,+ /// Should the payment status be synced with connector+ /// This will depend on the payment status and the force sync flag in the request+ pub should_sync_with_connector: bool,+}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex a65abe1495..d6fdf9f14c 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -25,6 +25,8 @@ use time::PrimitiveDateTime;use super::PaymentIntent;#[cfg(feature = "v2")]use crate::merchant_key_store::MerchantKeyStore;+#[cfg(feature = "v2")]+use crate::router_response_types;use crate::{behaviour, errors,mandates::{MandateDataType, MandateDetails},@@ -122,7 +124,7 @@ pub trait PaymentAttemptInterface {&self,key_manager_state: &KeyManagerState,merchant_key_store: &MerchantKeyStore,- attempt_id: &str,+ attempt_id: &id_type::GlobalAttemptId,storage_scheme: storage_enums::MerchantStorageScheme,) -> error_stack::Result<PaymentAttempt, errors::StorageError>;@@ -261,7 +263,7 @@ pub struct PaymentAttempt {/// Whether the payment was updated by postgres or redispub updated_by: String,/// The authentication data which is used for external authentication- pub authentication_data: Option<pii::SecretSerdeValue>,+ pub redirection_data: Option<router_response_types::RedirectForm>,pub encoded_data: Option<Secret<String>>,pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,/// Whether external 3DS authentication was attempted for this payment.@@ -383,7 +385,7 @@ impl PaymentAttempt {multiple_capture_count: None,connector_response_reference_id: None,updated_by: storage_scheme.to_string(),- authentication_data: None,+ redirection_data: None,encoded_data: None,merchant_connector_id: None,external_three_ds_authentication_attempted: None,@@ -1280,7 +1282,6 @@ impl PaymentAttemptUpdate {}}-// TODO: Add fields as necessary#[cfg(feature = "v2")]#[derive(Debug, Clone, Serialize)]pub enum PaymentAttemptUpdate {@@ -1296,13 +1297,19 @@ pub enum PaymentAttemptUpdate {status: storage_enums::AttemptStatus,connector_payment_id: Option<String>,updated_by: String,- authentication_data: Option<pii::SecretSerdeValue>,+ redirection_data: Option<router_response_types::RedirectForm>,+ },+ /// Update the payment attempt after force syncing with the connector+ SyncUpdate {+ status: storage_enums::AttemptStatus,+ updated_by: String,},/// Update the payment attempt on confirming the intent, after calling the connector on error response- ConfirmIntentError {+ ErrorUpdate {status: storage_enums::AttemptStatus,error: ErrorDetails,updated_by: String,+ connector_payment_id: Option<String>,},}@@ -1614,7 +1621,7 @@ impl behaviour::Conversion for PaymentAttempt {multiple_capture_count,connector_response_reference_id,updated_by,- authentication_data,+ redirection_data,encoded_data,merchant_connector_id,external_three_ds_authentication_attempted,@@ -1683,7 +1690,7 @@ impl behaviour::Conversion for PaymentAttempt {amount_capturable,updated_by,merchant_connector_id,- authentication_data,+ redirection_data: redirection_data.map(From::from),encoded_data,unified_code: error.as_ref()@@ -1791,7 +1798,7 @@ impl behaviour::Conversion for PaymentAttempt {multiple_capture_count: storage_model.multiple_capture_count,connector_response_reference_id: storage_model.connector_response_reference_id,updated_by: storage_model.updated_by,- authentication_data: storage_model.authentication_data,+ redirection_data: storage_model.redirection_data.map(From::from),encoded_data: storage_model.encoded_data,merchant_connector_id: storage_model.merchant_connector_id,external_three_ds_authentication_attempted: storage_model@@ -1867,7 +1874,7 @@ impl behaviour::Conversion for PaymentAttempt {amount_capturable: self.amount_details.amount_capturable,updated_by: self.updated_by,merchant_connector_id: self.merchant_connector_id,- authentication_data: self.authentication_data,+ redirection_data: self.redirection_data.map(From::from),encoded_data: self.encoded_data,unified_code: error_details.as_ref()@@ -1924,11 +1931,12 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternalunified_message: None,connector_payment_id: None,connector: Some(connector),- authentication_data: None,+ redirection_data: None,},- PaymentAttemptUpdate::ConfirmIntentError {+ PaymentAttemptUpdate::ErrorUpdate {status,error,+ connector_payment_id,updated_by,} => Self {status: Some(status),@@ -1941,15 +1949,15 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternalmerchant_connector_id: None,unified_code: None,unified_message: None,- connector_payment_id: None,+ connector_payment_id,connector: None,- authentication_data: None,+ redirection_data: None,},PaymentAttemptUpdate::ConfirmIntentResponse {status,connector_payment_id,updated_by,- authentication_data,+ redirection_data,} => Self {status: Some(status),error_message: None,@@ -1963,7 +1971,23 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternalunified_message: None,connector_payment_id,connector: None,- authentication_data,+ redirection_data: redirection_data+ .map(diesel_models::payment_attempt::RedirectForm::from),+ },+ PaymentAttemptUpdate::SyncUpdate { status, updated_by } => Self {+ status: Some(status),+ error_message: None,+ error_code: None,+ modified_at: common_utils::date_time::now(),+ browser_info: None,+ error_reason: None,+ updated_by,+ merchant_connector_id: None,+ unified_code: None,+ unified_message: None,+ connector_payment_id: None,+ connector: None,+ redirection_data: None,},}}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex 4e3f861d76..4f2053ec6f 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -271,15 +271,22 @@ pub enum PaymentIntentUpdate {#[cfg(feature = "v2")]#[derive(Debug, Clone, Serialize)]pub enum PaymentIntentUpdate {+ /// PreUpdate tracker of ConfirmIntentConfirmIntent {status: storage_enums::IntentStatus,- updated_by: String,active_attempt_id: id_type::GlobalAttemptId,+ updated_by: String,},+ /// PostUpdate tracker of ConfirmIntentConfirmIntentPostUpdate {status: storage_enums::IntentStatus,updated_by: String,},+ /// SyncUpdate of ConfirmIntent in PostUpdateTrackers+ SyncUpdate {+ status: storage_enums::IntentStatus,+ updated_by: String,+ },}#[cfg(feature = "v2")]@@ -359,19 +366,50 @@ pub struct PaymentIntentUpdateInternal {pub tax_details: Option<diesel_models::TaxDetails>,}-// TODO: convert directly to diesel_models::PaymentIntentUpdateInternal+// This conversion is used in the `update_payment_intent` function#[cfg(feature = "v2")]-impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {+impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal {fn from(payment_intent_update: PaymentIntentUpdate) -> Self {match payment_intent_update {PaymentIntentUpdate::ConfirmIntent {status,- updated_by,active_attempt_id,+ updated_by,} => Self {status: Some(status),+ active_attempt_id: Some(active_attempt_id),+ modified_at: common_utils::date_time::now(),updated_by,+ },+ PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {+ status: Some(status),+ active_attempt_id: None,+ modified_at: common_utils::date_time::now(),+ updated_by,+ },+ PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self {+ status: Some(status),+ active_attempt_id: None,+ modified_at: common_utils::date_time::now(),+ updated_by,+ },+ }+ }+}++// This conversion is required for the `apply_changeset` function used for mockdb+#[cfg(feature = "v2")]+impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {+ fn from(payment_intent_update: PaymentIntentUpdate) -> Self {+ match payment_intent_update {+ PaymentIntentUpdate::ConfirmIntent {+ status,+ active_attempt_id,+ updated_by,+ } => Self {+ status: Some(status),active_attempt_id: Some(active_attempt_id),+ updated_by,..Default::default()},PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {@@ -379,6 +417,11 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {updated_by,..Default::default()},+ PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self {+ status: Some(status),+ updated_by,+ ..Default::default()+ },}}}@@ -584,25 +627,21 @@ use diesel_models::{PaymentIntentUpdate as DieselPaymentIntentUpdate,PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields,};-#[cfg(feature = "v2")]-impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {- fn from(value: PaymentIntentUpdate) -> Self {- match value {- PaymentIntentUpdate::ConfirmIntent {- status,- updated_by,- active_attempt_id,- } => Self::ConfirmIntent {- status,- updated_by,- active_attempt_id,- },- PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => {- Self::ConfirmIntentPostUpdate { status, updated_by }- }- }- }-}++// TODO: check where this conversion is used+// #[cfg(feature = "v2")]+// impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {+// fn from(value: PaymentIntentUpdate) -> Self {+// match value {+// PaymentIntentUpdate::ConfirmIntent { status, updated_by } => {+// Self::ConfirmIntent { status, updated_by }+// }+// PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => {+// Self::ConfirmIntentPostUpdate { status, updated_by }+// }+// }+// }+// }#[cfg(feature = "v1")]impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rsindex 96a2a57a4b..f995c9a1e5 100644--- a/crates/hyperswitch_domain_models/src/router_data.rs+++ b/crates/hyperswitch_domain_models/src/router_data.rs@@ -389,3 +389,257 @@ impl ErrorResponse {}}}++#[cfg(feature = "v2")]+use crate::{+ payments::{+ payment_attempt::{ErrorDetails, PaymentAttemptUpdate},+ payment_intent::PaymentIntentUpdate,+ },+ router_flow_types, router_request_types, router_response_types,+};++/// Get updatable trakcer objects of payment intent and payment attempt+#[cfg(feature = "v2")]+pub trait TrackerPostUpdateObjects<Flow, FlowRequest> {+ fn get_payment_intent_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentIntentUpdate;+ fn get_payment_attempt_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentAttemptUpdate;+}++#[cfg(feature = "v2")]+impl+ TrackerPostUpdateObjects<+ router_flow_types::Authorize,+ router_request_types::PaymentsAuthorizeData,+ >+ for RouterData<+ router_flow_types::Authorize,+ router_request_types::PaymentsAuthorizeData,+ router_response_types::PaymentsResponseData,+ >+{+ fn get_payment_intent_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentIntentUpdate {+ match self.response {+ Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {+ status: common_enums::IntentStatus::from(self.status),+ updated_by: storage_scheme.to_string(),+ },+ Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {+ status: error+ .attempt_status+ .map(common_enums::IntentStatus::from)+ .unwrap_or(common_enums::IntentStatus::Failed),+ updated_by: storage_scheme.to_string(),+ },+ }+ }++ fn get_payment_attempt_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentAttemptUpdate {+ match self.response {+ Ok(ref response_router_data) => match response_router_data {+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charge_id,+ } => {+ let attempt_status = self.status;+ 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 {+ status: attempt_status,+ connector_payment_id,+ updated_by: storage_scheme.to_string(),+ redirection_data: *redirection_data.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::SessionUpdateResponse { .. } => {+ todo!()+ }+ },+ Err(ref error_response) => {+ let ErrorResponse {+ code,+ message,+ reason,+ status_code: _,+ attempt_status,+ connector_transaction_id,+ } = error_response.clone();+ let attempt_status = attempt_status.unwrap_or(self.status);++ let error_details = ErrorDetails {+ code,+ message,+ reason,+ unified_code: None,+ unified_message: None,+ };++ PaymentAttemptUpdate::ErrorUpdate {+ status: attempt_status,+ error: error_details,+ connector_payment_id: connector_transaction_id,+ updated_by: storage_scheme.to_string(),+ }+ }+ }+ }+}++#[cfg(feature = "v2")]+impl TrackerPostUpdateObjects<router_flow_types::PSync, router_request_types::PaymentsSyncData>+ for RouterData<+ router_flow_types::PSync,+ router_request_types::PaymentsSyncData,+ router_response_types::PaymentsResponseData,+ >+{+ fn get_payment_intent_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentIntentUpdate {+ match self.response {+ Ok(ref _response) => PaymentIntentUpdate::SyncUpdate {+ status: common_enums::IntentStatus::from(self.status),+ updated_by: storage_scheme.to_string(),+ },+ Err(ref error) => PaymentIntentUpdate::SyncUpdate {+ status: error+ .attempt_status+ .map(common_enums::IntentStatus::from)+ .unwrap_or(common_enums::IntentStatus::Failed),+ updated_by: storage_scheme.to_string(),+ },+ }+ }++ fn get_payment_attempt_update(+ &self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> PaymentAttemptUpdate {+ match self.response {+ Ok(ref response_router_data) => match response_router_data {+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charge_id,+ } => {+ let attempt_status = self.status;+ 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::SyncUpdate {+ status: attempt_status,+ updated_by: storage_scheme.to_string(),+ }+ }+ 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::SessionUpdateResponse { .. } => {+ todo!()+ }+ },+ Err(ref error_response) => {+ let ErrorResponse {+ code,+ message,+ reason,+ status_code: _,+ attempt_status,+ connector_transaction_id,+ } = error_response.clone();+ let attempt_status = attempt_status.unwrap_or(self.status);++ let error_details = ErrorDetails {+ code,+ message,+ reason,+ unified_code: None,+ unified_message: None,+ };++ PaymentAttemptUpdate::ErrorUpdate {+ status: attempt_status,+ error: error_details,+ connector_payment_id: connector_transaction_id,+ updated_by: storage_scheme.to_string(),+ }+ }+ }+ }+}diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rsindex e6af5c5eb3..4501582d00 100644--- a/crates/hyperswitch_domain_models/src/router_response_types.rs+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs@@ -191,6 +191,162 @@ impl From<(url::Url, Method)> for RedirectForm {}}+impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm {+ fn from(redirect_form: RedirectForm) -> Self {+ match redirect_form {+ RedirectForm::Form {+ endpoint,+ method,+ form_fields,+ } => Self::Form {+ endpoint,+ method,+ form_fields,+ },+ RedirectForm::Html { html_data } => Self::Html { html_data },+ RedirectForm::BlueSnap {+ payment_fields_token,+ } => Self::BlueSnap {+ payment_fields_token,+ },+ RedirectForm::CybersourceAuthSetup {+ access_token,+ ddc_url,+ reference_id,+ } => Self::CybersourceAuthSetup {+ access_token,+ ddc_url,+ reference_id,+ },+ RedirectForm::CybersourceConsumerAuth {+ access_token,+ step_up_url,+ } => Self::CybersourceConsumerAuth {+ access_token,+ step_up_url,+ },+ RedirectForm::Payme => Self::Payme,+ RedirectForm::Braintree {+ client_token,+ card_token,+ bin,+ } => Self::Braintree {+ client_token,+ card_token,+ bin,+ },+ RedirectForm::Nmi {+ amount,+ currency,+ public_key,+ customer_vault_id,+ order_id,+ } => Self::Nmi {+ amount,+ currency,+ public_key,+ customer_vault_id,+ order_id,+ },+ RedirectForm::Mifinity {+ initialization_token,+ } => Self::Mifinity {+ initialization_token,+ },+ RedirectForm::WorldpayDDCForm {+ endpoint,+ method,+ form_fields,+ collection_id,+ } => Self::WorldpayDDCForm {+ endpoint: common_utils::types::Url::wrap(endpoint),+ method,+ form_fields,+ collection_id,+ },+ }+ }+}++impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm {+ fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self {+ match redirect_form {+ diesel_models::payment_attempt::RedirectForm::Form {+ endpoint,+ method,+ form_fields,+ } => Self::Form {+ endpoint,+ method,+ form_fields,+ },+ diesel_models::payment_attempt::RedirectForm::Html { html_data } => {+ Self::Html { html_data }+ }+ diesel_models::payment_attempt::RedirectForm::BlueSnap {+ payment_fields_token,+ } => Self::BlueSnap {+ payment_fields_token,+ },+ diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup {+ access_token,+ ddc_url,+ reference_id,+ } => Self::CybersourceAuthSetup {+ access_token,+ ddc_url,+ reference_id,+ },+ diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth {+ access_token,+ step_up_url,+ } => Self::CybersourceConsumerAuth {+ access_token,+ step_up_url,+ },+ diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme,+ diesel_models::payment_attempt::RedirectForm::Braintree {+ client_token,+ card_token,+ bin,+ } => Self::Braintree {+ client_token,+ card_token,+ bin,+ },+ diesel_models::payment_attempt::RedirectForm::Nmi {+ amount,+ currency,+ public_key,+ customer_vault_id,+ order_id,+ } => Self::Nmi {+ amount,+ currency,+ public_key,+ customer_vault_id,+ order_id,+ },+ diesel_models::payment_attempt::RedirectForm::Mifinity {+ initialization_token,+ } => Self::Mifinity {+ initialization_token,+ },+ diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm {+ endpoint,+ method,+ form_fields,+ collection_id,+ } => Self::WorldpayDDCForm {+ endpoint: endpoint.into_inner(),+ method,+ form_fields,+ collection_id,+ },+ }+ }+}+#[derive(Default, Clone, Debug)]pub struct UploadFileResponse {pub provider_file_id: String,diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rsindex e447e9b953..5bbb4e7cf2 100644--- a/crates/router/src/compatibility/stripe/payment_intents.rs+++ b/crates/router/src/compatibility/stripe/payment_intents.rs@@ -100,7 +100,7 @@ pub async fn payment_intents_create(.await}-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]pub async fn payment_intents_retrieve(state: web::Data<routes::AppState>,diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rsindex 66b43e4ebe..919ced993a 100644--- a/crates/router/src/compatibility/stripe/setup_intents.rs+++ b/crates/router/src/compatibility/stripe/setup_intents.rs@@ -86,7 +86,7 @@ pub async fn setup_intents_create(.await}-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]pub async fn setup_intents_retrieve(state: web::Data<routes::AppState>,diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rsindex e1e5dc9f62..01cc6a8956 100644--- a/crates/router/src/core/authentication/utils.rs+++ b/crates/router/src/core/authentication/utils.rs@@ -17,6 +17,7 @@ use crate::{utils::OptionExt,};+#[cfg(feature = "v1")]pub fn get_connector_data_if_separate_authn_supported(connector_call_type: &api::ConnectorCallType,) -> Option<api::ConnectorData> {diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rsindex 4249559aab..af59c6c421 100644--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs@@ -36,7 +36,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC_merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rsindex 3ef2b92320..6bf5688104 100644--- a/crates/router/src/core/fraud_check/flows/record_return.rs+++ b/crates/router/src/core/fraud_check/flows/record_return.rs@@ -34,7 +34,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh_merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rsindex 0917ee87cc..bde91b3bda 100644--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs@@ -32,7 +32,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp_merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rsindex f7907066f7..62d242d0e6 100644--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs@@ -37,7 +37,7 @@ impl_merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 61572763af..23cb25a52d 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -36,7 +36,9 @@ use events::EventInfo;use futures::future::join_all;use helpers::{decrypt_paze_token, ApplePayData};#[cfg(feature = "v2")]-use hyperswitch_domain_models::payments::{PaymentConfirmData, PaymentIntentData};+use hyperswitch_domain_models::payments::{+ PaymentConfirmData, PaymentIntentData, PaymentStatusData,+};#[cfg(feature = "v2")]use hyperswitch_domain_models::router_response_types::RedirectForm;pub use hyperswitch_domain_models::{@@ -139,16 +141,21 @@ wheredyn api::Connector:services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,+ RouterData<F, FData, router_types::PaymentsResponseData>:+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData>,+// To perform router related operation for PaymentResponsePaymentResponse: Operation<F, FData, Data = D>,FData: Send + Sync + Clone,{let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);+ // Validate the request fieldslet (operation, validate_result) = operation.to_validate_request()?.validate_request(&req, &merchant_account)?;+ // Get the trackers related to track the state of the paymentlet operations::GetTrackerResponse {operation,mut payment_data,@@ -177,68 +184,57 @@ where.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound).attach_printable("Failed while fetching/creating customer")?;- let connector = get_connector_choice(- &operation,- state,- &req,- &merchant_account,- &profile,- &key_store,- &mut payment_data,- None,- None,- )- .await?;+ let connector = operation+ .to_domain()?+ .perform_routing(+ &merchant_account,+ &profile,+ state,+ &mut payment_data,+ &key_store,+ )+ .await?;++ let payment_data = match connector {+ ConnectorCallType::PreDetermined(connector_data) => {+ let router_data = call_connector_service(+ state,+ req_state.clone(),+ &merchant_account,+ &key_store,+ connector_data.clone(),+ &operation,+ &mut payment_data,+ &customer,+ call_connector_action.clone(),+ &validate_result,+ None,+ header_payload.clone(),+ #[cfg(feature = "frm")]+ None,+ #[cfg(not(feature = "frm"))]+ None,+ &profile,+ false,+ )+ .await?;++ let payments_response_operation = Box::new(PaymentResponse);- // TODO: do not use if let- let payment_data = if let Some(connector_call_type) = connector {- match connector_call_type {- ConnectorCallType::PreDetermined(connector_data) => {- let (router_data, mca) = call_connector_service(+ payments_response_operation+ .to_post_update_tracker()?+ .update_tracker(state,- req_state.clone(),- &merchant_account,+ payment_data,+ router_data,&key_store,- connector_data.clone(),- &operation,- &mut payment_data,- &customer,- call_connector_action.clone(),- &validate_result,- None,- header_payload.clone(),- #[cfg(feature = "frm")]- None,- #[cfg(not(feature = "frm"))]- None,- &profile,- false,+ merchant_account.storage_scheme,)- .await?;-- let payments_response_operation = Box::new(PaymentResponse);-- payments_response_operation- .to_post_update_tracker()?- .update_tracker(- state,- payment_data,- router_data,- &key_store,- merchant_account.storage_scheme,- &header_payload.locale,- #[cfg(all(feature = "dynamic_routing", feature = "v1"))]- routable_connectors,- #[cfg(all(feature = "dynamic_routing", feature = "v1"))]- &business_profile,- )- .await?- }- ConnectorCallType::Retryable(vec) => todo!(),- ConnectorCallType::SessionMultiple(vec) => todo!(),+ .await?}- } else {- todo!()+ ConnectorCallType::Retryable(vec) => todo!(),+ ConnectorCallType::SessionMultiple(vec) => todo!(),+ ConnectorCallType::Skip => payment_data,};Ok((payment_data, req, customer, None, None))@@ -1519,6 +1515,10 @@ where// To perform router related operation for PaymentResponsePaymentResponse: Operation<F, FData, Data = D>,++ // To create updatable objects in post update tracker+ RouterData<F, FData, router_types::PaymentsResponseData>:+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData>,{let (payment_data, _req, customer, connector_http_status_code, external_latency) =payments_operation_core::<_, _, _, _, _>(@@ -2143,6 +2143,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {}}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(@@ -2190,6 +2191,7 @@ where).await?;+ #[cfg(feature = "v1")]if payment_data.get_payment_attempt().merchant_connector_id@@ -2394,6 +2396,144 @@ whereOk((router_data, merchant_connector_account))}+#[cfg(feature = "v2")]+#[allow(clippy::too_many_arguments)]+#[instrument(skip_all)]+pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(+ state: &SessionState,+ req_state: ReqState,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ connector: api::ConnectorData,+ operation: &BoxedOperation<'_, F, ApiRequest, D>,+ payment_data: &mut D,+ customer: &Option<domain::Customer>,+ call_connector_action: CallConnectorAction,+ validate_result: &operations::ValidateResult,+ schedule_time: Option<time::PrimitiveDateTime>,+ header_payload: HeaderPayload,+ frm_suggestion: Option<storage_enums::FrmSuggestion>,+ business_profile: &domain::Profile,+ is_retry_payment: 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_id = connector+ .merchant_connector_id+ .as_ref()+ .get_required_value("merchant_connector_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("connector id is not set")?;++ let merchant_connector_account = state+ .store+ .find_merchant_connector_account_by_id(&state.into(), merchant_connector_id, key_store)+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_owned(),+ })?;++ let mut router_data = payment_data+ .construct_router_data(+ state,+ connector.connector.id(),+ merchant_account,+ key_store,+ customer,+ &merchant_connector_account,+ None,+ None,+ )+ .await?;++ let add_access_token_result = router_data+ .add_access_token(+ state,+ &connector,+ merchant_account,+ payment_data.get_creds_identifier(),+ )+ .await?;++ router_data = router_data.add_session_token(state, &connector).await?;++ let should_continue_further = access_token::update_router_data_with_access_token_result(+ &add_access_token_result,+ &mut router_data,+ &call_connector_action,+ );++ // In case of authorize flow, pre-task and post-tasks are being called in build request+ // if we do not want to proceed further, then the function will return Ok(None, false)+ let (connector_request, should_continue_further) = if should_continue_further {+ // Check if the actual flow specific request can be built with available data+ router_data+ .build_flow_specific_connector_request(state, &connector, call_connector_action.clone())+ .await?+ } else {+ (None, false)+ };++ // Update the payment trackers just before calling the connector+ // Since the request is already built in the previous step,+ // there should be no error in request construction from hyperswitch end+ (_, *payment_data) = operation+ .to_update_tracker()?+ .update_trackers(+ state,+ req_state,+ payment_data.clone(),+ customer.clone(),+ merchant_account.storage_scheme,+ // TODO: update the customer with connector customer id+ None,+ key_store,+ frm_suggestion,+ header_payload.clone(),+ )+ .await?;++ let router_data = if should_continue_further {+ // The status of payment_attempt and intent will be updated in the previous step+ // update this in router_data.+ // This is added because few connector integrations do not update the status,+ // and rely on previous status set in router_data+ // TODO: status is already set when constructing payment data, why should this be done again?+ // router_data.status = payment_data.get_payment_attempt().status;+ router_data+ .decide_flows(+ state,+ &connector,+ call_connector_action,+ connector_request,+ business_profile,+ header_payload.clone(),+ )+ .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)+}++#[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)]#[instrument(skip_all)]@@ -2718,7 +2858,7 @@ whereF: Send + Clone + Sync,D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,{- let merchant_id = &payment_data.get_payment_attempt().merchant_id;+ let merchant_id = merchant_account.get_id();let blocklist_enabled_key = merchant_id.get_blocklist_guard_key();let blocklist_guard_enabled = state.store@@ -2747,6 +2887,7 @@ where}}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]pub async fn call_multiple_connectors_service<F, Op, Req, D>(state: &SessionState,@@ -2872,6 +3013,7 @@ whereOk(payment_data)}+#[cfg(feature = "v1")]pub async fn call_create_connector_customer_if_required<F, Req, D>(state: &SessionState,customer: &Option<domain::Customer>,@@ -3137,6 +3279,7 @@ whereOk(router_data_and_should_continue_payment)}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>(state: &SessionState,@@ -3869,6 +4012,7 @@ where}}+#[cfg(feature = "v1")]pub fn should_call_connector<Op: Debug, F: Clone, D>(operation: &Op, payment_data: &D) -> boolwhereD: OperationSessionGetters<F> + Send + Sync + Clone,@@ -4317,53 +4461,6 @@ whereOk(())}-#[cfg(feature = "v2")]-#[allow(clippy::too_many_arguments)]-pub async fn get_connector_choice<F, Req, D>(- operation: &BoxedOperation<'_, F, Req, D>,- state: &SessionState,- req: &Req,- merchant_account: &domain::MerchantAccount,- business_profile: &domain::Profile,- key_store: &domain::MerchantKeyStore,- payment_data: &mut D,- eligible_connectors: Option<Vec<enums::RoutableConnectors>>,- mandate_type: Option<api::MandateTransactionType>,-) -> RouterResult<Option<ConnectorCallType>>-where- F: Send + Clone,- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,-{- // Currently rule based routing and other routing features are not implemented for v2- // So we are using the default fallback connector for now- // Eligibility analysis is not yet implemented-- let fallback_config = super::admin::ProfileWrapper::new(business_profile.clone())- .get_default_fallback_list_of_connector_under_profile()- .change_context(errors::RoutingError::FallbackConfigFetchFailed)- .change_context(errors::ApiErrorResponse::InternalServerError)?;-- let first_chosen_connector = fallback_config- .first()- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;-- let connector_name = first_chosen_connector.connector.to_string();- let merchant_connector_id = first_chosen_connector- .merchant_connector_id- .clone()- .get_required_value("merchant_connector_id")?;-- payment_data.set_connector_in_payment_attempt(Some(connector_name.to_string()));- let connector_data = api::ConnectorData::get_connector_by_name(- &state.conf.connectors,- &connector_name,- api::GetToken::Connector,- Some(merchant_connector_id),- )?;-- Ok(Some(ConnectorCallType::PreDetermined(connector_data)))-}-#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]pub async fn get_connector_choice<F, Req, D>(@@ -6012,29 +6109,23 @@ pub async fn payment_start_redirection(&key_store,payment_intent.active_attempt_id- .clone()+ .as_ref().ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("missing active attempt in payment_intent")?- .get_string_repr(),+ .attach_printable("missing active attempt in payment_intent")?,storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Error while fetching payment_attempt")?;let redirection_data = payment_attempt- .authentication_data+ .redirection_data.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_data in payment_attempt")?;- let form: RedirectForm = serde_json::from_value(redirection_data.expose()).map_err(|err| {- logger::error!(error = ?err, "Failed to deserialize redirection data");- errors::ApiErrorResponse::InternalServerError- })?;-Ok(services::ApplicationResponse::Form(Box::new(services::RedirectionFormData {- redirect_form: form,+ redirect_form: redirection_data,payment_method_data: None,amount: payment_attempt.amount_details.net_amount.to_string(),currency: payment_intent.amount_details.currency.to_string(),@@ -6263,6 +6354,9 @@ pub trait OperationSessionGetters<F> {fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>;fn get_force_sync(&self) -> Option<bool>;fn get_capture_method(&self) -> Option<enums::CaptureMethod>;++ #[cfg(feature = "v2")]+ fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>;}pub trait OperationSessionSetters<F> {@@ -6440,6 +6534,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {fn get_capture_method(&self) -> Option<enums::CaptureMethod> {Some(self.payment_intent.capture_method)}++ #[cfg(feature = "v2")]+ fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {+ todo!();+ }}#[cfg(feature = "v1")]@@ -6671,6 +6770,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> {fn get_capture_method(&self) -> Option<enums::CaptureMethod> {todo!()}++ #[cfg(feature = "v2")]+ fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {+ todo!();+ }}#[cfg(feature = "v2")]@@ -6880,6 +6984,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> {fn get_capture_method(&self) -> Option<enums::CaptureMethod> {todo!()}++ #[cfg(feature = "v2")]+ fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {+ todo!();+ }}#[cfg(feature = "v2")]@@ -6967,3 +7076,218 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {self.payment_attempt.connector = connector;}}++#[cfg(feature = "v2")]+impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> {+ #[track_caller]+ fn get_payment_attempt(&self) -> &storage::PaymentAttempt {+ todo!()+ }++ fn get_payment_intent(&self) -> &storage::PaymentIntent {+ &self.payment_intent+ }++ fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {+ todo!()+ }++ fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {+ todo!()+ }++ // what is this address find out and not required remove this+ fn get_address(&self) -> &PaymentAddress {+ todo!()+ }++ fn get_creds_identifier(&self) -> Option<&str> {+ None+ }++ fn get_token(&self) -> Option<&str> {+ todo!()+ }++ fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {+ todo!()+ }++ fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {+ todo!()+ }++ fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {+ todo!()+ }++ fn get_setup_mandate(&self) -> Option<&MandateData> {+ todo!()+ }++ fn get_poll_config(&self) -> Option<router_types::PollConfig> {+ todo!()+ }++ fn get_authentication(&self) -> Option<&storage::Authentication> {+ todo!()+ }++ fn get_frm_message(&self) -> Option<FraudCheck> {+ todo!()+ }++ fn get_refunds(&self) -> Vec<storage::Refund> {+ todo!()+ }++ fn get_disputes(&self) -> Vec<storage::Dispute> {+ todo!()+ }++ fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {+ todo!()+ }++ fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {+ todo!()+ }++ fn get_recurring_details(&self) -> Option<&RecurringDetails> {+ todo!()+ }++ fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {+ Some(&self.payment_intent.profile_id)+ }++ fn get_currency(&self) -> storage_enums::Currency {+ self.payment_intent.amount_details.currency+ }++ fn get_amount(&self) -> api::Amount {+ todo!()+ }++ fn get_payment_attempt_connector(&self) -> Option<&str> {+ todo!()+ }++ fn get_billing_address(&self) -> Option<api_models::payments::Address> {+ todo!()+ }++ fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {+ todo!()+ }++ fn get_sessions_token(&self) -> Vec<api::SessionToken> {+ todo!()+ }++ fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {+ todo!()+ }++ fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {+ todo!()+ }++ fn get_force_sync(&self) -> Option<bool> {+ todo!()+ }++ fn get_capture_method(&self) -> Option<enums::CaptureMethod> {+ todo!()+ }++ #[cfg(feature = "v2")]+ fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {+ self.payment_attempt.as_ref()+ }+}++#[cfg(feature = "v2")]+impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {+ fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {+ self.payment_intent = payment_intent;+ }++ fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {+ self.payment_attempt = Some(payment_attempt);+ }++ fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {+ todo!()+ }++ fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {+ todo!()+ }++ fn set_email_if_not_present(&mut self, _email: pii::Email) {+ todo!()+ }++ fn set_pm_token(&mut self, _token: String) {+ todo!()+ }++ fn set_connector_customer_id(&mut self, _customer_id: Option<String>) {+ // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData?+ }++ fn push_sessions_token(&mut self, _token: api::SessionToken) {+ todo!()+ }++ fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {+ todo!()+ }++ #[track_caller]+ fn set_merchant_connector_id_in_attempt(+ &mut self,+ merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,+ ) {+ todo!()+ }++ fn set_frm_message(&mut self, _frm_message: FraudCheck) {+ todo!()+ }++ fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {+ self.payment_intent.status = status;+ }++ fn set_authentication_type_in_attempt(+ &mut self,+ _authentication_type: Option<enums::AuthenticationType>,+ ) {+ todo!()+ }++ fn set_recurring_mandate_payment_data(+ &mut self,+ _recurring_mandate_payment_data:+ hyperswitch_domain_models::router_data::RecurringMandatePaymentData,+ ) {+ todo!()+ }++ fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {+ todo!()+ }++ fn set_setup_future_usage_in_payment_intent(+ &mut self,+ setup_future_usage: storage_enums::FutureUsage,+ ) {+ self.payment_intent.setup_future_usage = setup_future_usage;+ }++ fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) {+ todo!()+ }+}diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex 3fed81a890..7eec775d23 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -29,7 +29,7 @@ use crate::{#[async_trait]#[allow(clippy::too_many_arguments)]pub trait ConstructFlowSpecificData<F, Req, Res> {- #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -42,7 +42,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<types::RouterData<F, Req, Res>>;- #[cfg(all(feature = "v2", feature = "customer_v2"))]+ #[cfg(feature = "v2")]async fn construct_router_data<'a>(&self,_state: &SessionState,@@ -50,7 +50,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {_merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,_customer: &Option<domain::Customer>,- _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<types::MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<types::RouterData<F, Req, Res>>;diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rsindex 98d204d526..c35f096fbd 100644--- a/crates/router/src/core/payments/flows/approve_flow.rs+++ b/crates/router/src/core/payments/flows/approve_flow.rs@@ -16,6 +16,22 @@ implConstructFlowSpecificData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>for PaymentData<api::Approve>{+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsApproveRouterData> {+ todo!()+ }++ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 09a6fb5192..bc62408205 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -38,7 +38,7 @@ implmerchant_account: &domain::MerchantAccount,key_store: &domain::MerchantKeyStore,customer: &Option<domain::Customer>,- merchant_connector_account: &helpers::MerchantConnectorAccountType,+ merchant_connector_account: &domain::MerchantConnectorAccount,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rsindex 9c5bc84a62..e9c3f63c79 100644--- a/crates/router/src/core/payments/flows/cancel_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_flow.rs@@ -16,6 +16,22 @@ use crate::{impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>for PaymentData<api::Void>{+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ _state: &SessionState,+ _connector_id: &str,+ _merchant_account: &domain::MerchantAccount,+ _key_store: &domain::MerchantKeyStore,+ _customer: &Option<domain::Customer>,+ _merchant_connector_account: &domain::MerchantConnectorAccount,+ _merchant_recipient_data: Option<types::MerchantRecipientData>,+ _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsCancelRouterData> {+ todo!()+ }++ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rsindex aaa245a341..8b6fa24fbf 100644--- a/crates/router/src/core/payments/flows/capture_flow.rs+++ b/crates/router/src/core/payments/flows/capture_flow.rs@@ -16,6 +16,7 @@ implConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>for PaymentData<api::Capture>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -44,6 +45,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsCaptureRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 24f6d8d075..f3cfb45f18 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -20,6 +20,7 @@ impltypes::PaymentsResponseData,> for PaymentData<api::CompleteAuthorize>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -54,6 +55,27 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<+ types::RouterData<+ api::CompleteAuthorize,+ types::CompleteAuthorizeData,+ types::PaymentsResponseData,+ >,+ > {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rsindex a187146903..982fbc4c99 100644--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs@@ -19,6 +19,7 @@ impltypes::PaymentsResponseData,> for PaymentData<api::IncrementalAuthorization>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -47,6 +48,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rsindex 13738480c9..deb876660e 100644--- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs+++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs@@ -19,6 +19,7 @@ impltypes::PaymentsResponseData,> for PaymentData<api::PostSessionTokens>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -47,6 +48,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rsindex 34ebfdf4ba..d468514da8 100644--- a/crates/router/src/core/payments/flows/psync_flow.rs+++ b/crates/router/src/core/payments/flows/psync_flow.rs@@ -13,6 +13,8 @@ use crate::{services::{self, api::ConnectorValidation, logger},types::{self, api, domain},};++#[cfg(feature = "v1")]#[async_trait]impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>for PaymentData<api::PSync>@@ -59,6 +61,50 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme}}+#[cfg(feature = "v2")]+#[async_trait]+impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>+ for hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>+{+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<+ types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,+ > {+ Box::pin(transformers::construct_router_data_for_psync(+ state,+ self.clone(),+ connector_id,+ merchant_account,+ key_store,+ customer,+ merchant_connector_account,+ merchant_recipient_data,+ header_payload,+ ))+ .await+ }++ async fn get_merchant_recipient_data<'a>(+ &self,+ _state: &SessionState,+ _merchant_account: &domain::MerchantAccount,+ _key_store: &domain::MerchantKeyStore,+ _merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _connector: &api::ConnectorData,+ ) -> RouterResult<Option<types::MerchantRecipientData>> {+ Ok(None)+ }+}+#[async_trait]impl Feature<api::PSync, types::PaymentsSyncData>for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rsindex 43163c1374..66337a49e7 100644--- a/crates/router/src/core/payments/flows/reject_flow.rs+++ b/crates/router/src/core/payments/flows/reject_flow.rs@@ -15,6 +15,7 @@ use crate::{impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>for PaymentData<api::Reject>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -43,6 +44,21 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsRejectRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex 545d05e776..43f855182e 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -31,6 +31,7 @@ implConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>for PaymentData<api::Session>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &routes::SessionState,@@ -59,6 +60,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &routes::SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::PaymentsSessionRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &routes::SessionState,diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rsindex e48f90d1bb..8f4457b36f 100644--- a/crates/router/src/core/payments/flows/session_update_flow.rs+++ b/crates/router/src/core/payments/flows/session_update_flow.rs@@ -19,6 +19,7 @@ impltypes::PaymentsResponseData,> for PaymentData<api::SdkSessionUpdate>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -47,6 +48,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ _merchant_recipient_data: Option<types::MerchantRecipientData>,+ _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::SdkSessionUpdateRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex 2cee81115d..ee8ff78bda 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -23,6 +23,7 @@ impltypes::PaymentsResponseData,> for PaymentData<api::SetupMandate>{+ #[cfg(feature = "v1")]async fn construct_router_data<'a>(&self,state: &SessionState,@@ -51,6 +52,21 @@ impl.await}+ #[cfg(feature = "v2")]+ async fn construct_router_data<'a>(+ &self,+ state: &SessionState,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+ ) -> RouterResult<types::SetupMandateRouterData> {+ todo!()+ }+async fn get_merchant_recipient_data<'a>(&self,_state: &SessionState,diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rsindex b03f41ac0f..edf0485a77 100644--- a/crates/router/src/core/payments/operations.rs+++ b/crates/router/src/core/payments/operations.rs@@ -35,6 +35,9 @@ pub mod payment_create_intent;#[cfg(feature = "v2")]pub mod payment_get_intent;+#[cfg(feature = "v2")]+pub mod payment_get;+use api_models::enums::FrmSuggestion;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use api_models::routing::RoutableConnectorChoice;@@ -47,6 +50,8 @@ pub use self::payment_confirm_intent::PaymentIntentConfirm;#[cfg(feature = "v2")]pub use self::payment_create_intent::PaymentIntentCreate;#[cfg(feature = "v2")]+pub use self::payment_get::PaymentGet;+#[cfg(feature = "v2")]pub use self::payment_get_intent::PaymentGetIntent;pub use self::payment_response::PaymentResponse;#[cfg(feature = "v1")]@@ -83,20 +88,24 @@ pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| format!("validate request interface not found for {self:?}"))}+fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> {Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))}+fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> {Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| format!("domain interface not found for {self:?}"))}+fn to_update_tracker(&self,) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> {Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| format!("update tracker interface not found for {self:?}"))}+fn to_post_update_tracker(&self,) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, T> + Send + Sync)> {@@ -238,6 +247,7 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {Ok(())}+ #[cfg(feature = "v1")]async fn get_connector<'a>(&'a self,merchant_account: &domain::MerchantAccount,@@ -247,6 +257,17 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {mechant_key_store: &domain::MerchantKeyStore,) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>;+ #[cfg(feature = "v2")]+ async fn perform_routing<'a>(+ &'a self,+ merchant_account: &domain::MerchantAccount,+ business_profile: &domain::Profile,+ state: &SessionState,+ // TODO: do not take the whole payment data here+ payment_data: &mut D,+ mechant_key_store: &domain::MerchantKeyStore,+ ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse>;+async fn populate_payment_data<'a>(&'a self,_state: &SessionState,@@ -303,11 +324,36 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {) -> CustomResult<(), errors::ApiErrorResponse> {Ok(())}++ // #[cfg(feature = "v2")]+ // async fn call_connector<'a, RouterDataReq>(+ // &'a self,+ // _state: &SessionState,+ // _req_state: ReqState,+ // _merchant_account: &domain::MerchantAccount,+ // _key_store: &domain::MerchantKeyStore,+ // _business_profile: &domain::Profile,+ // _payment_method_data: Option<&domain::PaymentMethodData>,+ // _connector: api::ConnectorData,+ // _customer: &Option<domain::Customer>,+ // _payment_data: &mut D,+ // _call_connector_action: common_enums::CallConnectorAction,+ // ) -> CustomResult<+ // hyperswitch_domain_models::router_data::RouterData<F, RouterDataReq, PaymentsResponseData>,+ // errors::ApiErrorResponse,+ // > {+ // // TODO: raise an error here+ // todo!();+ // }}#[async_trait]#[allow(clippy::too_many_arguments)]pub trait UpdateTracker<F, D, Req>: Send {+ /// Update the tracker information with the new data from request or calculated by the operations performed after get trackers+ /// This will persist the SessionData ( PaymentData ) in the database+ ///+ /// In case we are calling a processor / connector, we persist all the data in the database and then call the connectorasync fn update_trackers<'b>(&'b self,db: &'b SessionState,@@ -324,9 +370,33 @@ pub trait UpdateTracker<F, D, Req>: Send {F: 'b + Send;}+#[cfg(feature = "v2")]+#[async_trait]+#[allow(clippy::too_many_arguments)]+pub trait CallConnector<F, D, RouterDReq: Send>: Send {+ async fn call_connector<'b>(+ &'b self,+ db: &'b SessionState,+ req_state: ReqState,+ payment_data: D,+ key_store: &domain::MerchantKeyStore,+ call_connector_action: common_enums::CallConnectorAction,+ connector_data: api::ConnectorData,+ storage_scheme: enums::MerchantStorageScheme,+ ) -> RouterResult<types::RouterData<F, RouterDReq, PaymentsResponseData>>+ where+ F: 'b + Send + Sync,+ D: super::flows::ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,+ types::RouterData<F, RouterDReq, PaymentsResponseData>:+ super::flows::Feature<F, RouterDReq> + Send;+}+#[async_trait]#[allow(clippy::too_many_arguments)]pub trait PostUpdateTracker<F, D, R: Send>: Send {+ /// Update the tracker information with the response from the connector+ /// The response from routerdata is used to update paymentdata and also persist this in the database+ #[cfg(feature = "v1")]async fn update_tracker<'b>(&'b self,db: &'b SessionState,@@ -335,14 +405,26 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {key_store: &domain::MerchantKeyStore,storage_scheme: enums::MerchantStorageScheme,locale: &Option<String>,- #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<- RoutableConnectorChoice,- >,- #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,+ #[cfg(feature = "dynamic_routing")] routable_connector: Vec<RoutableConnectorChoice>,+ #[cfg(feature = "dynamic_routing")] business_profile: &domain::Profile,) -> RouterResult<D>whereF: 'b + Send + Sync;+ #[cfg(feature = "v2")]+ async fn update_tracker<'b>(+ &'b self,+ db: &'b SessionState,+ payment_data: D,+ response: types::RouterData<F, R, PaymentsResponseData>,+ key_store: &domain::MerchantKeyStore,+ storage_scheme: enums::MerchantStorageScheme,+ ) -> RouterResult<D>+ where+ F: 'b + Send + Sync,+ types::RouterData<F, R, PaymentsResponseData>:+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, R>;+async fn save_pm_and_mandate<'b>(&self,_state: &SessionState,@@ -359,6 +441,7 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {}}+#[cfg(feature = "v1")]#[async_trait]impl<D,@@ -409,24 +492,6 @@ whereOk((Box::new(self), customer))}- #[instrument(skip_all)]- #[cfg(feature = "v2")]- async fn get_customer_details<'a>(- &'a self,- _state: &SessionState,- _payment_data: &mut D,- _merchant_key_store: &domain::MerchantKeyStore,- _storage_scheme: enums::MerchantStorageScheme,- ) -> CustomResult<- (- BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>,- Option<domain::Customer>,- ),- errors::StorageError,- > {- todo!()- }-async fn get_connector<'a>(&'a self,_merchant_account: &domain::MerchantAccount,@@ -467,6 +532,7 @@ where}}+#[cfg(feature = "v1")]#[async_trait]impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Data = D>>Domain<F, api::PaymentsCaptureRequest, D> for Op@@ -571,6 +637,7 @@ where}}+#[cfg(feature = "v1")]#[async_trait]impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Data = D>>Domain<F, api::PaymentsCancelRequest, D> for Op@@ -675,6 +742,7 @@ where}}+#[cfg(feature = "v1")]#[async_trait]impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Data = D>>Domain<F, api::PaymentsRejectRequest, D> for Op@@ -765,3 +833,12 @@ pub trait ValidateStatusForOperation {intent_status: common_enums::IntentStatus,) -> Result<(), errors::ApiErrorResponse>;}++/// Should the connector be called for this operation+pub trait ShouldCallConnector {+ fn should_call_connector(+ &self,+ intent_status: common_enums::IntentStatus,+ force_sync: Option<bool>,+ ) -> bool;+}diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex 4c61becdf4..c89f0bdc5c 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -5,16 +5,14 @@ use api_models::{};use async_trait::async_trait;use error_stack::ResultExt;-use hyperswitch_domain_models::payments::{- payment_attempt::PaymentAttempt, PaymentConfirmData, PaymentIntent,-};+use hyperswitch_domain_models::payments::PaymentConfirmData;use router_env::{instrument, tracing};use tracing_futures::Instrument;use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};use crate::{core::{- authentication,+ admin,errors::{self, CustomResult, RouterResult, StorageErrorExt},payments::{self, helpers,@@ -270,15 +268,44 @@ impl<F: Clone + Send> Domain<F, PaymentsConfirmIntentRequest, PaymentConfirmDataOk((Box::new(self), None, None))}- async fn get_connector<'a>(+ #[cfg(feature = "v2")]+ async fn perform_routing<'a>(&'a self,- _merchant_account: &domain::MerchantAccount,+ merchant_account: &domain::MerchantAccount,+ business_profile: &domain::Profile,state: &SessionState,- request: &PaymentsConfirmIntentRequest,- _payment_intent: &storage::PaymentIntent,- _key_store: &domain::MerchantKeyStore,- ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {- todo!()+ // TODO: do not take the whole payment data here+ payment_data: &mut PaymentConfirmData<F>,+ mechant_key_store: &domain::MerchantKeyStore,+ ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {+ use crate::core::payments::OperationSessionSetters;++ let fallback_config = admin::ProfileWrapper::new(business_profile.clone())+ .get_default_fallback_list_of_connector_under_profile()+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let first_chosen_connector = fallback_config+ .first()+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;++ let connector_name = first_chosen_connector.connector.to_string();+ let merchant_connector_id = first_chosen_connector+ .merchant_connector_id+ .clone()+ .get_required_value("merchant_connector_id")?;++ payment_data.set_connector_in_payment_attempt(Some(connector_name.to_string()));+ payment_data.set_merchant_connector_id_in_attempt(Some(merchant_connector_id.clone()));++ let connector_data = api::ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ &connector_name,+ api::GetToken::Connector,+ Some(merchant_connector_id),+ )?;++ Ok(ConnectorCallType::PreDetermined(connector_data))}}@@ -328,7 +355,7 @@ impl<F: Clone> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmIntentRequhyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {status: intent_status,updated_by: storage_scheme.to_string(),- active_attempt_id: payment_data.payment_attempt.get_id().clone(),+ active_attempt_id: payment_data.payment_attempt.id.clone(),};let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rsindex bd82a67e62..d57d24e3ed 100644--- a/crates/router/src/core/payments/operations/payment_create_intent.rs+++ b/crates/router/src/core/payments/operations/payment_create_intent.rs@@ -287,15 +287,17 @@ impl<F: Clone + Send> Domain<F, PaymentsCreateIntentRequest, payments::PaymentInOk((Box::new(self), None, None))}- async fn get_connector<'a>(+ #[instrument(skip_all)]+ async fn perform_routing<'a>(&'a self,- _merchant_account: &domain::MerchantAccount,+ merchant_account: &domain::MerchantAccount,+ business_profile: &domain::Profile,state: &SessionState,- _request: &PaymentsCreateIntentRequest,- _payment_intent: &storage::PaymentIntent,- _merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {- helpers::get_connector_default(state, None).await+ // TODO: do not take the whole payment data here+ payment_data: &mut payments::PaymentIntentData<F>,+ mechant_key_store: &domain::MerchantKeyStore,+ ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {+ Ok(api::ConnectorCallType::Skip)}#[instrument(skip_all)]diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rsnew file mode 100644index 0000000000..2a41756804--- /dev/null+++ b/crates/router/src/core/payments/operations/payment_get.rs@@ -0,0 +1,292 @@+use api_models::{+ admin::ExtendedCardInfoConfig,+ enums::FrmSuggestion,+ payments::{ExtendedCardInfo, GetAddressFromPaymentMethodData, PaymentsRetrieveRequest},+};+use async_trait::async_trait;+use common_utils::ext_traits::AsyncExt;+use error_stack::ResultExt;+use hyperswitch_domain_models::payments::{+ payment_attempt::PaymentAttempt, PaymentIntent, PaymentStatusData,+};+use router_env::{instrument, tracing};+use tracing_futures::Instrument;++use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};+use crate::{+ core::{+ authentication,+ errors::{self, CustomResult, RouterResult, StorageErrorExt},+ payments::{+ self, helpers,+ operations::{self, ValidateStatusForOperation},+ populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData,+ },+ utils as core_utils,+ },+ routes::{app::ReqState, SessionState},+ services,+ types::{+ self,+ api::{self, ConnectorCallType, PaymentIdTypeExt},+ domain::{self},+ storage::{self, enums as storage_enums},+ },+ utils::{self, OptionExt},+};++#[derive(Debug, Clone, Copy)]+pub struct PaymentGet;++impl ValidateStatusForOperation for PaymentGet {+ /// 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> {+ Ok(())+ }+}++type BoxedConfirmOperation<'b, F> =+ super::BoxedOperation<'b, F, PaymentsRetrieveRequest, PaymentStatusData<F>>;++// TODO: change the macro to include changes for v2+// TODO: PaymentData in the macro should be an input+impl<F: Send + Clone> Operation<F, PaymentsRetrieveRequest> for &PaymentGet {+ type Data = PaymentStatusData<F>;+ fn to_validate_request(+ &self,+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)>+ {+ Ok(*self)+ }+ fn to_get_tracker(+ &self,+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> {+ Ok(*self)+ }+ fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsRetrieveRequest, Self::Data>)> {+ Ok(*self)+ }+ fn to_update_tracker(+ &self,+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)>+ {+ Ok(*self)+ }+}+#[automatically_derived]+impl<F: Send + Clone> Operation<F, PaymentsRetrieveRequest> for PaymentGet {+ type Data = PaymentStatusData<F>;+ fn to_validate_request(+ &self,+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)>+ {+ Ok(self)+ }+ fn to_get_tracker(+ &self,+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> {+ Ok(self)+ }+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsRetrieveRequest, Self::Data>> {+ Ok(self)+ }+ fn to_update_tracker(+ &self,+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)>+ {+ Ok(self)+ }+}++impl<F: Send + Clone> ValidateRequest<F, PaymentsRetrieveRequest, PaymentStatusData<F>>+ for PaymentGet+{+ #[instrument(skip_all)]+ fn validate_request<'a, 'b>(+ &'b self,+ request: &PaymentsRetrieveRequest,+ merchant_account: &'a domain::MerchantAccount,+ ) -> RouterResult<(BoxedConfirmOperation<'b, F>, operations::ValidateResult)> {+ let validate_result = operations::ValidateResult {+ merchant_id: merchant_account.get_id().to_owned(),+ storage_scheme: merchant_account.storage_scheme,+ requeue: false,+ };++ Ok((Box::new(self), validate_result))+ }+}++#[async_trait]+impl<F: Send + Clone> GetTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest> for PaymentGet {+ #[instrument(skip_all)]+ async fn get_trackers<'a>(+ &'a self,+ state: &'a SessionState,+ payment_id: &common_utils::id_type::GlobalPaymentId,+ request: &PaymentsRetrieveRequest,+ merchant_account: &domain::MerchantAccount,+ _profile: &domain::Profile,+ key_store: &domain::MerchantKeyStore,+ header_payload: &hyperswitch_domain_models::payments::HeaderPayload,+ ) -> RouterResult<+ operations::GetTrackerResponse<'a, F, PaymentsRetrieveRequest, PaymentStatusData<F>>,+ > {+ let db = &*state.store;+ let key_manager_state = &state.into();++ let storage_scheme = merchant_account.storage_scheme;++ let payment_intent = db+ .find_payment_intent_by_id(key_manager_state, payment_id, key_store, storage_scheme)+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ let payment_attempt = payment_intent+ .active_attempt_id+ .as_ref()+ .async_map(|active_attempt| async {+ db.find_payment_attempt_by_id(+ key_manager_state,+ key_store,+ active_attempt,+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Could not find payment attempt given the attempt id")+ })+ .await+ .transpose()?;++ let should_sync_with_connector =+ request.force_sync && payment_intent.status.should_force_sync_with_connector();++ let payment_data = PaymentStatusData {+ flow: std::marker::PhantomData,+ payment_intent,+ payment_attempt,+ should_sync_with_connector,+ };++ let get_trackers_response = operations::GetTrackerResponse {+ operation: Box::new(self),+ payment_data,+ };++ Ok(get_trackers_response)+ }+}++#[async_trait]+impl<F: Clone + Send> Domain<F, PaymentsRetrieveRequest, PaymentStatusData<F>> for PaymentGet {+ async fn get_customer_details<'a>(+ &'a self,+ state: &SessionState,+ payment_data: &mut PaymentStatusData<F>,+ merchant_key_store: &domain::MerchantKeyStore,+ storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>+ {+ match payment_data.payment_intent.customer_id.clone() {+ Some(id) => {+ let customer = state+ .store+ .find_customer_by_global_id(+ &state.into(),+ id.get_string_repr(),+ &payment_data.payment_intent.merchant_id,+ merchant_key_store,+ storage_scheme,+ )+ .await?;++ Ok((Box::new(self), Some(customer)))+ }+ None => Ok((Box::new(self), None)),+ }+ }++ #[instrument(skip_all)]+ async fn make_pm_data<'a>(+ &'a self,+ state: &'a SessionState,+ payment_data: &mut PaymentStatusData<F>,+ storage_scheme: storage_enums::MerchantStorageScheme,+ key_store: &domain::MerchantKeyStore,+ customer: &Option<domain::Customer>,+ business_profile: &domain::Profile,+ ) -> RouterResult<(+ BoxedConfirmOperation<'a, F>,+ Option<domain::PaymentMethodData>,+ Option<String>,+ )> {+ Ok((Box::new(self), None, None))+ }++ #[instrument(skip_all)]+ async fn perform_routing<'a>(+ &'a self,+ merchant_account: &domain::MerchantAccount,+ business_profile: &domain::Profile,+ state: &SessionState,+ // TODO: do not take the whole payment data here+ payment_data: &mut PaymentStatusData<F>,+ mechant_key_store: &domain::MerchantKeyStore,+ ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {+ match &payment_data.payment_attempt {+ Some(payment_attempt) if payment_data.should_sync_with_connector => {+ let connector = payment_attempt+ .connector+ .as_ref()+ .get_required_value("connector")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Connector is none when constructing response")?;++ let merchant_connector_id = payment_attempt+ .merchant_connector_id+ .as_ref()+ .get_required_value("merchant_connector_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Merchant connector id is none when constructing response")?;++ let connector_data = api::ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ connector,+ api::GetToken::Connector,+ Some(merchant_connector_id.to_owned()),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid connector name received")?;++ Ok(ConnectorCallType::PreDetermined(connector_data))+ }+ None | Some(_) => Ok(ConnectorCallType::Skip),+ }+ }+}++#[async_trait]+impl<F: Clone> UpdateTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest> for PaymentGet {+ #[instrument(skip_all)]+ async fn update_trackers<'b>(+ &'b self,+ state: &'b SessionState,+ req_state: ReqState,+ mut payment_data: PaymentStatusData<F>,+ customer: Option<domain::Customer>,+ storage_scheme: storage_enums::MerchantStorageScheme,+ updated_customer: Option<storage::CustomerUpdate>,+ key_store: &domain::MerchantKeyStore,+ frm_suggestion: Option<FrmSuggestion>,+ header_payload: hyperswitch_domain_models::payments::HeaderPayload,+ ) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentStatusData<F>)>+ where+ F: 'b + Send,+ {+ Ok((Box::new(self), payment_data))+ }+}diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rsindex 55ddc3b482..ca09d021b7 100644--- a/crates/router/src/core/payments/operations/payment_get_intent.rs+++ b/crates/router/src/core/payments/operations/payment_get_intent.rs@@ -207,15 +207,17 @@ impl<F: Clone + Send> Domain<F, PaymentsGetIntentRequest, payments::PaymentIntenOk((Box::new(self), None, None))}- async fn get_connector<'a>(+ #[instrument(skip_all)]+ async fn perform_routing<'a>(&'a self,- _merchant_account: &domain::MerchantAccount,+ merchant_account: &domain::MerchantAccount,+ business_profile: &domain::Profile,state: &SessionState,- _request: &PaymentsGetIntentRequest,- _payment_intent: &storage::PaymentIntent,- _merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {- helpers::get_connector_default(state, None).await+ // TODO: do not take the whole payment data here+ payment_data: &mut payments::PaymentIntentData<F>,+ mechant_key_store: &domain::MerchantKeyStore,+ ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {+ Ok(api::ConnectorCallType::Skip)}#[instrument(skip_all)]diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 427a406dbf..42c3c819fe 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -13,7 +13,7 @@ use error_stack::{report, ResultExt};use futures::FutureExt;use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;#[cfg(feature = "v2")]-use hyperswitch_domain_models::payments::PaymentConfirmData;+use hyperswitch_domain_models::payments::{PaymentConfirmData, PaymentStatusData};use router_derive;use router_env::{instrument, logger, metrics::add_attributes, tracing};use storage_impl::DataModelExt;@@ -27,8 +27,8 @@ use crate::{consts,core::{errors::{self, CustomResult, RouterResult, StorageErrorExt},- mandate, payment_methods,- payment_methods::cards::create_encrypted_data,+ mandate,+ payment_methods::{self, cards::create_encrypted_data},payments::{helpers::{self as payments_helpers,@@ -1259,6 +1259,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,) -> RouterResult<PaymentData<F>> {// Update additional payment data with the payment method response that we received from connector+ // This is for details like whether 3ds was upgraded and which version of 3ds was used+ // also some connectors might send card network details in the response, which is captured and storedlet additional_payment_method_data = match payment_data.payment_method_data.clone() {Some(payment_method_data) => match payment_method_data {@@ -2212,161 +2214,134 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorresponse: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,key_store: &domain::MerchantKeyStore,storage_scheme: enums::MerchantStorageScheme,- locale: &Option<String>,- #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<- RoutableConnectorChoice,- >,- #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,) -> RouterResult<PaymentConfirmData<F>>whereF: 'b + Send + Sync,+ types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<+ F,+ types::PaymentsAuthorizeData,+ >,{+ use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;+let db = &*state.store;let key_manager_state = &state.into();let response_router_data = response;- match response_router_data.response {- Ok(response) => match response {- types::PaymentsResponseData::TransactionResponse {- resource_id,- redirection_data,- mandate_reference,- connector_metadata,- network_txn_id,- connector_response_reference_id,- incremental_authorization_allowed,- charge_id,- } => {- let attempt_status = response_router_data.status;- let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);- let connector_payment_id = match resource_id {- types::ResponseId::NoResponseId => None,- types::ResponseId::ConnectorTransactionId(id)- | types::ResponseId::EncodedData(id) => Some(id),- };- let authentication_data = (*redirection_data)- .as_ref()- .map(Encode::encode_to_value)- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Could not parse the connector response")?- .map(masking::Secret::new);-- let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntentPostUpdate { status: intent_status, updated_by: storage_scheme.to_string() };- 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")?;- payment_data.payment_intent = updated_payment_intent;-- let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntentResponse { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), authentication_data };- 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_attempt = updated_payment_attempt;- }- types::PaymentsResponseData::MultipleCaptureResponse {- capture_sync_response_list,- } => todo!(),- types::PaymentsResponseData::SessionResponse { session_token } => todo!(),- types::PaymentsResponseData::SessionTokenResponse { session_token } => todo!(),- types::PaymentsResponseData::TransactionUnresolvedResponse {- resource_id,- reason,- connector_response_reference_id,- } => todo!(),- types::PaymentsResponseData::TokenizationResponse { token } => todo!(),- types::PaymentsResponseData::ConnectorCustomerResponse {- connector_customer_id,- } => todo!(),- types::PaymentsResponseData::ThreeDSEnrollmentResponse {- enrolled_v2,- related_transaction_id,- } => todo!(),- types::PaymentsResponseData::PreProcessingResponse {- pre_processing_id,- connector_metadata,- session_token,- connector_response_reference_id,- } => todo!(),- types::PaymentsResponseData::IncrementalAuthorizationResponse {- status,- connector_authorization_id,- error_code,- error_message,- } => todo!(),- types::PaymentsResponseData::PostProcessingResponse { session_token } => todo!(),- types::PaymentsResponseData::SessionUpdateResponse { status } => todo!(),- },- Err(ErrorResponse {- code,- message,- reason,- status_code,- attempt_status,- connector_transaction_id,- }) => {- let attempt_status = common_enums::AttemptStatus::Failure;- let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);- let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntentPostUpdate { status: intent_status, updated_by: storage_scheme.to_string() };-- 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")?;-- payment_data.payment_intent = updated_payment_intent;-- // TODO: populate unified code and message and translation by calling gsm and translation table- let error_details =- hyperswitch_domain_models::payments::payment_attempt::ErrorDetails {- code,- message,- reason,- unified_code: None,- unified_message: None,- };+ let payment_intent_update = response_router_data.get_payment_intent_update(storage_scheme);+ let payment_attempt_update =+ response_router_data.get_payment_attempt_update(storage_scheme);- let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntentError { status: attempt_status, error: error_details,updated_by: storage_scheme.to_string() };- 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")?;+ 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;++ Ok(payment_data)+ }+}++#[cfg(feature = "v2")]+impl<F: Send + Clone> Operation<F, types::PaymentsSyncData> for PaymentResponse {+ type Data = PaymentStatusData<F>;+ fn to_post_update_tracker(+ &self,+ ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsSyncData> + Send + Sync)>+ {+ Ok(self)+ }+}++#[cfg(feature = "v2")]+#[async_trait]+impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncData>+ for PaymentResponse+{+ async fn update_tracker<'b>(+ &'b self,+ state: &'b SessionState,+ mut payment_data: PaymentStatusData<F>,+ response: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,+ key_store: &domain::MerchantKeyStore,+ storage_scheme: enums::MerchantStorageScheme,+ ) -> RouterResult<PaymentStatusData<F>>+ where+ F: 'b + Send + Sync,+ types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>:+ hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<+ F,+ types::PaymentsSyncData,+ >,+ {+ 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(storage_scheme);+ let payment_attempt_update =+ response_router_data.get_payment_attempt_update(storage_scheme);++ let payment_attempt = payment_data+ .payment_attempt+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Payment attempt not found in payment data in post update trackers",+ )?;++ 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_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 = Some(updated_payment_attempt);- payment_data.payment_attempt = updated_payment_attempt;- }- }- // TODO: Implement thisOk(payment_data)}}diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex 7fdccf9c60..fed28b6801 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -291,6 +291,7 @@ fn get_flow_name<F>() -> RouterResult<String> {.to_string())}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]pub async fn do_retry<F, ApiRequest, FData, D>(diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex d37b249cd8..52c0f69be1 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -182,7 +182,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(merchant_account: &domain::MerchantAccount,_key_store: &domain::MerchantKeyStore,customer: &'a Option<domain::Customer>,- merchant_connector_account: &helpers::MerchantConnectorAccountType,+ merchant_connector_account: &domain::MerchantConnectorAccount,_merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,) -> RouterResult<types::PaymentsAuthorizeRouterData> {@@ -192,9 +192,8 @@ pub async fn construct_payment_router_data_for_authorize<'a>(Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)})?;- let auth_type: types::ConnectorAuthType = merchant_connector_account+ let auth_type = merchant_connector_account.get_connector_account_details()- .parse_value("ConnectorAuthType").change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed while parsing value for ConnectorAuthType")?;@@ -376,6 +375,138 @@ 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_router_data_for_psync<'a>(+ state: &'a SessionState,+ payment_data: hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>,+ connector_id: &str,+ merchant_account: &domain::MerchantAccount,+ _key_store: &domain::MerchantKeyStore,+ customer: &'a Option<domain::Customer>,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ _merchant_recipient_data: Option<types::MerchantRecipientData>,+ header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,+) -> RouterResult<types::PaymentsSyncRouterData> {+ use masking::ExposeOptionInterface;++ fp_utils::when(merchant_connector_account.is_disabled(), || {+ Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)+ })?;++ // TODO: Take Globalid / CustomerReferenceId and convert to connector reference id+ let customer_id = None;++ let payment_intent = payment_data.payment_intent;++ let auth_type: types::ConnectorAuthType = merchant_connector_account+ .get_connector_account_details()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;++ let attempt = &payment_data+ .payment_attempt+ .get_required_value("attempt")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Payment Attempt is not available in payment data")?;++ let connector_request_reference_id = payment_intent+ .merchant_reference_id+ .map(|id| id.get_string_repr().to_owned())+ .unwrap_or(attempt.id.get_string_repr().to_owned());++ let request = types::PaymentsSyncData {+ amount: attempt.amount_details.net_amount,+ integrity_object: None,+ mandate_id: None,+ connector_transaction_id: match attempt.get_connector_payment_id() {+ Some(connector_txn_id) => {+ types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned())+ }+ None => types::ResponseId::NoResponseId,+ },+ encoded_data: attempt.encoded_data.clone().expose_option(),+ capture_method: Some(payment_intent.capture_method),+ connector_meta: attempt.connector_metadata.clone().expose_option(),+ sync_type: types::SyncRequestType::SinglePaymentSync,+ payment_method_type: Some(attempt.payment_method_subtype),+ currency: payment_intent.amount_details.currency,+ // TODO: Get the charges object from+ charges: None,+ payment_experience: None,+ };++ // TODO: evaluate the fields in router data, if they are required or not+ let router_data = types::RouterData {+ flow: PhantomData,+ merchant_id: merchant_account.get_id().clone(),+ // TODO: evaluate why we need customer id at the connector level. We already have connector customer id.+ customer_id,+ connector: connector_id.to_owned(),+ // TODO: evaluate why we need payment id at the connector level. We already have connector reference id+ payment_id: payment_intent.id.get_string_repr().to_owned(),+ // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id+ attempt_id: attempt.get_id().get_string_repr().to_owned(),+ status: attempt.status,+ payment_method: attempt.payment_method_type,+ connector_auth_type: auth_type,+ description: payment_intent+ .description+ .as_ref()+ .map(|description| description.get_string_repr())+ .map(ToOwned::to_owned),+ // TODO: evaluate why we need to send merchant's return url here+ // This should be the return url of application, since application takes care of the redirection+ return_url: payment_intent+ .return_url+ .as_ref()+ .map(|description| description.get_string_repr())+ .map(ToOwned::to_owned),+ // TODO: Create unified address+ address: hyperswitch_domain_models::payment_address::PaymentAddress::default(),+ auth_type: attempt.authentication_type,+ connector_meta_data: None,+ connector_wallets_details: None,+ request,+ response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),+ amount_captured: None,+ minor_amount_captured: None,+ access_token: None,+ session_token: None,+ reference_id: None,+ payment_method_status: None,+ payment_method_token: None,+ connector_customer: None,+ recurring_mandate_payment_data: None,+ // TODO: This has to be generated as the reference id based on the connector configuration+ // Some connectros might not accept accept the global id. This has to be done when generating the reference id+ connector_request_reference_id,+ preprocessing_id: attempt.preprocessing_step_id.clone(),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,+ // TODO: take this based on the env+ test_mode: Some(true),+ payment_method_balance: None,+ connector_api_version: None,+ connector_http_status_code: None,+ external_latency: None,+ apple_pay_flow: None,+ frm_metadata: None,+ refund_id: None,+ dispute_id: None,+ connector_response: None,+ integrity_check: Ok(()),+ additional_merchant_data: None,+ header_payload,+ connector_mandate_request_reference_id: None,+ };++ Ok(router_data)+}+#[cfg(feature = "v2")]#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]@@ -800,6 +931,7 @@ whereOk(services::ApplicationResponse::JsonWithHeaders((Self {id: payment_intent.id.clone(),+ status: payment_intent.status,amount_details: api_models::payments::AmountDetailsResponse::foreign_from(payment_intent.amount_details.clone(),),@@ -903,7 +1035,7 @@ wherelet redirect_to_url = payment_intent.create_start_redirection_url(base_url, merchant_account.publishable_key.clone())?;let next_action = payment_attempt- .authentication_data+ .redirection_data.as_ref().map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url });@@ -932,6 +1064,68 @@ where}}+#[cfg(feature = "v2")]+impl<F, Op, D> ToResponse<F, D, Op> for api_models::payments::PaymentsRetrieveResponse+where+ F: Clone,+ Op: Debug,+ D: OperationSessionGetters<F>,+{+ #[allow(clippy::too_many_arguments)]+ fn generate_response(+ payment_data: D,+ _customer: Option<domain::Customer>,+ _base_url: &str,+ operation: Op,+ _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,+ _connector_http_status_code: Option<u16>,+ _external_latency: Option<u128>,+ _is_latency_header_enabled: Option<bool>,+ _merchant_account: &domain::MerchantAccount,+ ) -> RouterResponse<Self> {+ let payment_intent = payment_data.get_payment_intent();+ let payment_attempt = payment_data.get_optional_payment_attempt();++ let amount = api_models::payments::ConfirmIntentAmountDetailsResponse::foreign_from((+ &payment_intent.amount_details,+ payment_attempt.map(|payment_attempt| &payment_attempt.amount_details),+ ));++ let connector =+ payment_attempt.and_then(|payment_attempt| payment_attempt.connector.clone());++ let merchant_connector_id = payment_attempt+ .and_then(|payment_attempt| payment_attempt.merchant_connector_id.clone());++ let error = payment_attempt+ .and_then(|payment_attempt| payment_attempt.error.clone())+ .map(api_models::payments::ErrorDetails::foreign_from);++ let response = Self {+ id: payment_intent.id.clone(),+ status: payment_intent.status,+ amount,+ connector,+ client_secret: payment_intent.client_secret.clone(),+ created: payment_intent.created_at,+ payment_method_data: None,+ payment_method_type: payment_attempt.map(|attempt| attempt.payment_method_type),+ payment_method_subtype: payment_attempt.map(|attempt| attempt.payment_method_subtype),+ connector_transaction_id: payment_attempt+ .and_then(|attempt| attempt.connector_payment_id.clone()),+ connector_reference_id: None,+ merchant_connector_id,+ browser_info: None,+ error,+ };++ Ok(services::ApplicationResponse::JsonWithHeaders((+ response,+ vec![],+ )))+ }+}+#[cfg(feature = "v1")]impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponsewhere@@ -3123,6 +3317,57 @@ impl}}+/// The response amount details in the confirm intent response will have the combined fields from+/// intent amount details and attempt amount details.+#[cfg(feature = "v2")]+impl+ ForeignFrom<(+ &hyperswitch_domain_models::payments::AmountDetails,+ Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>,+ )> for api_models::payments::ConfirmIntentAmountDetailsResponse+{+ fn foreign_from(+ (intent_amount_details, attempt_amount_details): (+ &hyperswitch_domain_models::payments::AmountDetails,+ Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>,+ ),+ ) -> Self {+ Self {+ order_amount: intent_amount_details.order_amount,+ currency: intent_amount_details.currency,+ shipping_cost: attempt_amount_details+ .and_then(|attempt_amount| attempt_amount.shipping_cost)+ .or(intent_amount_details.shipping_cost),+ order_tax_amount: attempt_amount_details+ .and_then(|attempt_amount| attempt_amount.order_tax_amount)+ .or(intent_amount_details+ .tax_details+ .as_ref()+ .and_then(|tax_details| tax_details.get_default_tax_amount())),+ skip_external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from(+ intent_amount_details.skip_external_tax_calculation,+ ),+ skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from(+ intent_amount_details.skip_surcharge_calculation,+ ),+ surcharge_amount: attempt_amount_details+ .and_then(|attempt| attempt.surcharge_amount)+ .or(intent_amount_details.surcharge_amount),+ tax_on_surcharge: attempt_amount_details+ .and_then(|attempt| attempt.tax_on_surcharge)+ .or(intent_amount_details.tax_on_surcharge),+ net_amount: attempt_amount_details+ .map(|attempt| attempt.net_amount)+ .unwrap_or(intent_amount_details.calculate_net_amount()),+ amount_to_capture: attempt_amount_details.and_then(|attempt| attempt.amount_to_capture),+ amount_capturable: attempt_amount_details+ .map(|attempt| attempt.amount_capturable)+ .unwrap_or(MinorUnit::zero()),+ amount_captured: intent_amount_details.amount_captured,+ }+ }+}+#[cfg(feature = "v2")]impl ForeignFrom<hyperswitch_domain_models::payments::payment_attempt::ErrorDetails>for api_models::payments::ErrorDetailsdiff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 02c619b68d..adf3c51fd8 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -1762,6 +1762,7 @@ async fn complete_payout_quote_steps_if_required<F>(Ok(())}+#[cfg(feature = "v1")]pub async fn complete_payout_retrieve(state: &SessionState,merchant_account: &domain::MerchantAccount,@@ -1783,6 +1784,16 @@ pub async fn complete_payout_retrieve(Ok(())}+#[cfg(feature = "v2")]+pub async fn complete_payout_retrieve(+ state: &SessionState,+ merchant_account: &domain::MerchantAccount,+ connector_call_type: api::ConnectorCallType,+ payout_data: &mut PayoutData,+) -> RouterResult<()> {+ todo!()+}+pub async fn create_payout_retrieve(state: &SessionState,merchant_account: &domain::MerchantAccount,diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex cf73bd5b11..4b99a9c8f3 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1516,7 +1516,7 @@ impl PaymentAttemptInterface for KafkaStore {&self,key_manager_state: &KeyManagerState,merchant_key_store: &domain::MerchantKeyStore,- attempt_id: &str,+ attempt_id: &id_type::GlobalAttemptId,storage_scheme: MerchantStorageScheme,) -> error_stack::Result<storage::PaymentAttempt, errors::DataStorageError> {self.diesel_storediff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 9f0a83a053..ee6bd68ac2 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -536,6 +536,7 @@ impl Payments {web::resource("/create-external-sdk-tokens").route(web::post().to(payments::payments_connector_session)),)+ .service(web::resource("").route(web::get().to(payments::payment_status))).service(web::resource("/start_redirection").route(web::get().to(payments::payments_start_redirection)),diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex c20f487a28..d674770f4e 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -2139,13 +2139,6 @@ pub async fn payment_confirm_intent(}};- // TODO: handle client secret auth- // let (auth_type, auth_flow) =- // match auth::check_client_secret_and_get_auth(req.headers(), &payload) {- // Ok(auth) => auth,- // Err(e) => return api::log_and_return_error_response(e),- // };-let locking_action = internal_payload.get_locking_input(flow.clone());Box::pin(api::server_wrap(@@ -2185,3 +2178,79 @@ pub async fn payment_confirm_intent()).await}++#[cfg(feature = "v2")]+#[instrument(skip(state, req), fields(flow, payment_id))]+pub async fn payment_status(+ state: web::Data<app::AppState>,+ req: actix_web::HttpRequest,+ payload: web::Query<api_models::payments::PaymentsRetrieveRequest>,+ path: web::Path<common_utils::id_type::GlobalPaymentId>,+) -> impl Responder {+ use hyperswitch_domain_models::payments::PaymentStatusData;++ let flow = match payload.force_sync {+ true => Flow::PaymentsRetrieveForceSync,+ false => Flow::PaymentsRetrieve,+ };++ let global_payment_id = path.into_inner();+ tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());++ let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {+ global_payment_id,+ payload: payload.into_inner(),+ };++ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {+ Ok(headers) => headers,+ Err(err) => {+ return api::log_and_return_error_response(err);+ }+ };++ 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| async {+ let payment_id = req.global_payment_id;+ let request = req.payload;++ let operation = payments::operations::PaymentGet;++ Box::pin(payments::payments_core::<+ api_types::PSync,+ api_models::payments::PaymentsRetrieveResponse,+ _,+ _,+ _,+ PaymentStatusData<api_types::PSync>,+ >(+ state,+ req_state,+ auth.merchant_account,+ auth.profile,+ auth.key_store,+ operation,+ request,+ payment_id,+ payments::CallConnectorAction::Trigger,+ header_payload.clone(),+ ))+ .await+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth),+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentRead,+ },+ req.headers(),+ ),+ locking_action,+ ))+ .await+}diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rsindex 29c7594255..f0269bd029 100644--- a/crates/router/src/routes/routing.rs+++ b/crates/router/src/routes/routing.rs@@ -84,8 +84,7 @@ pub async fn routing_create_config(auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth),&auth::JWTAuth {- permission: Permission::RoutingWrite,- minimum_entity_level: EntityType::Profile,+ permission: Permission::ProfileRoutingWrite,},req.headers(),),@@ -255,8 +254,7 @@ pub async fn routing_retrieve_config(auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth),&auth::JWTAuth {- permission: Permission::RoutingRead,- minimum_entity_level: EntityType::Profile,+ permission: Permission::ProfileRoutingRead,},req.headers(),),diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 70974f0ae6..891d2601c7 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -315,9 +315,6 @@ where#[derive(Debug)]pub struct ApiKeyAuth;-#[derive(Debug)]-pub struct ApiKeyAuthV2;-pub struct NoAuth;#[cfg(feature = "partial-auth")]@@ -2498,6 +2495,13 @@ impl ClientSecretFetch for payments::PaymentsRequest {}}+#[cfg(feature = "v1")]+impl ClientSecretFetch for payments::PaymentsRetrieveRequest {+ fn get_client_secret(&self) -> Option<&String> {+ self.client_secret.as_ref()+ }+}+impl ClientSecretFetch for PaymentMethodListRequest {fn get_client_secret(&self) -> Option<&String> {self.client_secret.as_ref()@@ -2533,12 +2537,6 @@ impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {}}-impl ClientSecretFetch for payments::PaymentsRetrieveRequest {- fn get_client_secret(&self) -> Option<&String> {- self.client_secret.as_ref()- }-}-impl ClientSecretFetch for payments::RetrievePaymentLinkRequest {fn get_client_secret(&self) -> Option<&String> {self.client_secret.as_ref()diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex 6db9d29daa..d0da2466b9 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -76,6 +76,8 @@ pub enum ConnectorCallType {PreDetermined(ConnectorData),Retryable(Vec<ConnectorData>),SessionMultiple(Vec<SessionConnectorData>),+ #[cfg(feature = "v2")]+ Skip,}pub trait ConnectorTransactionId: ConnectorCommon + Sync {diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 2507fa6170..b6beaa1de8 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -134,43 +134,10 @@ impl}}+// TODO: remove this usage in v1 codeimpl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {fn foreign_from(s: storage_enums::AttemptStatus) -> Self {- match s {- storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::AutoRefunded => {- Self::Succeeded- }-- storage_enums::AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation,- storage_enums::AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod,-- storage_enums::AttemptStatus::Authorized => Self::RequiresCapture,- storage_enums::AttemptStatus::AuthenticationPending- | storage_enums::AttemptStatus::DeviceDataCollectionPending => {- Self::RequiresCustomerAction- }- storage_enums::AttemptStatus::Unresolved => Self::RequiresMerchantAction,-- storage_enums::AttemptStatus::PartialCharged => Self::PartiallyCaptured,- storage_enums::AttemptStatus::PartialChargedAndChargeable => {- Self::PartiallyCapturedAndCapturable- }- storage_enums::AttemptStatus::Started- | storage_enums::AttemptStatus::AuthenticationSuccessful- | storage_enums::AttemptStatus::Authorizing- | storage_enums::AttemptStatus::CodInitiated- | storage_enums::AttemptStatus::VoidInitiated- | storage_enums::AttemptStatus::CaptureInitiated- | storage_enums::AttemptStatus::Pending => Self::Processing,-- storage_enums::AttemptStatus::AuthenticationFailed- | storage_enums::AttemptStatus::AuthorizationFailed- | storage_enums::AttemptStatus::VoidFailed- | storage_enums::AttemptStatus::RouterDeclined- | storage_enums::AttemptStatus::CaptureFailed- | storage_enums::AttemptStatus::Failure => Self::Failed,- storage_enums::AttemptStatus::Voided => Self::Cancelled,- }+ Self::from(s)}}diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rsindex 8adeb70064..ae4a9e659a 100644--- a/crates/storage_impl/src/mock_db/payment_attempt.rs+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs@@ -1,6 +1,6 @@use common_utils::errors::CustomResult;#[cfg(feature = "v2")]-use common_utils::types::keymanager::KeyManagerState;+use common_utils::{id_type, types::keymanager::KeyManagerState};use diesel_models::enums as storage_enums;#[cfg(feature = "v2")]use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;@@ -74,7 +74,7 @@ impl PaymentAttemptInterface for MockDb {&self,_key_manager_state: &KeyManagerState,_merchant_key_store: &MerchantKeyStore,- _attempt_id: &str,+ _attempt_id: &id_type::GlobalAttemptId,_storage_scheme: storage_enums::MerchantStorageScheme,) -> error_stack::Result<PaymentAttempt, StorageError> {// [#172]: Implement function for `MockDb`diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rsindex 22160d901f..3a564d958e 100644--- a/crates/storage_impl/src/mock_db/payment_intent.rs+++ b/crates/storage_impl/src/mock_db/payment_intent.rs@@ -95,6 +95,7 @@ impl PaymentIntentInterface for MockDb {Ok(new)}+ #[cfg(feature = "v1")]// safety: only used for testing#[allow(clippy::unwrap_used)]async fn update_payment_intent(@@ -130,6 +131,20 @@ impl PaymentIntentInterface for MockDb {Ok(payment_intent.clone())}+ #[cfg(feature = "v2")]+ // safety: only used for testing+ #[allow(clippy::unwrap_used)]+ async fn update_payment_intent(+ &self,+ state: &KeyManagerState,+ this: PaymentIntent,+ update: PaymentIntentUpdate,+ key_store: &MerchantKeyStore,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<PaymentIntent, StorageError> {+ todo!()+ }+#[cfg(feature = "v1")]// safety: only used for testing#[allow(clippy::unwrap_used)]diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rsindex 899ba08244..7bc9bcc8a9 100644--- a/crates/storage_impl/src/payments/payment_attempt.rs+++ b/crates/storage_impl/src/payments/payment_attempt.rs@@ -375,7 +375,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {&self,key_manager_state: &KeyManagerState,merchant_key_store: &MerchantKeyStore,- attempt_id: &str,+ attempt_id: &common_utils::id_type::GlobalAttemptId,_storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentAttempt, errors::StorageError> {let conn = pg_connection_read(self).await?;@@ -1132,7 +1132,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {&self,key_manager_state: &KeyManagerState,merchant_key_store: &MerchantKeyStore,- attempt_id: &str,+ attempt_id: &common_utils::id_type::GlobalAttemptId,storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentAttempt, errors::StorageError> {// Ignoring storage scheme for v2 implementationdiff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex 3fcd30f1e8..f26cf876ad 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -495,6 +495,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {.change_context(StorageError::DecryptionError)}+ #[cfg(feature = "v1")]#[instrument(skip_all)]async fn update_payment_intent(&self,@@ -528,6 +529,41 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {.change_context(StorageError::DecryptionError)}+ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn update_payment_intent(+ &self,+ state: &KeyManagerState,+ this: PaymentIntent,+ payment_intent: PaymentIntentUpdate,+ merchant_key_store: &MerchantKeyStore,+ _storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PaymentIntent, StorageError> {+ let conn = pg_connection_write(self).await?;+ let diesel_payment_intent_update =+ diesel_models::PaymentIntentUpdateInternal::from(payment_intent);++ let diesel_payment_intent = this+ .convert()+ .await+ .change_context(StorageError::EncryptionError)?+ .update(&conn, diesel_payment_intent_update)+ .await+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(er.current_context());+ er.change_context(new_err)+ })?;++ PaymentIntent::convert_back(+ state,+ diesel_payment_intent,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)+ }+#[cfg(feature = "v1")]#[instrument(skip_all)]async fn find_payment_intent_by_payment_id_merchant_id(diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sqlindex 70aa439510..d008367af3 100644--- a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql+++ b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql@@ -41,4 +41,5 @@ ALTER TABLE payment_attempt DROP COLUMN payment_method_type_v2,DROP COLUMN external_reference_id,DROP COLUMN tax_on_surcharge,DROP COLUMN payment_method_billing_address,+ DROP COLUMN redirection_data,DROP COLUMN connector_payment_data;diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sqlindex 64decb1a0a..a402beac13 100644--- a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql+++ b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql@@ -21,7 +21,7 @@ ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL,-- If no merchants have enabled this, then we can use `false` as the default value-- when adding the column, later we can drop the default added for the column-- so that we ensure new records inserted always have a value for the column.- ADD COLUMN should_collect_cvv_during_payment BOOLEAN NOT NULL;+ADD COLUMN should_collect_cvv_during_payment BOOLEAN NOT NULL;ALTER TABLE payment_intentADD COLUMN merchant_reference_id VARCHAR(64),@@ -50,4 +50,5 @@ ADD COLUMN payment_method_type_v2 VARCHAR,ADD COLUMN external_reference_id VARCHAR(128),ADD COLUMN tax_on_surcharge BIGINT,ADD COLUMN payment_method_billing_address BYTEA,+ ADD COLUMN redirection_data JSONB,ADD COLUMN connector_payment_data VARCHAR(512);diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sqlindex d0bc53f8ca..661f7f294e 100644--- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql+++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql@@ -86,9 +86,17 @@ ALTER TABLE payment_intentALTER COLUMN currency DROP NOT NULL,ALTER COLUMN client_secret DROP NOT NULL,ALTER COLUMN profile_id DROP NOT NULL;-ALTER TABLE payment_intent ALTER COLUMN active_attempt_id SET NOT NULL;-ALTER TABLE payment_intent ALTER COLUMN active_attempt_id SET DEFAULT 'xxx';-ALTER TABLE payment_intent ALTER COLUMN session_expiry DROP NOT NULL;++ALTER TABLE payment_intent+ALTER COLUMN active_attempt_id+SET NOT NULL;++ALTER TABLE payment_intent+ALTER COLUMN session_expiry DROP NOT NULL;++ALTER TABLE payment_intent+ALTER COLUMN active_attempt_id+SET DEFAULT 'xxx';------------------------ Payment Attempt -----------------------ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey;diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sqlindex 8e72e06b66..3b1fe9b46a 100644--- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql+++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql@@ -125,10 +125,14 @@ SET NOT NULL,SET NOT NULL,ALTER COLUMN payment_method_subtypeSET NOT NULL;-ALTER TABLE payment_intent ALTER COLUMN session_expiry SET NOT NULL;++ALTER TABLE payment_intent+ALTER COLUMN session_expiry+SET NOT NULL;-- This migration is to make fields optional in payment_intent table-ALTER TABLE payment_intent ALTER COLUMN active_attempt_id DROP NOT NULL;+ALTER TABLE payment_intent+ALTER COLUMN active_attempt_id DROP NOT NULL;ALTER TABLE payment_intentALTER COLUMN active_attempt_id DROP DEFAULT;diff --git a/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sqlindex 55c5b3f749..64cbd2233e 100644--- a/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql+++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql@@ -87,6 +87,7 @@ ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64) NOT NULL,ADD COLUMN tax_amount bigint,ADD COLUMN straight_through_algorithm JSONB,ADD COLUMN confirm BOOLEAN,+ ADD COLUMN authentication_data JSONB,ADD COLUMN payment_method_billing_address_id VARCHAR(64);-- Create the index which was dropped because of dropping the columndiff --git a/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sqlindex 0d22741b94..507b29dadf 100644--- a/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql+++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql@@ -85,4 +85,5 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id,DROP COLUMN tax_amount,DROP COLUMN straight_through_algorithm,DROP COLUMN confirm,+ DROP COLUMN authentication_data,DROP COLUMN payment_method_billing_address_id;