Skip to content

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

fix(router): Payment link api contract change (#2975)

Sahkal Poddar3cd74966b279
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index ed49b6f27b..c588bb8718 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -95,15 +95,8 @@ pub struct MerchantAccountCreate {
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
- ///Will be used to expire client secret after certain amount of time to be supplied in seconds
- ///(900) for 15 mins
- #[schema(example = 900)]
- pub intent_fulfillment_time: Option<u32>,
-
/// The id of the organization to which the merchant belongs to
pub organization_id: Option<String>,
-
- pub payment_link_config: Option<PaymentLinkConfig>,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
@@ -185,16 +178,10 @@ pub struct MerchantAccountUpdate {
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
- ///Will be used to expire client secret after certain amount of time to be supplied in seconds
- ///(900) for 15 mins
- pub intent_fulfillment_time: Option<u32>,
-
/// The default business profile that must be used for creating merchant accounts and payments
/// To unset this field, pass an empty string
#[schema(max_length = 64)]
pub default_profile: Option<String>,
-
- pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -288,8 +275,6 @@ pub struct MerchantAccountResponse {
/// A enum value to indicate the status of recon service. By default it is not_requested.
#[schema(value_type = ReconStatus, example = "not_requested")]
pub recon_status: enums::ReconStatus,
-
- pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -460,26 +445,6 @@ pub struct PrimaryBusinessDetails {
pub business: String,
}
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
-#[serde(deny_unknown_fields)]
-pub struct PaymentLinkConfig {
- #[schema(
- max_length = 255,
- max_length = 255,
- example = "https://i.imgur.com/RfxPFQo.png"
- )]
- pub merchant_logo: Option<String>,
- pub color_scheme: Option<PaymentLinkColorSchema>,
-}
-
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
-#[serde(deny_unknown_fields)]
-
-pub struct PaymentLinkColorSchema {
- pub background_primary_color: Option<String>,
- pub sdk_theme: Option<String>,
-}
-
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WebhookDetails {
@@ -1048,6 +1013,13 @@ pub struct BusinessProfileCreate {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<BusinessPaymentLinkConfig>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -1112,6 +1084,13 @@ pub struct BusinessProfileResponse {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<i64>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -1169,4 +1148,41 @@ pub struct BusinessProfileUpdate {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<BusinessPaymentLinkConfig>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct BusinessPaymentLinkConfig {
+ pub domain_name: Option<String>,
+ #[serde(flatten)]
+ pub config: PaymentLinkConfigRequest,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentLinkConfigRequest {
+ /// custom theme for the payment link
+ #[schema(value_type = Option<String>, max_length = 255, example = "#4E6ADD")]
+ pub theme: Option<String>,
+ /// merchant display logo
+ #[schema(value_type = Option<String>, max_length = 255, example = "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg")]
+ pub logo: Option<String>,
+ /// Custom merchant name for payment link
+ #[schema(value_type = Option<String>, max_length = 255, example = "hyperswitch")]
+ pub seller_name: Option<String>,
+}
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)]
+pub struct PaymentLinkConfig {
+ /// custom theme for the payment link
+ pub theme: String,
+ /// merchant display logo
+ pub logo: String,
+ /// Custom merchant name for payment link
+ pub seller_name: String,
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5a894e868a..0bfee76304 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -296,8 +296,14 @@ pub struct PaymentsRequest {
/// additional data that might be required by hyperswitch
pub feature_metadata: Option<FeatureMetadata>,
- /// payment link object required for generating the payment_link
- pub payment_link_object: Option<PaymentLinkObject>,
+
+ /// Whether to get the payment link (if applicable)
+ #[schema(default = false, example = true)]
+ pub payment_link: Option<bool>,
+
+ /// custom payment link config for the particular payment
+ #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)]
+ pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>,
/// The business profile to use for this payment, if not passed the default business profile
/// associated with the merchant account will be used.
@@ -314,6 +320,11 @@ pub struct PaymentsRequest {
///Request for an incremental authorization
pub request_incremental_authorization: Option<bool>,
+ ///Will be used to expire client secret after certain amount of time to be supplied in seconds
+ ///(900) for 15 mins
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
/// additional data related to some frm connectors
pub frm_metadata: Option<serde_json::Value>,
}
@@ -3309,17 +3320,6 @@ mod tests {
}
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
-pub struct PaymentLinkObject {
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub link_expiry: Option<PrimitiveDateTime>,
- pub merchant_custom_domain_name: Option<String>,
- #[schema(value_type = PaymentLinkConfig)]
- pub payment_link_config: Option<admin::PaymentLinkConfig>,
- /// Custom merchant name for payment link
- pub custom_merchant_name: Option<String>,
-}
-
#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)]
pub struct RetrievePaymentLinkRequest {
pub client_secret: Option<String>,
@@ -3339,10 +3339,10 @@ pub struct RetrievePaymentLinkResponse {
pub amount: i64,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub link_expiry: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub expiry: Option<PrimitiveDateTime>,
pub description: Option<String>,
- pub status: String,
+ pub status: PaymentLinkStatus,
#[schema(value_type = Option<Currency>)]
pub currency: Option<api_enums::Currency>,
}
@@ -3360,14 +3360,15 @@ pub struct PaymentLinkDetails {
pub pub_key: String,
pub client_secret: String,
pub payment_id: String,
- #[serde(with = "common_utils::custom_serde::iso8601::option")]
- pub expiry: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub session_expiry: PrimitiveDateTime,
pub merchant_logo: String,
pub return_url: String,
pub merchant_name: String,
pub order_details: Option<Vec<OrderDetailsWithStringAmount>>,
pub max_items_visible_after_collapse: i8,
- pub sdk_theme: Option<String>,
+ pub theme: String,
+ pub merchant_description: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
@@ -3424,6 +3425,13 @@ pub struct PaymentLinkListResponse {
pub data: Vec<PaymentLinkResponse>,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentCreatePaymentLinkConfig {
+ #[serde(flatten)]
+ #[schema(value_type = Option<PaymentLinkConfigRequest>)]
+ pub config: admin::PaymentLinkConfigRequest,
+}
+
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct OrderDetailsWithStringAmount {
/// Name of the product that is being purchased
@@ -3437,3 +3445,9 @@ pub struct OrderDetailsWithStringAmount {
/// Product Image link
pub product_img_link: Option<String>,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub enum PaymentLinkStatus {
+ Active,
+ Expired,
+}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 7f9533d7ea..169cb972c0 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -33,11 +33,8 @@ pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;
/// Header Key for application overhead of a request
pub const X_HS_LATENCY: &str = "x-hs-latency";
-/// SDK Default Theme const
-pub const DEFAULT_SDK_THEME: &str = "#7EA8F6";
-
/// Default Payment Link Background color
-pub const DEFAULT_BACKGROUND_COLOR: &str = "#E5E5E5";
+pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46";
/// Default product Img Link
pub const DEFAULT_PRODUCT_IMG: &str = "https://i.imgur.com/On3VtKF.png";
@@ -50,3 +47,9 @@ pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/to
/// Variable which store the card token for Prophetpay
pub const PROPHETPAY_TOKEN: &str = "cctoken";
+
+/// Payment intent fulfillment default timeout (in seconds)
+pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;
+
+/// Payment intent default client secret expiry (in seconds)
+pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
diff --git a/crates/data_models/src/payments.rs b/crates/data_models/src/payments.rs
index b3e2c2e520..cc6b03f89a 100644
--- a/crates/data_models/src/payments.rs
+++ b/crates/data_models/src/payments.rs
@@ -53,4 +53,5 @@ pub struct PaymentIntent {
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 5389cfdd78..80671ec7f6 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -110,6 +110,7 @@ pub struct PaymentIntentNew {
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -162,6 +163,7 @@ pub enum PaymentIntentUpdate {
metadata: Option<pii::SecretSerdeValue>,
payment_confirm_source: Option<storage_enums::PaymentSource>,
updated_by: String,
+ session_expiry: Option<PrimitiveDateTime>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
@@ -226,6 +228,7 @@ pub struct PaymentIntentUpdateInternal {
pub surcharge_applicable: Option<bool>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
@@ -249,6 +252,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -268,6 +272,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
..Default::default()
},
PaymentIntentUpdate::MetadataUpdate {
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 700104aaae..ad66eb7f6f 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -32,6 +32,8 @@ pub struct BusinessProfile {
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -55,6 +57,8 @@ pub struct BusinessProfileNew {
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -75,6 +79,8 @@ pub struct BusinessProfileUpdateInternal {
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
impl From<BusinessProfileNew> for BusinessProfile {
@@ -97,6 +103,8 @@ impl From<BusinessProfileNew> for BusinessProfile {
payout_routing_algorithm: new.payout_routing_algorithm,
is_recon_enabled: new.is_recon_enabled,
applepay_verified_domains: new.applepay_verified_domains,
+ payment_link_config: new.payment_link_config,
+ session_expiry: new.session_expiry,
}
}
}
@@ -118,6 +126,8 @@ impl BusinessProfileUpdateInternal {
payout_routing_algorithm,
is_recon_enabled,
applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
} = self;
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
@@ -136,6 +146,8 @@ impl BusinessProfileUpdateInternal {
payout_routing_algorithm,
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
..source
}
}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index df567f5835..6b546f9078 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -55,18 +55,11 @@ pub struct PaymentIntent {
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(
- Clone,
- Debug,
- Default,
- Eq,
- PartialEq,
- Insertable,
- router_derive::DebugAsDisplay,
- Serialize,
- Deserialize,
+ Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentNew {
@@ -112,6 +105,8 @@ pub struct PaymentIntentNew {
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -164,6 +159,7 @@ pub enum PaymentIntentUpdate {
metadata: Option<pii::SecretSerdeValue>,
payment_confirm_source: Option<storage_enums::PaymentSource>,
updated_by: String,
+ session_expiry: Option<PrimitiveDateTime>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
@@ -229,6 +225,7 @@ pub struct PaymentIntentUpdateInternal {
pub surcharge_applicable: Option<bool>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
impl PaymentIntentUpdate {
@@ -261,6 +258,7 @@ impl PaymentIntentUpdate {
surcharge_applicable,
incremental_authorization_allowed,
authorization_count,
+ session_expiry,
} = self.into();
PaymentIntent {
amount: amount.unwrap_or(source.amount),
@@ -290,10 +288,10 @@ impl PaymentIntentUpdate {
payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source),
updated_by,
surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable),
-
incremental_authorization_allowed: incremental_authorization_allowed
.or(source.incremental_authorization_allowed),
authorization_count: authorization_count.or(source.authorization_count),
+ session_expiry,
..source
}
}
@@ -320,6 +318,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -339,6 +338,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
..Default::default()
},
PaymentIntentUpdate::MetadataUpdate {
diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs
index 999a6767d8..ed0e979d02 100644
--- a/crates/diesel_models/src/payment_link.rs
+++ b/crates/diesel_models/src/payment_link.rs
@@ -18,17 +18,17 @@ pub struct PaymentLink {
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
+ pub profile_id: Option<String>,
}
#[derive(
Clone,
Debug,
- Default,
Eq,
PartialEq,
Insertable,
@@ -48,9 +48,10 @@ pub struct PaymentLinkNew {
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_modified_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
+ pub profile_id: Option<String>,
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f4a0437c6c..f4e41cefde 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -83,6 +83,8 @@ diesel::table! {
payout_routing_algorithm -> Nullable<Jsonb>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
+ payment_link_config -> Nullable<Jsonb>,
+ session_expiry -> Nullable<Int8>,
}
}
@@ -705,6 +707,7 @@ diesel::table! {
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
incremental_authorization_allowed -> Nullable<Bool>,
authorization_count -> Nullable<Int4>,
+ session_expiry -> Nullable<Timestamp>,
}
}
@@ -731,6 +734,8 @@ diesel::table! {
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index eff42c0cd7..afe7618463 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -24,6 +24,9 @@ pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str =
///Payment intent fulfillment default timeout (in seconds)
pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;
+/// Payment intent default client secret expiry (in seconds)
+pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
+
// String literals
pub(crate) const NO_ERROR_MESSAGE: &str = "No error message";
pub(crate) const NO_ERROR_CODE: &str = "No error code";
@@ -71,4 +74,10 @@ pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant";
+/// Max payment session expiry
+pub const MAX_SESSION_EXPIRY: u32 = 7890000;
+
+/// Min payment session expiry
+pub const MIN_SESSION_EXPIRY: u32 = 60;
+
pub const LOCKER_HEALTH_CALL_PATH: &str = "/health";
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 84a2f442de..5381059320 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -140,17 +140,6 @@ pub async fn create_merchant_account(
.transpose()?
.map(Secret::new);
- let payment_link_config = req
- .payment_link_config
- .as_ref()
- .map(|pl_metadata| {
- utils::Encode::<admin_types::PaymentLinkConfig>::encode_to_value(pl_metadata)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config",
- })
- })
- .transpose()?;
-
let organization_id = if let Some(organization_id) = req.organization_id.as_ref() {
db.find_organization_by_org_id(organization_id)
.await
@@ -199,15 +188,15 @@ pub async fn create_merchant_account(
primary_business_details,
created_at: date_time::now(),
modified_at: date_time::now(),
+ intent_fulfillment_time: None,
frm_routing_algorithm: req.frm_routing_algorithm,
- intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),
payout_routing_algorithm: req.payout_routing_algorithm,
id: None,
organization_id,
is_recon_enabled: false,
default_profile: None,
recon_status: diesel_models::enums::ReconStatus::NotRequested,
- payment_link_config,
+ payment_link_config: None,
})
}
.await
@@ -429,6 +418,8 @@ pub async fn update_business_profile_cascade(
frm_routing_algorithm: None,
payout_routing_algorithm: None,
applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -581,10 +572,10 @@ pub async fn merchant_account_update(
publishable_key: None,
primary_business_details,
frm_routing_algorithm: req.frm_routing_algorithm,
- intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),
+ intent_fulfillment_time: None,
payout_routing_algorithm: req.payout_routing_algorithm,
default_profile: business_profile_id_update,
- payment_link_config: req.payment_link_config,
+ payment_link_config: None,
};
let response = db
@@ -1426,6 +1417,9 @@ pub async fn create_business_profile(
request: api::BusinessProfileCreate,
merchant_id: &str,
) -> RouterResponse<api_models::admin::BusinessProfileResponse> {
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into())
@@ -1539,6 +1533,10 @@ pub async fn update_business_profile(
})?
}
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
+
let webhook_details = request
.webhook_details
.as_ref()
@@ -1561,6 +1559,17 @@ pub async fn update_business_profile(
.attach_printable("Invalid routing algorithm given")?;
}
+ let payment_link_config = request
+ .payment_link_config
+ .as_ref()
+ .map(|pl_metadata| {
+ utils::Encode::<admin_types::BusinessPaymentLinkConfig>::encode_to_value(pl_metadata)
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })
+ })
+ .transpose()?;
+
let business_profile_update = storage::business_profile::BusinessProfileUpdateInternal {
profile_name: request.profile_name,
modified_at: Some(date_time::now()),
@@ -1576,6 +1585,8 @@ pub async fn update_business_profile(
payout_routing_algorithm: request.payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains: request.applepay_verified_domains,
+ payment_link_config,
+ session_expiry: request.session_expiry.map(i64::from),
};
let updated_business_profile = db
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 81b06f5f9a..f2043d392a 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -1,7 +1,8 @@
use api_models::admin as admin_types;
use common_utils::{
consts::{
- DEFAULT_BACKGROUND_COLOR, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_THEME,
+ DEFAULT_BACKGROUND_COLOR, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
+ DEFAULT_SESSION_EXPIRY,
},
ext_traits::{OptionExt, ValueExt},
};
@@ -27,15 +28,20 @@ pub async fn retrieve_payment_link(
payment_link_id: String,
) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> {
let db = &*state.store;
- let payment_link_object = db
+ let payment_link_config = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
- let status = check_payment_link_status(payment_link_object.fulfilment_time);
+ let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+
+ let status = check_payment_link_status(session_expiry);
let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from((
- payment_link_object,
+ payment_link_config,
status,
));
Ok(services::ApplicationResponse::Json(response))
@@ -74,15 +80,25 @@ pub async fn intiate_payment_link_flow(
"use payment link for",
)?;
+ let merchant_name_from_merchant_account = merchant_account
+ .merchant_name
+ .clone()
+ .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
+ .unwrap_or_default();
+
let payment_link = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
- let payment_link_config = if let Some(pl_config) = payment_link.payment_link_config.clone() {
- extract_payment_link_config(Some(pl_config))?
+ let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config {
+ extract_payment_link_config(pl_config_value)?
} else {
- extract_payment_link_config(merchant_account.payment_link_config.clone())?
+ admin_types::PaymentLinkConfig {
+ theme: DEFAULT_BACKGROUND_COLOR.to_string(),
+ logo: DEFAULT_MERCHANT_LOGO.to_string(),
+ seller_name: merchant_name_from_merchant_account,
+ }
};
let return_url = if let Some(payment_create_return_url) = payment_intent.return_url {
@@ -102,8 +118,13 @@ pub async fn intiate_payment_link_flow(
)?;
let order_details = validate_order_details(payment_intent.order_details, currency)?;
- let (default_sdk_theme, default_background_color) =
- (DEFAULT_SDK_THEME, DEFAULT_BACKGROUND_COLOR);
+ let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+
+ // converting first letter of merchant name to upperCase
+ let merchant_name = capitalize_first_char(&payment_link_config.seller_name);
let payment_details = api_models::payments::PaymentLinkDetails {
amount: currency
@@ -112,38 +133,20 @@ pub async fn intiate_payment_link_flow(
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?,
currency,
payment_id: payment_intent.payment_id,
- merchant_name: payment_link.custom_merchant_name.unwrap_or(
- merchant_account
- .merchant_name
- .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
- .unwrap_or_default(),
- ),
+ merchant_name,
order_details,
return_url,
- expiry: payment_link.fulfilment_time,
+ session_expiry,
pub_key,
client_secret,
- merchant_logo: payment_link_config
- .clone()
- .map(|pl_config| {
- pl_config
- .merchant_logo
- .unwrap_or(DEFAULT_MERCHANT_LOGO.to_string())
- })
- .unwrap_or_default(),
+ merchant_logo: payment_link_config.clone().logo,
max_items_visible_after_collapse: 3,
- sdk_theme: payment_link_config.clone().and_then(|pl_config| {
- pl_config
- .color_scheme
- .map(|color| color.sdk_theme.unwrap_or(default_sdk_theme.to_string()))
- }),
+ theme: payment_link_config.clone().theme,
+ merchant_description: payment_intent.description,
};
let js_script = get_js_script(payment_details)?;
- let css_script = get_color_scheme_css(
- payment_link_config.clone(),
- default_background_color.to_string(),
- );
+ let css_script = get_color_scheme_css(payment_link_config.clone());
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
@@ -168,20 +171,8 @@ fn get_js_script(
Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};"))
}
-fn get_color_scheme_css(
- payment_link_config: Option<api_models::admin::PaymentLinkConfig>,
- default_primary_color: String,
-) -> String {
- let background_primary_color = payment_link_config
- .and_then(|pl_config| {
- pl_config.color_scheme.map(|color| {
- color
- .background_primary_color
- .unwrap_or(default_primary_color.clone())
- })
- })
- .unwrap_or(default_primary_color);
-
+fn get_color_scheme_css(payment_link_config: api_models::admin::PaymentLinkConfig) -> String {
+ let background_primary_color = payment_link_config.theme;
format!(
":root {{
--primary-color: {background_primary_color};
@@ -226,13 +217,15 @@ pub async fn list_payment_link(
Ok(services::ApplicationResponse::Json(payment_link_list))
}
-pub fn check_payment_link_status(fulfillment_time: Option<PrimitiveDateTime>) -> String {
- let curr_time = Some(common_utils::date_time::now());
+pub fn check_payment_link_status(
+ max_age: PrimitiveDateTime,
+) -> api_models::payments::PaymentLinkStatus {
+ let curr_time = common_utils::date_time::now();
- if curr_time > fulfillment_time {
- "expired".to_string()
+ if curr_time > max_age {
+ api_models::payments::PaymentLinkStatus::Expired
} else {
- "active".to_string()
+ api_models::payments::PaymentLinkStatus::Active
}
}
@@ -276,7 +269,8 @@ fn validate_order_details(
.to_currency_base_unit(order.amount)
.into_report()
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?;
- order_details_amount_string.product_name = order.product_name.clone();
+ order_details_amount_string.product_name =
+ capitalize_first_char(&order.product_name.clone());
order_details_amount_string.quantity = order.quantity;
order_details_amount_string_array.push(order_details_amount_string)
}
@@ -287,16 +281,91 @@ fn validate_order_details(
Ok(updated_order_details)
}
-fn extract_payment_link_config(
- pl_config: Option<serde_json::Value>,
-) -> Result<Option<admin_types::PaymentLinkConfig>, error_stack::Report<errors::ApiErrorResponse>> {
- pl_config
- .map(|config| {
- serde_json::from_value::<admin_types::PaymentLinkConfig>(config)
- .into_report()
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config",
- })
+pub fn extract_payment_link_config(
+ pl_config: serde_json::Value,
+) -> Result<api_models::admin::PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> {
+ serde_json::from_value::<api_models::admin::PaymentLinkConfig>(pl_config.clone())
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
})
- .transpose()
+}
+
+pub fn get_payment_link_config_based_on_priority(
+ payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>,
+ business_link_config: Option<serde_json::Value>,
+ merchant_name: String,
+ default_domain_name: String,
+) -> Result<(admin_types::PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>>
+{
+ let (domain_name, business_config) = if let Some(business_config) = business_link_config {
+ let extracted_value: api_models::admin::BusinessPaymentLinkConfig = business_config
+ .parse_value("BusinessPaymentLinkConfig")
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })
+ .attach_printable("Invalid payment_link_config given in business config")?;
+
+ (
+ extracted_value
+ .domain_name
+ .clone()
+ .map(|d_name| format!("https://{}", d_name))
+ .unwrap_or_else(|| default_domain_name.clone()),
+ Some(extracted_value.config),
+ )
+ } else {
+ (default_domain_name, None)
+ };
+
+ let theme = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.theme.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.theme.clone())
+ })
+ .unwrap_or(DEFAULT_BACKGROUND_COLOR.to_string());
+
+ let logo = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.logo.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.logo.clone())
+ })
+ .unwrap_or(DEFAULT_MERCHANT_LOGO.to_string());
+
+ let seller_name = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.seller_name.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.seller_name.clone())
+ })
+ .unwrap_or(merchant_name.clone());
+
+ let payment_link_config = admin_types::PaymentLinkConfig {
+ theme,
+ logo,
+ seller_name,
+ };
+
+ Ok((payment_link_config, domain_name))
+}
+
+fn capitalize_first_char(s: &str) -> String {
+ if let Some(first_char) = s.chars().next() {
+ let capitalized = first_char.to_uppercase();
+ let mut result = capitalized.to_string();
+ if let Some(remaining) = s.get(1..) {
+ result.push_str(remaining);
+ }
+ result
+ } else {
+ s.to_owned()
+ }
}
diff --git a/crates/router/src/core/payment_link/payment_link.html b/crates/router/src/core/payment_link/payment_link.html
index 0ca4abd340..4fb5bb98ef 100644
--- a/crates/router/src/core/payment_link/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link.html
@@ -1,9 +1,9 @@
<!DOCTYPE html>
-<html>
+<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- {{ hyperloader_sdk_link }}
+ <title>Payments requested by HyperSwitch</title>
<style>
{{ css_color_scheme }}
@@ -19,8 +19,7 @@
align-items: center;
justify-content: flex-start;
margin: 0;
- background-color: #fafafa;
- color: #292929;
+ color: #333333;
}
/* Hide scrollbar for Chrome, Safari and Opera */
@@ -36,16 +35,27 @@
/* Firefox */
}
+ /* For ellipsis on text lines */
+ .ellipsis-container-3 {
+ height: 4em;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ text-overflow: ellipsis;
+ white-space: normal;
+ }
+
.hidden {
display: none !important;
}
.hyper-checkout {
display: flex;
- background-color: #fafafa;
+ background-color: #f8f9fb;
+ color: #333333;
width: 100%;
height: 100%;
- max-width: 1900px;
overflow: scroll;
}
@@ -54,7 +64,6 @@
display: flex;
justify-content: center;
background-color: white;
- z-index: 100;
padding: 20px 0;
}
@@ -63,8 +72,7 @@
flex-flow: column;
justify-content: center;
align-items: center;
- background-color: #fdfdfd;
- min-width: 500px;
+ min-width: 600px;
width: 50vw;
}
@@ -73,15 +81,23 @@
}
.hyper-checkout-payment {
- border: 1px solid #e6e6e6;
+ min-width: 600px;
+ box-shadow: 0px 0px 5px #d1d1d1;
border-radius: 8px;
- min-width: 582px;
+ background-color: #fefefe;
}
.hyper-checkout-payment-content-details {
+ display: flex;
+ flex-flow: column;
+ justify-content: space-between;
+ align-content: space-between;
+ }
+
+ .content-details-wrap {
display: flex;
flex-flow: row;
- margin: 20px;
+ margin: 20px 20px 30px 20px;
justify-content: space-between;
}
@@ -94,16 +110,17 @@
}
#hyper-checkout-payment-merchant-details {
- margin-top: 20px;
+ margin-top: 5px;
}
.hyper-checkout-payment-merchant-name {
font-weight: 600;
- font-size: 18px;
+ font-size: 19px;
}
.hyper-checkout-payment-ref {
- font-size: 13px;
+ font-size: 12px;
+ margin-top: 5px;
}
.hyper-checkout-image-header {
@@ -119,13 +136,14 @@
border: 1px solid #e6e6e6;
border-radius: 4px;
display: flex;
+ align-self: flex-start;
align-items: center;
justify-content: center;
}
#hyper-checkout-merchant-image > img {
- height: 40px;
- width: 40px;
+ height: 48px;
+ width: 48px;
}
#hyper-checkout-cart-image {
@@ -138,25 +156,24 @@
}
#hyper-checkout-payment-footer {
- padding: 8px 20px;
+ margin-top: 20px;
background-color: #f5f5f5;
font-size: 13px;
font-weight: 500;
+ padding: 12px 20px;
+ border-radius: 0 0 8px 8px;
}
#hyper-checkout-cart {
display: flex;
flex-flow: column;
- min-width: 584px;
- width: 400px;
- margin-top: 30px;
- max-height: 600px;
+ min-width: 600px;
+ margin-top: 40px;
+ max-height: 60vh;
}
#hyper-checkout-cart-items {
- margin: 10px 20px 10px 0;
- max-height: 354px;
- height: 354px;
+ max-height: 291px;
overflow: scroll;
transition: all 0.3s ease;
}
@@ -181,14 +198,14 @@
.hyper-checkout-cart-item {
display: flex;
flex-flow: row;
- padding: 20px 10px;
+ padding: 20px 0;
font-size: 15px;
- box-shadow: 0px 0px 10px #efefef;
}
.hyper-checkout-cart-product-image {
height: 56px;
width: 56px;
+ border-radius: 4px;
}
.hyper-checkout-card-item-name {
@@ -213,7 +230,7 @@
.hyper-checkout-cart-product-details {
display: flex;
flex-flow: column;
- margin-left: 10px;
+ margin-left: 15px;
justify-content: space-between;
width: 100%;
}
@@ -233,10 +250,30 @@
}
.hyper-checkout-cart-button {
- color: var(--primary-color);
- font-size: 15px;
- font-weight: 600;
+ font-size: 12px;
+ font-weight: 500;
cursor: pointer;
+ align-self: flex-start;
+ display: flex;
+ align-content: flex-end;
+ gap: 3px;
+ text-decoration: none;
+ transition: text-decoration 0.3s;
+ margin-top: 10px;
+ }
+
+ .hyper-checkout-cart-button:hover {
+ text-decoration: underline;
+ }
+
+ #hyper-checkout-merchant-description {
+ font-size: 13px;
+ color: #808080;
+ }
+
+ .powered-by-hyper {
+ margin-top: 40px;
+ align-self: flex-start;
}
.hyper-checkout-sdk {
@@ -259,10 +296,6 @@
border-radius: 3px;
}
- .powered-by-hyper {
- margin-top: 20px;
- }
-
#hyper-checkout-sdk-header {
padding: 10px 10px 10px 22px;
display: flex;
@@ -315,82 +348,155 @@
margin-top: 10px;
}
- .page-spinner,
- .page-spinner::before,
- .page-spinner::after {
- border-radius: 50%;
- }
-
.page-spinner {
- color: #ffffff;
- font-size: 22px;
- text-indent: -99999px;
- margin: 0px auto;
- position: relative;
- width: 20px;
- height: 20px;
- box-shadow: inset 0 0 0 2px;
- -webkit-transform: translateZ(0);
- -ms-transform: translateZ(0);
- transform: translateZ(0);
- }
-
- .page-spinner::before,
- .page-spinner::after {
position: absolute;
- content: "";
+ width: 100vw;
+ height: 100vh;
+ z-index: 3;
+ background-color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .sdk-spinner {
+ width: 100%;
+ height: 100%;
+ z-index: 3;
+ background-color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .spinner {
+ width: 60px;
+ height: 60px;
+ }
+ .spinner div {
+ transform-origin: 30px 30px;
+ animation: spinner 1.2s linear infinite;
+ }
+ .spinner div:after {
+ content: " ";
+ display: block;
+ position: absolute;
+ top: 3px;
+ left: 28px;
+ width: 4px;
+ height: 15px;
+ border-radius: 20%;
+ background: var(--primary-color);
+ }
+ .spinner div:nth-child(1) {
+ transform: rotate(0deg);
+ animation-delay: -1.1s;
+ }
+ .spinner div:nth-child(2) {
+ transform: rotate(30deg);
+ animation-delay: -1s;
+ }
+ .spinner div:nth-child(3) {
+ transform: rotate(60deg);
+ animation-delay: -0.9s;
+ }
+ .spinner div:nth-child(4) {
+ transform: rotate(90deg);
+ animation-delay: -0.8s;
+ }
+ .spinner div:nth-child(5) {
+ transform: rotate(120deg);
+ animation-delay: -0.7s;
+ }
+ .spinner div:nth-child(6) {
+ transform: rotate(150deg);
+ animation-delay: -0.6s;
+ }
+ .spinner div:nth-child(7) {
+ transform: rotate(180deg);
+ animation-delay: -0.5s;
+ }
+ .spinner div:nth-child(8) {
+ transform: rotate(210deg);
+ animation-delay: -0.4s;
+ }
+ .spinner div:nth-child(9) {
+ transform: rotate(240deg);
+ animation-delay: -0.3s;
+ }
+ .spinner div:nth-child(10) {
+ transform: rotate(270deg);
+ animation-delay: -0.2s;
+ }
+ .spinner div:nth-child(11) {
+ transform: rotate(300deg);
+ animation-delay: -0.1s;
+ }
+ .spinner div:nth-child(12) {
+ transform: rotate(330deg);
+ animation-delay: 0s;
+ }
+ @keyframes spinner {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0;
+ }
}
- .page-spinner {
- color: var(--primary-color) !important;
- height: 50px !important;
- width: 50px !important;
- box-shadow: inset 0 0 0 4px !important;
- margin: auto !important;
+ #hyper-checkout-status-canvas {
+ width: 100%;
+ height: 100%;
+ justify-content: center;
+ align-items: center;
+ background-color: var(--primary-color);
}
- #hyper-checkout-status {
+ .hyper-checkout-status-wrap {
display: flex;
flex-flow: column;
font-family: "Montserrat";
- height: 100%;
- width: 100%;
+ width: auto;
+ min-width: 400px;
+ background-color: white;
+ border-radius: 5px;
}
#hyper-checkout-status-header {
max-width: 1200px;
- border: 1px solid #e6e6e6;
border-radius: 3px;
- padding: 20px;
+ border-bottom: 1px solid #e6e6e6;
}
#hyper-checkout-status-header,
#hyper-checkout-status-content {
- width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 24px;
font-weight: 600;
+ padding: 15px 20px;
}
.hyper-checkout-status-amount {
font-family: "Montserrat";
- font-size: 40px;
+ font-size: 35px;
font-weight: 700;
}
.hyper-checkout-status-merchant-logo {
border: 1px solid #e6e6e6;
- height: 62px;
- width: 62px;
+ border-radius: 5px;
+ padding: 9px;
+ height: 48px;
+ width: 48px;
}
#hyper-checkout-status-content {
- justify-content: center;
- align-items: center;
- flex-flow: column;
height: 100%;
+ flex-flow: column;
+ min-height: 500px;
+ align-items: center;
+ justify-content: center;
}
.hyper-checkout-status-image {
@@ -400,17 +506,18 @@
.hyper-checkout-status-text {
text-align: center;
- font-size: 28px;
+ font-size: 21px;
font-weight: 600;
margin-top: 20px;
}
.hyper-checkout-status-message {
text-align: center;
- font-size: 12px;
+ font-size: 12px !important;
margin-top: 10px;
font-size: 14px;
font-weight: 500;
+ max-width: 400px;
}
.hyper-checkout-status-details {
@@ -419,7 +526,7 @@
margin-top: 20px;
border-radius: 3px;
border: 1px solid #e6e6e6;
- width: 90vw;
+ max-width: calc(100vw - 40px);
}
.hyper-checkout-status-item {
@@ -427,6 +534,7 @@
align-items: center;
padding: 5px 10px;
border-bottom: 1px solid #e6e6e6;
+ word-wrap: break-word;
}
.hyper-checkout-status-item:last-child {
@@ -443,6 +551,13 @@
overflow-x: hidden;
overflow-y: auto;
word-wrap: break-word;
+ font-weight: 400;
+ }
+
+ #hyper-checkout-status-redirect-message {
+ margin-top: 20px;
+ font-family: "Montserrat";
+ font-size: 13px;
}
@keyframes loading {
@@ -490,10 +605,20 @@
text-align: center;
}
- @media only screen and (max-width: 1200px) {
+ @media only screen and (max-width: 1400px) {
+ body {
+ overflow: scroll;
+ }
+
.hyper-checkout {
flex-flow: column;
margin: 0;
+ height: auto;
+ overflow: visible;
+ }
+
+ #hyper-checkout-payment-merchant-details {
+ margin-top: 20px;
}
.main {
@@ -502,9 +627,10 @@
}
.hyper-checkout-payment {
- min-width: 100px;
- width: 100vw;
+ min-width: 300px;
+ width: calc(100vw - 50px);
margin: 0;
+ padding: 25px;
border: 0;
border-radius: 0;
background-color: var(--primary-color);
@@ -515,9 +641,16 @@
}
.hyper-checkout-payment-content-details {
+ max-width: 520px;
+ width: 100%;
+ align-self: center;
+ margin-bottom: 0;
+ }
+
+ .content-details-wrap {
flex-flow: column;
flex-direction: column-reverse;
- margin: 24px;
+ margin: 0;
}
#hyper-checkout-merchant-image {
@@ -538,11 +671,9 @@
}
#hyper-checkout-payment-footer {
- background-color: var(--primary-accent-color);
border-radius: 50px;
- width: auto;
- align-self: center;
- margin: 0 24px 24px 24px;
+ width: max-content;
+ padding: 10px 20px;
}
#hyper-checkout-cart {
@@ -574,7 +705,6 @@
#hyper-checkout-cart-items {
margin: 20px 20px 0 20px;
padding: 0;
- max-height: max-content;
}
.hyper-checkout-cart-button {
@@ -582,17 +712,30 @@
text-align: right;
}
+ .powered-by-hyper {
+ display: none;
+ }
+
#hyper-checkout-sdk {
- margin: 20px 0 0 0;
background-color: transparent;
+ width: auto;
min-width: 300px;
- width: 100vw;
}
#payment-form-wrap {
min-width: 300px;
- padding: 10px;
- width: calc(100vw - 20px);
+ width: calc(100vw - 40px);
+ margin: 0;
+ padding: 25px 20px;
+ }
+
+ #hyper-checkout-status-canvas {
+ background-color: #fefefe;
+ }
+
+ .hyper-checkout-status-wrap {
+ min-width: 100vw;
+ width: 100vw;
}
#hyper-checkout-status-header {
@@ -604,7 +747,8 @@
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800"
/>
-
+ </head>
+ <body>
<!-- SVG ICONS -->
<svg xmlns="http://www.w3.org/2000/svg" display="none">
<defs>
@@ -618,7 +762,7 @@
width="16"
height="16"
>
- <path d="M16 0H0V16H16V0Z" fill="white" />
+ <path d="M16 0H0V16H16V0Z" fill="white"></path>
</mask>
<g mask="url(#mask0_1_13)">
<mask
@@ -630,19 +774,19 @@
width="16"
height="16"
>
- <path d="M16 0H0V16H16V0Z" fill="#D9D9D9" />
+ <path d="M16 0H0V16H16V0Z" fill="#D9D9D9"></path>
</mask>
<g mask="url(#mask1_1_13)">
<path
d="M3.53716 14.3331C3.20469 14.3331 2.92071 14.2153 2.68525 13.9798C2.44977 13.7444 2.33203 13.4604 2.33203 13.1279V5.53823C2.33203 5.20575 2.44977 4.92178 2.68525 4.68631C2.92071 4.45083 3.20469 4.3331 3.53716 4.3331H4.9987C4.9987 3.50063 5.29058 2.79252 5.87433 2.20876C6.4581 1.62501 7.16621 1.33313 7.99868 1.33313C8.83115 1.33313 9.53927 1.62501 10.123 2.20876C10.7068 2.79252 10.9987 3.50063 10.9987 4.3331H12.4602C12.7927 4.3331 13.0766 4.45083 13.3121 4.68631C13.5476 4.92178 13.6653 5.20575 13.6653 5.53823V13.1279C13.6653 13.4604 13.5476 13.7444 13.3121 13.9798C13.0766 14.2153 12.7927 14.3331 12.4602 14.3331H3.53716ZM3.53716 13.3331H12.4602C12.5115 13.3331 12.5585 13.3117 12.6012 13.269C12.644 13.2262 12.6653 13.1792 12.6653 13.1279V5.53823C12.6653 5.48694 12.644 5.43992 12.6012 5.39718C12.5585 5.35445 12.5115 5.33308 12.4602 5.33308H3.53716C3.48588 5.33308 3.43886 5.35445 3.39611 5.39718C3.35338 5.43992 3.33201 5.48694 3.33201 5.53823V13.1279C3.33201 13.1792 3.35338 13.2262 3.39611 13.269C3.43886 13.3117 3.48588 13.3331 3.53716 13.3331ZM7.99868 8.99973C8.83115 8.99973 9.53927 8.70785 10.123 8.1241C10.7068 7.54033 10.9987 6.83221 10.9987 5.99975H9.99868C9.99868 6.5553 9.80424 7.02752 9.41535 7.41641C9.02646 7.8053 8.55424 7.99975 7.99868 7.99975C7.44313 7.99975 6.9709 7.8053 6.58202 7.41641C6.19313 7.02752 5.99868 6.5553 5.99868 5.99975H4.9987C4.9987 6.83221 5.29058 7.54033 5.87433 8.1241C6.4581 8.70785 7.16621 8.99973 7.99868 8.99973ZM5.99868 4.3331H9.99868C9.99868 3.77754 9.80424 3.30532 9.41535 2.91643C9.02646 2.52754 8.55424 2.3331 7.99868 2.3331C7.44313 2.3331 6.9709 2.52754 6.58202 2.91643C6.19313 3.30532 5.99868 3.77754 5.99868 4.3331Z"
fill="#333333"
- />
+ ></path>
</g>
</g>
</symbol>
<symbol id="cart-icon-big">
<mask
- id="mask0_1_13"
+ id="mask0_1_14"
style="mask-type: luminance"
maskUnits="userSpaceOnUse"
x="0"
@@ -650,11 +794,11 @@
width="30"
height="30"
>
- <path d="M30 0H0V30H30V0Z" fill="white" />
+ <path d="M30 0H0V30H30V0Z" fill="white"></path>
</mask>
- <g mask="url(#mask0_1_13)">
+ <g mask="url(#mask0_1_14)">
<mask
- id="mask1_1_13"
+ id="mask1_1_14"
style="mask-type: alpha"
maskUnits="userSpaceOnUse"
x="0"
@@ -662,13 +806,13 @@
width="30"
height="30"
>
- <path d="M30 0H0V30H30V0Z" fill="#D9D9D9" />
+ <path d="M30 0H0V30H30V0Z" fill="#D9D9D9"></path>
</mask>
- <g mask="url(#mask1_1_13)">
+ <g mask="url(#mask1_1_14)">
<path
d="M6.63218 26.8746C6.0088 26.8746 5.47633 26.6537 5.03485 26.2121C4.59332 25.7708 4.37256 25.2383 4.37256 24.6148V10.3842C4.37256 9.76078 4.59332 9.22834 5.03485 8.78683C5.47633 8.34531 6.0088 8.12456 6.63218 8.12456H9.37257C9.37257 6.56368 9.91984 5.23597 11.0144 4.14142C12.1089 3.04689 13.4366 2.49962 14.9975 2.49962C16.5584 2.49962 17.8861 3.04689 18.9806 4.14142C20.0753 5.23597 20.6226 6.56368 20.6226 8.12456H23.3629C23.9863 8.12456 24.5186 8.34531 24.9602 8.78683C25.4018 9.22834 25.6224 9.76078 25.6224 10.3842V24.6148C25.6224 25.2383 25.4018 25.7708 24.9602 26.2121C24.5186 26.6537 23.9863 26.8746 23.3629 26.8746H6.63218ZM6.63218 24.9996H23.3629C23.4591 24.9996 23.5472 24.9594 23.6273 24.8794C23.7075 24.7991 23.7474 24.711 23.7474 24.6148V10.3842C23.7474 10.288 23.7075 10.1999 23.6273 10.1197C23.5472 10.0396 23.4591 9.99952 23.3629 9.99952H6.63218C6.53603 9.99952 6.44786 10.0396 6.36771 10.1197C6.28759 10.1999 6.24752 10.288 6.24752 10.3842V24.6148C6.24752 24.711 6.28759 24.7991 6.36771 24.8794C6.44786 24.9594 6.53603 24.9996 6.63218 24.9996ZM14.9975 16.8745C16.5584 16.8745 17.8861 16.3272 18.9806 15.2327C20.0753 14.1381 20.6226 12.8104 20.6226 11.2495H18.7475C18.7475 12.2912 18.383 13.1766 17.6538 13.9058C16.9246 14.6349 16.0392 14.9995 14.9975 14.9995C13.9559 14.9995 13.0704 14.6349 12.3413 13.9058C11.6121 13.1766 11.2475 12.2912 11.2475 11.2495H9.37257C9.37257 12.8104 9.91984 14.1381 11.0144 15.2327C12.1089 16.3272 13.4366 16.8745 14.9975 16.8745ZM11.2475 8.12456H18.7475C18.7475 7.08289 18.383 6.19747 17.6538 5.46831C16.9246 4.73914 16.0392 4.37456 14.9975 4.37456C13.9559 4.37456 13.0704 4.73914 12.3413 5.46831C11.6121 6.19747 11.2475 7.08289 11.2475 8.12456Z"
fill="#333333"
- />
+ ></path>
</g>
</g>
</symbol>
@@ -730,52 +874,100 @@
></path>
</g>
</symbol>
+ <symbol id="arrow-down">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M8.20573 11.0351C8.33593 11.0351 8.45573 10.9831 8.54948 10.8841L12.5911 6.75911C12.6797 6.66536 12.7266 6.55078 12.7266 6.41536C12.7266 6.14974 12.5234 5.94141 12.2526 5.94141C12.1224 5.94141 12.0026 5.99349 11.9141 6.07682L8.20573 9.86848L4.4974 6.07682C4.40887 5.99349 4.29429 5.94141 4.15882 5.94141C3.88798 5.94141 3.68486 6.14974 3.68486 6.41536C3.68486 6.55078 3.7318 6.66536 3.82549 6.75911L7.86198 10.8841C7.96094 10.9831 8.07551 11.0351 8.20573 11.0351Z"
+ fill="#333333"
+ ></path>
+ </svg>
+ </symbol>
+ <symbol id="arrow-up">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M7.79427 4.96485C7.66407 4.96485 7.54427 5.01694 7.45052 5.11587L3.40886 9.24089C3.32032 9.33464 3.27344 9.44922 3.27344 9.58464C3.27344 9.85026 3.47657 10.0586 3.7474 10.0586C3.87761 10.0586 3.9974 10.0065 4.08594 9.92318L7.79427 6.13152L11.5026 9.92318C11.5911 10.0065 11.7057 10.0586 11.8412 10.0586C12.112 10.0586 12.3151 9.85026 12.3151 9.58464C12.3151 9.44922 12.2682 9.33464 12.1745 9.24089L8.13802 5.11587C8.03906 5.01694 7.92449 4.96485 7.79427 4.96485Z"
+ fill="#333333"
+ ></path>
+ </svg>
+ </symbol>
</defs>
</svg>
- </head>
-
- <body onload="showSDK()">
- <div class="page-spinner hidden" id="page-spinner"></div>
+ <div id="page-spinner" class="page-spinner hidden">
+ <div class="spinner">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ </div>
+ </div>
<div class="hyper-checkout">
- <div class="main hidden" id="hyper-checkout-status">
- <div id="hyper-checkout-status-header"></div>
- <div id="hyper-checkout-status-content"></div>
+ <div class="main hidden" id="hyper-checkout-status-canvas">
+ <div class="hyper-checkout-status-wrap">
+ <div id="hyper-checkout-status-header"></div>
+ <div id="hyper-checkout-status-content"></div>
+ </div>
+ <div id="hyper-checkout-status-redirect-message"></div>
</div>
- <div class="main hidden" id="hyper-checkout-details">
- <div class="hyper-checkout-payment">
+ <div class="main" id="hyper-checkout-details">
+ <div id="hyper-checkout-payment" class="hyper-checkout-payment">
<div class="hyper-checkout-payment-content-details">
- <div id="hyper-checkout-payment-context">
- <div id="hyper-checkout-payment-merchant-details"></div>
- </div>
- <div class="hyper-checkout-image-header">
- <div id="hyper-checkout-merchant-image"></div>
- <div
- id="hyper-checkout-cart-image"
- onclick="viewCartInMobileView()"
- >
- <svg
- width="30"
- height="30"
- viewBox="0 0 30 30"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- class="cart-icon"
+ <div class="content-details-wrap">
+ <div id="hyper-checkout-payment-context">
+ <div id="hyper-checkout-payment-merchant-details"></div>
+ </div>
+ <div class="hyper-checkout-image-header">
+ <div id="hyper-checkout-merchant-image"></div>
+ <div
+ id="hyper-checkout-cart-image"
+ onclick="viewCartInMobileView()"
>
- <use
- xlink:href="#cart-icon-big"
- x="0"
- y="0"
+ <svg
width="30"
height="30"
- />
- </svg>
+ viewBox="0 0 30 30"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ class="cart-icon"
+ >
+ <use
+ xlink:href="#cart-icon-big"
+ x="0"
+ y="0"
+ width="30"
+ height="30"
+ ></use>
+ </svg>
+ </div>
</div>
</div>
+ <div id="hyper-checkout-payment-footer"></div>
</div>
- <div id="hyper-checkout-payment-footer"></div>
</div>
<div id="hyper-checkout-cart" class="">
- <div class="hyper-checkout-cart-header">
+ <div
+ id="hyper-checkout-cart-header"
+ class="hyper-checkout-cart-header"
+ >
<svg
width="16"
height="16"
@@ -790,7 +982,7 @@
y="0"
width="16"
height="16"
- />
+ ></use>
</svg>
<span>Your Cart</span>
<svg
@@ -807,61 +999,58 @@
y="0"
width="50"
height="50"
- />
+ ></use>
</svg>
</div>
<div id="hyper-checkout-cart-items" class="hide-scrollbar"></div>
+ <div id="hyper-checkout-merchant-description"></div>
+ <div class="powered-by-hyper">
+ <svg class="fill-current" height="18" width="130">
+ <use
+ xlink:href="#hyperswitch-brand"
+ x="0"
+ y="0"
+ height="18"
+ width="130"
+ ></use>
+ </svg>
+ </div>
</div>
</div>
- <div class="hyper-checkout-sdk hidden" id="hyper-checkout-sdk">
+ <div class="hyper-checkout-sdk" id="hyper-checkout-sdk">
<div id="payment-form-wrap">
- <form id="payment-form">
- <div id="unified-checkout">
- <div
- id="orca-element-unified-checkout"
- style="height: auto"
- class="payment base"
- >
- <div id="orca-fullscreen-iframeRef-unified-checkout"></div>
- <iframe
- id="orca-payment-element-iframeRef-unified-checkout"
- name="orca-payment-element-iframeRef-unified-checkout"
- src="http://localhost:9050/?componentName=payment"
- allow="payment *"
- style="
- border: 0px;
- transition: height 0.35s ease 0s, opacity 0.4s ease 0.1s;
- height: 368px;
- "
- width="100%"
- ></iframe>
- </div>
+ <div id="sdk-spinner" class="sdk-spinner">
+ <div class="spinner">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
</div>
+ </div>
+ <form id="payment-form">
+ <div id="unified-checkout"></div>
<div id="payment-message" class="hidden"></div>
</form>
</div>
- <div class="powered-by-hyper">
- <svg class="fill-current" height="18" width="130" transform="">
- <use
- xlink:href="#hyperswitch-brand"
- x="0"
- y="0"
- height="18"
- width="130"
- />
- </svg>
- </div>
</div>
</div>
<div id="hyper-footer" class="hidden">
- <svg class="fill-current" height="18" width="130" transform="">
+ <svg class="fill-current" height="18" width="130">
<use
xlink:href="#hyperswitch-brand"
x="0"
y="0"
height="18"
width="130"
- />
+ ></use>
</svg>
</div>
@@ -872,25 +1061,152 @@
prevHeight: window.innerHeight,
prevWidth: window.innerWidth,
isMobileView: window.innerWidth <= 1200,
+ currentScreen: "payment_link",
};
var widgets = null;
var unifiedCheckout = null;
var pub_key = window.__PAYMENT_DETAILS.pub_key;
- var hyper = Hyper(pub_key);
+ var hyper = null;
- function mountUnifiedCheckout(id) {
- if (unifiedCheckout !== null) {
- unifiedCheckout.mount(id);
+ // Boot functions
+ function boot() {
+ // Update HTML doc
+ var paymentDetails = window.__PAYMENT_DETAILS;
+
+ if (paymentDetails.merchant_name) {
+ document.title =
+ "Payment requested by " + paymentDetails.merchant_name;
+ }
+
+ if (paymentDetails.merchant_logo) {
+ var link = document.createElement("link");
+ link.rel = "icon";
+ link.href = paymentDetails.merchant_logo;
+ link.type = "image/x-icon";
+ document.head.appendChild(link);
+ }
+
+ // Render UI
+ renderPaymentDetails();
+ renderSDKHeader();
+ renderCart();
+
+ // Deal w loaders
+ show("#sdk-spinner");
+ hide("#page-spinner");
+ hide("#unified-checkout");
+
+ // Add event listeners
+ initializeEventListeners();
+
+ // Initialize SDK
+ if (window.Hyper) {
+ initializeSDK();
+ }
+
+ // State specific functions
+ if (window.state.isMobileView) {
+ show("#hyper-footer");
+ hide("#hyper-checkout-cart");
+ } else {
+ show("#hyper-checkout-cart");
}
}
+ boot();
+
+ function initializeEventListeners() {
+ var primaryColor = window
+ .getComputedStyle(document.documentElement)
+ .getPropertyValue("--primary-color");
+ var lighterColor = adjustLightness(primaryColor, 1.4);
+ var darkerColor = adjustLightness(primaryColor, 0.8);
+ var contrastBWColor = invert(primaryColor, true);
+ var hyperCheckoutNode = document.getElementById(
+ "hyper-checkout-payment"
+ );
+ var hyperCheckoutFooterNode = document.getElementById(
+ "hyper-checkout-payment-footer"
+ );
+ var statusRedirectTextNode = document.getElementById(
+ "hyper-checkout-status-redirect-message"
+ );
+
+ if (window.innerWidth <= 1200) {
+ statusRedirectTextNode.style.color = "#333333";
+ hyperCheckoutNode.style.color = contrastBWColor;
+ var a = lighterColor.match(/[fF]/gi);
+ hyperCheckoutFooterNode.style.backgroundColor =
+ Array.isArray(a) && a.length > 4 ? darkerColor : lighterColor;
+ } else if (window.innerWidth > 1200) {
+ statusRedirectTextNode.style.color = contrastBWColor;
+ hyperCheckoutNode.style.color = "#333333";
+ hyperCheckoutFooterNode.style.backgroundColor = "#F5F5F5";
+ }
- async function initialize() {
+ window.addEventListener("resize", function (event) {
+ var currentHeight = window.innerHeight;
+ var currentWidth = window.innerWidth;
+ if (currentWidth <= 1200 && window.state.prevWidth > 1200) {
+ hide("#hyper-checkout-cart");
+ if (window.state.currentScreen === "payment_link") {
+ show("#hyper-footer");
+ }
+ try {
+ statusRedirectTextNode.style.color = "#333333";
+ hyperCheckoutNode.style.color = contrastBWColor;
+ hyperCheckoutFooterNode.style.backgroundColor = lighterColor;
+ } catch (error) {
+ console.error(
+ "Failed to fetch primary-color, using default",
+ error
+ );
+ }
+ } else if (currentWidth > 1200 && window.state.prevWidth <= 1200) {
+ if (window.state.currentScreen === "payment_link") {
+ hide("#hyper-footer");
+ }
+ show("#hyper-checkout-cart");
+ try {
+ statusRedirectTextNode.style.color = contrastBWColor;
+ hyperCheckoutNode.style.color = "#333333";
+ hyperCheckoutFooterNode.style.backgroundColor = "#F5F5F5";
+ } catch (error) {
+ console.error("Failed to revert back to default colors", error);
+ }
+ }
+
+ window.state.prevHeight = currentHeight;
+ window.state.prevWidth = currentWidth;
+ window.state.isMobileView = currentWidth <= 1200;
+ });
+ }
+
+ function showSDK() {
+ checkStatus()
+ .then(function (res) {
+ if (res.showSdk) {
+ show("#hyper-checkout-sdk");
+ show("#hyper-checkout-details");
+ } else {
+ hide("#hyper-checkout-details");
+ hide("#hyper-checkout-sdk");
+ show("#hyper-checkout-status-canvas");
+ hide("#hyper-footer");
+ window.state.currentScreen = "status";
+ }
+ })
+ .catch(function (err) {
+ console.error("Failed to check status", err);
+ });
+ }
+
+ function initializeSDK() {
var paymentDetails = window.__PAYMENT_DETAILS;
var client_secret = paymentDetails.client_secret;
var appearance = {
variables: {
- colorPrimary: paymentDetails.sdk_theme || "rgb(0, 109, 249)",
+ colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)",
fontFamily: "Work Sans, sans-serif",
fontSizeBase: "16px",
colorText: "rgb(51, 65, 85)",
@@ -901,12 +1217,11 @@
colorBackground: "rgb(255, 255, 255)",
},
};
-
+ hyper = window.Hyper(pub_key);
widgets = hyper.widgets({
- appearance,
+ appearance: appearance,
clientSecret: client_secret,
});
-
var unifiedCheckoutOptions = {
layout: "tabs",
sdkHandleConfirmPayment: true,
@@ -920,10 +1235,29 @@
},
},
};
-
unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
mountUnifiedCheckout("#unified-checkout");
+ // Add event listener for SDK iframe mutations
+ var orcaIFrame = document.getElementById(
+ "orca-payment-element-iframeRef-unified-checkout"
+ );
+ var callback = function (mutationList, observer) {
+ for (var i = 0; i < mutationList.length; i++) {
+ var mutation = mutationList[i];
+
+ if (
+ mutation.type === "attributes" &&
+ mutation.attributeName === "style"
+ ) {
+ show("#unified-checkout");
+ hide("#sdk-spinner");
+ }
+ }
+ };
+ var observer = new MutationObserver(callback);
+ observer.observe(orcaIFrame, { attributes: true });
+
// Handle button press callback
var paymentElement = widgets.getElement("payment");
if (paymentElement) {
@@ -931,111 +1265,132 @@
handleSubmit(event);
});
}
+ showSDK();
}
- initialize();
-
- async function handleSubmit(e) {
- var paymentDetails = window.__PAYMENT_DETAILS;
- var { error, data, status } = await hyper.confirmPayment({
- widgets,
- confirmParams: {
- // Make sure to change this to your payment completion page
- return_url: paymentDetails.return_url,
- },
- });
- // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your 'return_url'.
- // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the 'return_url'.
-
- if (error) {
- if (error.type === "validation_error") {
- showMessage(error.message);
- } else {
- showMessage("An unexpected error occurred.");
- }
- // Re-initialize SDK
- mountUnifiedCheckout("#unified-checkout");
- } else {
- var { paymentIntent } = await hyper.retrievePaymentIntent(
- paymentDetails.client_secret
- );
- if (paymentIntent && paymentIntent.status) {
- hide("#hyper-checkout-sdk");
- hide("#hyper-checkout-details");
- show("#hyper-checkout-status");
- show("#hyper-footer");
- showStatus(paymentIntent);
- }
+ // Util functions
+ function mountUnifiedCheckout(id) {
+ if (unifiedCheckout !== null) {
+ unifiedCheckout.mount(id);
}
}
- // Fetches the payment status after payment submission
- async function checkStatus() {
+ function handleSubmit(e) {
var paymentDetails = window.__PAYMENT_DETAILS;
- var res = {
- showSdk: true,
- };
-
- let clientSecret = new URLSearchParams(window.location.search).get(
- "payment_intent_client_secret"
- );
-
- // If clientSecret is not found in URL params, try to fetch from window context
- if (!clientSecret) {
- clientSecret = paymentDetails.client_secret;
- }
+ hyper
+ .confirmPayment({
+ widgets: widgets,
+ confirmParams: {
+ // Make sure to change this to your payment completion page
+ return_url: paymentDetails.return_url,
+ },
+ })
+ .then(function (result) {
+ var error = result.error;
+ if (error) {
+ if (error.type === "validation_error") {
+ showMessage(error.message);
+ } else {
+ showMessage("An unexpected error occurred.");
+ }
- // If clientSecret is not present, show status
- if (!clientSecret) {
- res.showSdk = false;
- showStatus(
- Object.assign({}, paymentDetails, {
- status: "",
- error: {
- code: "NO_CLIENT_SECRET",
- message: "client_secret not found",
- },
- })
- );
- return res;
- }
+ // Re-initialize SDK
+ mountUnifiedCheckout("#unified-checkout");
+ } else {
+ // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your 'return_url'.
+ // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the 'return_url'.
+ hyper
+ .retrievePaymentIntent(paymentDetails.client_secret)
+ .then(function (result) {
+ var paymentIntent = result.paymentIntent;
+ if (paymentIntent && paymentIntent.status) {
+ hide("#hyper-checkout-sdk");
+ hide("#hyper-checkout-details");
+ show("#hyper-checkout-status-canvas");
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, paymentIntent)
+ );
+ }
+ })
+ .catch(function (error) {
+ console.error("Error retrieving payment_intent", error);
+ });
+ }
+ })
+ .catch(function (error) {
+ console.error("Error confirming payment_intent", error);
+ });
+ }
- var { paymentIntent } = await hyper.retrievePaymentIntent(clientSecret);
-
- // If paymentIntent was not found, show status
- if (!paymentIntent) {
- res.showSdk = false;
- showStatus(
- Object.assign({}, paymentDetails, {
- status: "",
- error: {
- code: "NOT_FOUND",
- message: "PaymentIntent was not found",
- },
- })
+ // Fetches the payment status after payment submission
+ function checkStatus() {
+ return new window.Promise(function (resolve, reject) {
+ var paymentDetails = window.__PAYMENT_DETAILS;
+ var res = {
+ showSdk: true,
+ };
+
+ var clientSecret = new URLSearchParams(window.location.search).get(
+ "payment_intent_client_secret"
);
- return res;
- }
-
- // Show SDK only if paymentIntent status has not been initiated
- switch (paymentIntent.status) {
- case "requires_confirmation":
- case "requires_payment_method":
- return res;
- }
- showStatus(paymentIntent);
- res.showSdk = false;
-
- return res;
- }
+ // If clientSecret is not found in URL params, try to fetch from window context
+ if (!clientSecret) {
+ clientSecret = paymentDetails.client_secret;
+ }
- function setPageLoading(showLoader) {
- if (showLoader) {
- show(".page-spinner");
- } else {
- hide(".page-spinner");
- }
+ // If clientSecret is not present, show status
+ if (!clientSecret) {
+ res.showSdk = false;
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, {
+ status: "",
+ error: {
+ code: "NO_CLIENT_SECRET",
+ message: "client_secret not found",
+ },
+ })
+ );
+ return resolve(res);
+ }
+ hyper
+ .retrievePaymentIntent(clientSecret)
+ .then(function (response) {
+ var paymentIntent = response.paymentIntent;
+ // If paymentIntent was not found, show status
+ if (!paymentIntent) {
+ res.showSdk = false;
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, {
+ status: "",
+ error: {
+ code: "NOT_FOUND",
+ message: "PaymentIntent was not found",
+ },
+ })
+ );
+ return resolve(res);
+ }
+ // Show SDK only if paymentIntent status has not been initiated
+ switch (paymentIntent.status) {
+ case "requires_confirmation":
+ case "requires_payment_method":
+ return resolve(res);
+ }
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, paymentIntent)
+ );
+ res.showSdk = false;
+ resolve(res);
+ })
+ .catch(function (error) {
+ reject(error);
+ });
+ });
}
function show(id) {
@@ -1050,9 +1405,9 @@
addText("#payment-message", msg);
}
- function showStatus(paymentDetails) {
+ function showStatus(amount, paymentDetails) {
var status = paymentDetails.status;
- let statusDetails = {
+ var statusDetails = {
imageSource: "",
message: null,
status: status,
@@ -1142,8 +1497,7 @@
// Form header items
var amountNode = document.createElement("div");
amountNode.className = "hyper-checkout-status-amount";
- amountNode.innerText =
- paymentDetails.currency + " " + paymentDetails.amount;
+ amountNode.innerText = paymentDetails.currency + " " + amount;
var merchantLogoNode = document.createElement("img");
merchantLogoNode.className = "hyper-checkout-status-merchant-logo";
merchantLogoNode.src = window.__PAYMENT_DETAILS.merchant_logo;
@@ -1163,23 +1517,72 @@
statusDetailsNode.className = "hyper-checkout-status-details";
// Append items
- statusDetails.items.map((item) => statusDetailsNode?.append(item));
+ if (statusDetailsNode instanceof HTMLDivElement) {
+ statusDetails.items.map(function (item) {
+ statusDetailsNode.append(item);
+ });
+ }
var statusHeaderNode = document.getElementById(
"hyper-checkout-status-header"
);
- if (statusHeaderNode !== null) {
+ if (statusHeaderNode instanceof HTMLDivElement) {
statusHeaderNode.append(amountNode, merchantLogoNode);
}
var statusContentNode = document.getElementById(
"hyper-checkout-status-content"
);
- if (statusContentNode !== null) {
+ if (statusContentNode instanceof HTMLDivElement) {
statusContentNode.append(statusImageNode, statusTextNode);
- if (statusDetails.message !== null) {
+ if (statusDetails.message instanceof HTMLDivElement) {
statusContentNode.append(statusMessageNode);
}
statusContentNode.append(statusDetailsNode);
}
+
+ // Form redirect text
+ var statusRedirectTextNode = document.getElementById(
+ "hyper-checkout-status-redirect-message"
+ );
+ if (
+ statusRedirectTextNode &&
+ typeof paymentDetails.return_url === "string"
+ ) {
+ var timeout = 5,
+ j = 0;
+ for (var i = 0; i <= timeout; i++) {
+ setTimeout(function () {
+ var secondsLeft = timeout - j++;
+ var innerText =
+ secondsLeft === 0
+ ? "Redirecting ..."
+ : "Redirecting in " + secondsLeft + " seconds ...";
+ statusRedirectTextNode.innerText = innerText;
+ if (secondsLeft === 0) {
+ // Form query params
+ var queryParams = {
+ payment_id: paymentDetails.payment_id,
+ status: paymentDetails.status,
+ payment_intent_client_secret: paymentDetails.client_secret,
+ amount: amount,
+ manual_retry_allowed: paymentDetails.manual_retry_allowed,
+ };
+ var url = new URL(paymentDetails.return_url);
+ var params = new URLSearchParams(url.search);
+ // Attach query params to return_url
+ for (var key in queryParams) {
+ if (queryParams.hasOwnProperty(key)) {
+ params.set(key, queryParams[key]);
+ }
+ }
+ url.search = params.toString();
+ setTimeout(function () {
+ // Finally redirect
+ window.location.href = url.toString();
+ }, 1000);
+ }
+ }, i * 1000);
+ }
+ }
}
function createItem(heading, value) {
@@ -1211,6 +1614,61 @@
element.classList.remove(className);
}
+ function formatDate(date) {
+ var months = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+ ];
+
+ var hours = date.getHours();
+ var minutes = date.getMinutes();
+ minutes = minutes < 10 ? "0" + minutes : minutes;
+ var suffix = hours > 11 ? "PM" : "AM";
+ hours = hours % 12;
+ hours = hours ? hours : 12;
+ var day = date.getDate();
+ var month = months[date.getMonth()];
+ var year = date.getUTCFullYear();
+
+ var locale = navigator.language || navigator.userLanguage;
+ var timezoneShorthand = date
+ .toLocaleDateString(locale, {
+ day: "2-digit",
+ timeZoneName: "long",
+ })
+ .substring(4)
+ .split(" ")
+ .reduce(function (tz, c) {
+ return tz + c.charAt(0).toUpperCase();
+ }, "");
+
+ var formatted =
+ hours +
+ ":" +
+ minutes +
+ " " +
+ suffix +
+ " " +
+ timezoneShorthand +
+ " " +
+ month +
+ " " +
+ day +
+ ", " +
+ year;
+ return formatted;
+ }
+
function renderPaymentDetails() {
var paymentDetails = window.__PAYMENT_DETAILS;
@@ -1238,8 +1696,9 @@
// Create expiry node
var paymentExpiryNode = document.createElement("div");
paymentExpiryNode.className = "hyper-checkout-payment-footer-expiry";
- paymentExpiryNode.innerText =
- "Link expires on: " + new Date(paymentDetails.expiry).toTimeString();
+ var expiryDate = new Date(paymentDetails.session_expiry);
+ var formattedDate = formatDate(expiryDate);
+ paymentExpiryNode.innerText = "Link expires on: " + formattedDate;
// Append information to DOM
var paymentContextNode = document.getElementById(
@@ -1264,17 +1723,17 @@
function renderCart() {
var paymentDetails = window.__PAYMENT_DETAILS;
var orderDetails = paymentDetails.order_details;
- var cartNode = document.getElementById("hyper-checkout-cart");
- var cartItemsNode = document.getElementById(
- "hyper-checkout-cart-items"
- );
-
- var MAX_ITEMS_VISIBLE_AFTER_COLLAPSE =
- paymentDetails.max_items_visible_after_collapse;
// Cart items
- if (Array.isArray(orderDetails)) {
- orderDetails.map((item, index) => {
+ if (Array.isArray(orderDetails) && orderDetails.length > 0) {
+ var cartNode = document.getElementById("hyper-checkout-cart");
+ var cartItemsNode = document.getElementById(
+ "hyper-checkout-cart-items"
+ );
+ var MAX_ITEMS_VISIBLE_AFTER_COLLAPSE =
+ paymentDetails.max_items_visible_after_collapse;
+
+ orderDetails.map(function (item, index) {
if (index >= MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
@@ -1285,22 +1744,38 @@
cartItemsNode
);
});
- }
-
- // Expand / collapse button
- var totalItems = orderDetails.length;
- if (totalItems > MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
- var expandButtonNode = document.createElement("div");
- expandButtonNode.className = "hyper-checkout-cart-button";
- expandButtonNode.onclick = handleCartView;
- var buttonImageNode = document.createElement("img");
- var buttonTextNode = document.createElement("span");
- buttonTextNode.id = "hyper-checkout-cart-button-text";
- var hiddenItemsCount =
- orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
- buttonTextNode.innerText = "Show More (" + hiddenItemsCount + ")";
- expandButtonNode.append(buttonTextNode, buttonImageNode);
- cartNode.append(expandButtonNode);
+ // Expand / collapse button
+ var totalItems = orderDetails.length;
+ if (totalItems > MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
+ var expandButtonNode = document.createElement("div");
+ expandButtonNode.className = "hyper-checkout-cart-button";
+ expandButtonNode.onclick = handleCartView;
+ var buttonImageNode = document.createElement("svg");
+ buttonImageNode.id = "hyper-checkout-cart-button-arrow";
+ buttonImageNode.innerHTML =
+ document.getElementById("arrow-down").innerHTML;
+ var buttonTextNode = document.createElement("span");
+ buttonTextNode.id = "hyper-checkout-cart-button-text";
+ var hiddenItemsCount =
+ orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
+ buttonTextNode.innerText = "Show More (" + hiddenItemsCount + ")";
+ expandButtonNode.append(buttonTextNode, buttonImageNode);
+ cartNode.insertBefore(expandButtonNode, cartNode.lastElementChild);
+ }
+ } else {
+ hide("#hyper-checkout-cart-header");
+ hide("#hyper-checkout-cart-items");
+ hide("#hyper-checkout-cart-image");
+ if (
+ typeof paymentDetails.merchant_description === "string" &&
+ paymentDetails.merchant_description.length > 0
+ ) {
+ show("#hyper-checkout-merchant-description");
+ var merchantDescription = paymentDetails.merchant_description;
+ document.getElementById(
+ "hyper-checkout-merchant-description"
+ ).innerText = merchantDescription;
+ }
}
}
@@ -1367,9 +1842,12 @@
var cartButtonTextNode = document.getElementById(
"hyper-checkout-cart-button-text"
);
+ var cartButtonImageNode = document.getElementById(
+ "hyper-checkout-cart-button-arrow"
+ );
if (isHidden) {
if (Array.isArray(orderDetails)) {
- orderDetails.map((item, index) => {
+ orderDetails.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
@@ -1384,18 +1862,20 @@
cartItemsNode.style.maxHeight = cartItemsNode.scrollHeight + "px";
cartItemsNode.style.height = cartItemsNode.scrollHeight + "px";
cartButtonTextNode.innerText = "Show Less";
+ cartButtonImageNode.innerHTML =
+ document.getElementById("arrow-up").innerHTML;
} else {
- cartItemsNode.style.maxHeight = "354px";
- cartItemsNode.style.height = "354px";
+ cartItemsNode.style.maxHeight = "300px";
+ cartItemsNode.style.height = "290px";
cartItemsNode.scrollTo({ top: 0, behavior: "smooth" });
setTimeout(function () {
- cartItems.map((item, index) => {
+ cartItems.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
cartItemsNode.removeChild(item);
});
- dividerItems.map((item, index) => {
+ dividerItems.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE - 1) {
return;
}
@@ -1407,6 +1887,8 @@
orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
cartButtonTextNode.innerText =
"Show More (" + hiddenItemsCount + ")";
+ cartButtonImageNode.innerHTML =
+ document.getElementById("arrow-down").innerHTML;
}, 250);
}
}
@@ -1450,53 +1932,168 @@
var sdkHeaderNode = document.getElementById(
"hyper-checkout-sdk-header"
);
- if (sdkHeaderNode !== null) {
+ if (sdkHeaderNode instanceof HTMLDivElement) {
sdkHeaderNode.append(sdkHeaderLogoNode);
sdkHeaderNode.append(sdkHeaderItemNode);
}
}
- function showSDK(e) {
- if (window.state.isMobileView) {
- hide("#hyper-checkout-cart");
+ function adjustLightness(hexColor, factor) {
+ // Convert hex to RGB
+ var r = parseInt(hexColor.slice(1, 3), 16);
+ var g = parseInt(hexColor.slice(3, 5), 16);
+ var b = parseInt(hexColor.slice(5, 7), 16);
+
+ // Convert RGB to HSL
+ var hsl = rgbToHsl(r, g, b);
+
+ // Adjust lightness
+ hsl[2] = Math.max(0, Math.min(100, hsl[2] * factor));
+
+ // Convert HSL back to RGB
+ var rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
+
+ // Convert RGB to hex
+ var newHexColor = rgbToHex(rgb[0], rgb[1], rgb[2]);
+
+ return newHexColor;
+ }
+ function rgbToHsl(r, g, b) {
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ var max = Math.max(r, g, b),
+ min = Math.min(r, g, b);
+ var h,
+ s,
+ l = (max + min) / 2;
+
+ if (max === min) {
+ h = s = 0;
} else {
- show("#hyper-checkout-cart");
+ var d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
}
- setPageLoading(true);
- checkStatus()
- .then((res) => {
- if (res.showSdk) {
- renderPaymentDetails();
- renderCart();
- renderSDKHeader();
- show("#hyper-checkout-sdk");
- show("#hyper-checkout-details");
- } else {
- hide("#hyper-checkout-sdk");
- hide("#hyper-checkout-details");
- show("#hyper-checkout-status");
- show("#hyper-footer");
- }
- })
- .catch((err) => {})
- .finally(() => {
- setPageLoading(false);
- });
+
+ return [h * 360, s * 100, l * 100];
}
+ function hslToRgb(h, s, l) {
+ h /= 360;
+ s /= 100;
+ l /= 100;
+ var r, g, b;
- window.addEventListener("resize", (event) => {
- var currentHeight = window.innerHeight;
- var currentWidth = window.innerWidth;
- if (currentWidth <= 1200 && window.state.prevWidth > 1200) {
- hide("#hyper-checkout-cart");
- } else if (currentWidth > 1200 && window.state.prevWidth <= 1200) {
- show("#hyper-checkout-cart");
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ var hue2rgb = function (p, q, t) {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+ };
+
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+
+ r = hue2rgb(p, q, h + 1 / 3);
+ g = hue2rgb(p, q, h);
+ b = hue2rgb(p, q, h - 1 / 3);
}
- window.state.prevHeight = currentHeight;
- window.state.prevWidth = currentWidth;
- window.state.isMobileView = currentWidth <= 1200;
- });
+ return [r * 255, g * 255, b * 255];
+ }
+ function rgbToHex(r, g, b) {
+ var toHex = function (c) {
+ var hex = Math.round(c).toString(16);
+ return hex.length === 1 ? "0" + hex : hex;
+ };
+ return "#" + toHex(r) + toHex(g) + toHex(b);
+ }
+
+ /**
+ * Ref - https://github.com/onury/invert-color/blob/master/lib/cjs/invert.js
+ */
+ function padz(str, len) {
+ if (len === void 0) {
+ len = 2;
+ }
+ return (new Array(len).join("0") + str).slice(-len);
+ }
+ function hexToRgbArray(hex) {
+ if (hex.slice(0, 1) === "#") hex = hex.slice(1);
+ var RE_HEX = /^(?:[0-9a-f]{3}){1,2}$/i;
+ if (!RE_HEX.test(hex))
+ throw new Error('Invalid HEX color: "' + hex + '"');
+ if (hex.length === 3) {
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
+ }
+ return [
+ parseInt(hex.slice(0, 2), 16),
+ parseInt(hex.slice(2, 4), 16),
+ parseInt(hex.slice(4, 6), 16),
+ ];
+ }
+ function toRgbArray(c) {
+ if (!c) throw new Error("Invalid color value");
+ if (Array.isArray(c)) return c;
+ return typeof c === "string" ? hexToRgbArray(c) : [c.r, c.g, c.b];
+ }
+ function getLuminance(c) {
+ var i, x;
+ var a = [];
+ for (i = 0; i < c.length; i++) {
+ x = c[i] / 255;
+ a[i] = x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
+ }
+ return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
+ }
+ function invertToBW(color, bw, asArr) {
+ var DEFAULT_BW = {
+ black: "#090302",
+ white: "#FFFFFC",
+ threshold: Math.sqrt(1.05 * 0.05) - 0.05,
+ };
+ var options =
+ bw === true ? DEFAULT_BW : Object.assign({}, DEFAULT_BW, bw);
+ return getLuminance(color) > options.threshold
+ ? asArr
+ ? hexToRgbArray(options.black)
+ : options.black
+ : asArr
+ ? hexToRgbArray(options.white)
+ : options.white;
+ }
+ function invert(color, bw) {
+ if (bw === void 0) {
+ bw = false;
+ }
+ color = toRgbArray(color);
+ if (bw) return invertToBW(color, bw);
+ return (
+ "#" +
+ color
+ .map(function (c) {
+ return padz((255 - c).toString(16));
+ })
+ .join("")
+ );
+ }
</script>
+ {{ hyperloader_sdk_link }}
</body>
</html>
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index aaecd86627..39bc54fa15 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -21,7 +21,10 @@ use common_utils::{
ext_traits::{AsyncExt, StringExt, ValueExt},
generate_id,
};
-use diesel_models::{encryption::Encryption, enums as storage_enums, payment_method};
+use diesel_models::{
+ business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
+ payment_method,
+};
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
@@ -44,6 +47,7 @@ use crate::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
+ utils as core_utils,
},
db, logger,
pii::prelude::*,
@@ -1077,6 +1081,12 @@ pub async fn list_payment_methods(
})
.await
.transpose()?;
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ profile_id.as_ref(),
+ &merchant_account.merchant_id,
+ )
+ .await?;
// filter out connectors based on the business country
let filtered_mcas = helpers::filter_mca_based_on_business_profile(all_mcas, profile_id);
@@ -1690,13 +1700,18 @@ pub async fn list_payment_methods(
payment_method_types: bank_transfer_payment_method_types,
});
}
-
let merchant_surcharge_configs =
- if let Some((attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent) {
+ if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
+ .as_ref()
+ .zip(payment_intent)
+ .zip(business_profile)
+ .map(|((pa, pi), bp)| (pa, pi, bp))
+ {
Box::pin(call_surcharge_decision_management(
state,
&merchant_account,
- attempt,
+ &business_profile,
+ payment_attempt,
payment_intent,
billing_address,
&mut payment_method_responses,
@@ -1705,7 +1720,6 @@ pub async fn list_payment_methods(
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
-
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: merchant_account.return_url,
@@ -1747,6 +1761,7 @@ pub async fn list_payment_methods(
pub async fn call_surcharge_decision_management(
state: routes::AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
billing_address: Option<domain::Address>,
@@ -1777,7 +1792,7 @@ pub async fn call_surcharge_decision_management(
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
- .persist_individual_surcharge_details_in_redis(&state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(&state, business_profile)
.await?;
let _ = state
.store
@@ -1800,6 +1815,7 @@ pub async fn call_surcharge_decision_management(
pub async fn call_surcharge_decision_management_for_saved_card(
state: &routes::AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
customer_payment_method_response: &mut api::CustomerPaymentMethodsListResponse,
@@ -1827,7 +1843,7 @@ pub async fn call_surcharge_decision_management_for_saved_card(
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
- .persist_individual_surcharge_details_in_redis(state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
let _ = state
.store
@@ -2536,10 +2552,38 @@ pub async fn list_customer_payment_method(
.await
.transpose()?;
- if let Some((payment_attempt, payment_intent)) = payment_attempt.zip(payment_intent) {
+ let profile_id = payment_intent
+ .as_ref()
+ .async_map(|payment_intent| async {
+ crate::core::utils::get_profile_id_from_business_details(
+ payment_intent.business_country,
+ payment_intent.business_label.as_ref(),
+ &merchant_account,
+ payment_intent.profile_id.as_ref(),
+ db,
+ false,
+ )
+ .await
+ .attach_printable("Could not find profile id from business details")
+ })
+ .await
+ .transpose()?;
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ profile_id.as_ref(),
+ &merchant_account.merchant_id,
+ )
+ .await?;
+
+ if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
+ .zip(payment_intent)
+ .zip(business_profile)
+ .map(|((pa, pi), bp)| (pa, pi, bp))
+ {
call_surcharge_decision_management_for_saved_card(
state,
&merchant_account,
+ &business_profile,
&payment_attempt,
payment_intent,
&mut response,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 62d66926ef..04e947d36e 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -337,6 +337,7 @@ where
call_surcharge_decision_management_for_session_flow(
state,
&merchant_account,
+ &business_profile,
&mut payment_data,
&connectors,
)
@@ -570,6 +571,7 @@ pub fn get_connector_data(
pub async fn call_surcharge_decision_management_for_session_flow<O>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &diesel_models::business_profile::BusinessProfile,
payment_data: &mut PaymentData<O>,
session_connector_data: &[api::SessionConnectorData],
) -> RouterResult<Option<api::SessionSurchargeDetails>>
@@ -615,7 +617,7 @@ where
.attach_printable("error performing surcharge decision operation")?;
surcharge_results
- .persist_individual_surcharge_details_in_redis(state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
Ok(if surcharge_results.is_empty_result() {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 08e2e5dab1..29e59a1af7 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -23,7 +23,6 @@ use openssl::{
symm::{decrypt_aead, Cipher},
};
use router_env::{instrument, logger, tracing};
-use time::Duration;
use uuid::Uuid;
use x509_parser::parse_x509_certificate;
@@ -2377,24 +2376,23 @@ pub fn generate_mandate(
pub fn authenticate_client_secret(
request_client_secret: Option<&String>,
payment_intent: &PaymentIntent,
- merchant_intent_fulfillment_time: Option<i64>,
) -> Result<(), errors::ApiErrorResponse> {
match (request_client_secret, &payment_intent.client_secret) {
(Some(req_cs), Some(pi_cs)) => {
if req_cs != pi_cs {
Err(errors::ApiErrorResponse::ClientSecretInvalid)
} else {
- //This is done to check whether the merchant_account's intent fulfillment time has expired or not
- let payment_intent_fulfillment_deadline =
- payment_intent.created_at.saturating_add(Duration::seconds(
- merchant_intent_fulfillment_time
- .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME),
- ));
let current_timestamp = common_utils::date_time::now();
- fp_utils::when(
- current_timestamp > payment_intent_fulfillment_deadline,
- || Err(errors::ApiErrorResponse::ClientSecretExpired),
- )
+
+ let session_expiry = payment_intent.session_expiry.unwrap_or(
+ payment_intent
+ .created_at
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ );
+
+ fp_utils::when(current_timestamp > session_expiry, || {
+ Err(errors::ApiErrorResponse::ClientSecretExpired)
+ })
}
}
// If there is no client in payment intent, then it has expired
@@ -2403,26 +2401,6 @@ pub fn authenticate_client_secret(
}
}
-pub async fn get_merchant_fullfillment_time(
- payment_link_id: Option<String>,
- intent_fulfillment_time: Option<i64>,
- db: &dyn StorageInterface,
-) -> RouterResult<Option<i64>> {
- if let Some(payment_link_id) = payment_link_id {
- let payment_link_db = db
- .find_payment_link_by_payment_link_id(&payment_link_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
-
- let curr_time = common_utils::date_time::now();
- Ok(payment_link_db
- .fulfilment_time
- .map(|merchant_expiry_time| (merchant_expiry_time - curr_time).whole_seconds()))
- } else {
- Ok(intent_fulfillment_time)
- }
-}
-
pub(crate) fn validate_payment_status_against_allowed_statuses(
intent_status: &storage_enums::IntentStatus,
allowed_statuses: &[storage_enums::IntentStatus],
@@ -2495,14 +2473,7 @@ pub async fn verify_payment_intent_time_and_client_secret(
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let intent_fulfillment_time = get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- authenticate_client_secret(Some(&cs), &payment_intent, intent_fulfillment_time)?;
+ authenticate_client_secret(Some(&cs), &payment_intent)?;
Ok(payment_intent)
})
.await
@@ -2634,15 +2605,14 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(900);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_ok()); // Check if the result is an Ok variant
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
+ // Check if the result is an Ok variant
}
#[test]
@@ -2664,7 +2634,7 @@ mod tests {
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)),
+ created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
@@ -2689,15 +2659,13 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(10);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_err())
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
}
#[test]
@@ -2719,7 +2687,7 @@ mod tests {
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)),
+ created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
@@ -2744,15 +2712,13 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(10);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_err())
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
}
}
@@ -3732,22 +3698,11 @@ pub fn get_key_params_for_surcharge_details(
}
pub fn validate_payment_link_request(
- payment_link_object: &api_models::payments::PaymentLinkObject,
confirm: Option<bool>,
- order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
) -> Result<(), errors::ApiErrorResponse> {
if let Some(cnf) = confirm {
if !cnf {
- let current_time = Some(common_utils::date_time::now());
- if current_time > payment_link_object.link_expiry {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "link_expiry time cannot be less than current time".to_string(),
- });
- } else if order_details.is_none() {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "cannot create payment link without order details".to_string(),
- });
- }
+ return Ok(());
} else {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "cannot confirm a payment while creating a payment link".to_string(),
@@ -3818,3 +3773,14 @@ pub fn validate_order_details_amount(
Ok(())
}
}
+
+// This function validates the client secret expiry set by the merchant in the request
+pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> {
+ if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(),
+ })
+ } else {
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 58983f264c..6a50abc543 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -50,7 +50,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
- let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
let (currency, amount);
@@ -122,18 +121,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"confirm",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let customer_details = helpers::get_customer_details_from_request(request);
@@ -161,7 +149,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.await
});
- let store = state.clone().store;
+ let store = state.store.clone();
+
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
@@ -774,6 +763,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let m_metadata = metadata.clone();
let m_db = state.clone().store;
let m_storage_scheme = storage_scheme.to_string();
+ let session_expiry = m_payment_data_payment_intent.session_expiry;
let payment_intent_fut = tokio::spawn(
async move {
@@ -797,6 +787,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
+ session_expiry,
},
storage_scheme,
)
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 798678e64d..6f4f10e0ab 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -6,14 +6,17 @@ use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt};
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
+use masking::PeekInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
+use time::PrimitiveDateTime;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_link,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -66,31 +69,36 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let payment_link_data = if let Some(payment_link_object) = &request.payment_link_object {
- create_payment_link(
- request,
- payment_link_object.clone(),
- merchant_id.clone(),
- payment_id.clone(),
- db,
- state,
- amount,
- request.description.clone(),
- )
- .await?
- } else {
- None
- };
-
helpers::validate_business_details(
request.business_country,
request.business_label.as_ref(),
merchant_account,
)?;
+ // If profile id is not passed, get it from the business_country and business_label
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ request.business_country,
+ request.business_label.as_ref(),
+ merchant_account,
+ request.profile_id.as_ref(),
+ &*state.store,
+ true,
+ )
+ .await?;
+
// Validate whether profile_id passed in request is valid and is linked to the merchant
- core_utils::validate_and_get_business_profile(db, request.profile_id.as_ref(), merchant_id)
- .await?;
+ let business_profile = if let Some(business_profile) =
+ core_utils::validate_and_get_business_profile(db, Some(&profile_id), merchant_id)
+ .await?
+ {
+ business_profile
+ } else {
+ db.find_business_profile_by_profile_id(&profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_string(),
+ })?
+ };
let (
token,
@@ -154,6 +162,52 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
utils::get_payment_attempt_id(payment_id.clone(), 1)
};
+ let session_expiry =
+ common_utils::date_time::now().saturating_add(time::Duration::seconds(
+ request.session_expiry.map(i64::from).unwrap_or(
+ business_profile
+ .session_expiry
+ .unwrap_or(consts::DEFAULT_SESSION_EXPIRY),
+ ),
+ ));
+
+ let payment_link_data = if let Some(payment_link_create) = request.payment_link {
+ if payment_link_create {
+ let merchant_name = merchant_account
+ .merchant_name
+ .clone()
+ .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
+ .unwrap_or_default();
+
+ let default_domain_name = state.conf.server.base_url.clone();
+
+ let (payment_link_config, domain_name) =
+ payment_link::get_payment_link_config_based_on_priority(
+ request.payment_link_config.clone(),
+ business_profile.payment_link_config.clone(),
+ merchant_name,
+ default_domain_name,
+ )?;
+ create_payment_link(
+ request,
+ payment_link_config,
+ merchant_id.clone(),
+ payment_id.clone(),
+ db,
+ amount,
+ request.description.clone(),
+ profile_id.clone(),
+ domain_name,
+ session_expiry,
+ )
+ .await?
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
let payment_intent_new = Self::make_payment_intent(
&payment_id,
merchant_account,
@@ -163,7 +217,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_link_data.clone(),
billing_address.clone().map(|x| x.address_id),
attempt_id,
- state,
+ profile_id,
+ session_expiry,
)
.await?;
@@ -200,20 +255,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_id: payment_id.clone(),
})?;
- let profile_id = payment_intent
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("'profile_id' not set in payment intent")?;
-
- let business_profile = db
- .find_business_profile_by_profile_id(profile_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
- id: profile_id.to_string(),
- })?;
-
let mandate_id = request
.mandate_id
.as_ref()
@@ -396,7 +437,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
_state: &'a AppState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
- _schedule_time: Option<time::PrimitiveDateTime>,
+ _schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -531,15 +572,16 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
-
- if let Some(payment_link_object) = &request.payment_link_object {
- helpers::validate_payment_link_request(
- payment_link_object,
- request.confirm,
- request.order_details.clone(),
- )?;
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
}
+ if let Some(payment_link) = &request.payment_link {
+ if *payment_link {
+ helpers::validate_payment_link_request(request.confirm)?;
+ }
+ };
+
let payment_id = request.payment_id.clone().ok_or(error_stack::report!(
errors::ApiErrorResponse::PaymentNotFound
))?;
@@ -697,7 +739,8 @@ impl PaymentCreate {
payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
billing_address_id: Option<String>,
active_attempt_id: String,
- state: &AppState,
+ profile_id: String,
+ session_expiry: PrimitiveDateTime,
) -> RouterResult<storage::PaymentIntentNew> {
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status =
@@ -711,17 +754,6 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
- // If profile id is not passed, get it from the business_country and business_label
- let profile_id = core_utils::get_profile_id_from_business_details(
- request.business_country,
- request.business_label.as_ref(),
- merchant_account,
- request.profile_id.as_ref(),
- &*state.store,
- true,
- )
- .await?;
-
let allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -784,6 +816,7 @@ impl PaymentCreate {
request_incremental_authorization,
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(session_expiry),
})
}
@@ -825,32 +858,31 @@ pub fn payments_create_request_validation(
#[allow(clippy::too_many_arguments)]
async fn create_payment_link(
request: &api::PaymentsRequest,
- payment_link_object: api_models::payments::PaymentLinkObject,
+ payment_link_config: api_models::admin::PaymentLinkConfig,
merchant_id: String,
payment_id: String,
db: &dyn StorageInterface,
- state: &AppState,
amount: api::Amount,
description: Option<String>,
+ profile_id: String,
+ domain_name: String,
+ session_expiry: PrimitiveDateTime,
) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> {
let created_at @ last_modified_at = Some(common_utils::date_time::now());
- let domain = if let Some(domain_name) = payment_link_object.merchant_custom_domain_name {
- format!("https://{domain_name}")
- } else {
- state.conf.server.base_url.clone()
- };
-
let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink");
let payment_link = format!(
"{}/payment_link/{}/{}",
- domain,
+ domain_name,
merchant_id.clone(),
payment_id.clone()
);
- let payment_link_config = payment_link_object.payment_link_config.map(|pl_config|{
- common_utils::ext_traits::Encode::<api_models::admin::PaymentLinkConfig>::encode_to_value(&pl_config)
- }).transpose().change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config" })?;
+ let payment_link_config_encoded_value = common_utils::ext_traits::Encode::<
+ api_models::admin::PaymentLinkConfig,
+ >::encode_to_value(&payment_link_config)
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })?;
let payment_link_req = storage::PaymentLinkNew {
payment_link_id: payment_link_id.clone(),
@@ -861,10 +893,11 @@ async fn create_payment_link(
currency: request.currency,
created_at,
last_modified_at,
- fulfilment_time: payment_link_object.link_expiry,
+ fulfilment_time: Some(session_expiry),
+ custom_merchant_name: Some(payment_link_config.seller_name),
description,
- payment_link_config,
- custom_merchant_name: payment_link_object.custom_merchant_name,
+ payment_link_config: Some(payment_link_config_encoded_value),
+ profile_id: Some(profile_id),
};
let payment_link_db = db
.insert_payment_link(payment_link_req)
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 6f7dcd6c11..49fad8f078 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -66,18 +66,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"create a session token for",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- Some(&request.client_secret),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(Some(&request.client_secret), &payment_intent)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 8896e4e43e..ea05cdcb74 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -66,17 +66,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"update",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
helpers::authenticate_client_secret(
payment_intent.client_secret.as_ref(),
&payment_intent,
- intent_fulfillment_time,
)?;
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index c5311ce3d0..e5db177c83 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -229,17 +229,7 @@ async fn get_tracker_for_sync<
)
.await?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let payment_id_str = payment_attempt.payment_id.clone();
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 153ded14f4..5019a66233 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -86,18 +86,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"update",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let (
token,
payment_method,
@@ -595,11 +584,12 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
.clone();
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
+ let session_expiry = payment_data.payment_intent.session_expiry;
payment_data.payment_intent = state
.store
.update_payment_intent(
- payment_data.payment_intent,
+ payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::Update {
amount: payment_data.amount.into(),
currency: payment_data.currency,
@@ -618,6 +608,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
metadata,
payment_confirm_source: None,
updated_by: storage_scheme.to_string(),
+ session_expiry,
},
storage_scheme,
)
@@ -646,6 +637,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
let payment_id = request
.payment_id
.clone()
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 00160db985..41a8850ab3 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -3,6 +3,7 @@ use std::{collections::HashMap, num::TryFromIntError};
use api_models::{payment_methods::SurchargeDetailsResponse, payments::RequestSurchargeDetails};
use common_utils::{consts, errors::CustomResult, ext_traits::Encode, types as common_types};
use data_models::payments::payment_attempt::PaymentAttempt;
+use diesel_models::business_profile::BusinessProfile;
use error_stack::{IntoReport, ResultExt};
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
@@ -12,7 +13,6 @@ use crate::{
core::errors::{self, RouterResult},
routes::AppState,
types::{
- domain,
storage::{self, enums as storage_enums},
transformers::ForeignTryFrom,
},
@@ -322,7 +322,7 @@ impl SurchargeMetadata {
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &AppState,
- merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
@@ -341,7 +341,7 @@ impl SurchargeMetadata {
.attach_printable("Failed to encode to string of json")?,
));
}
- let intent_fulfillment_time = merchant_account
+ let intent_fulfillment_time = business_profile
.intent_fulfillment_time
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 6eec39f53b..c86e527b00 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -255,6 +255,8 @@ pub async fn update_business_profile_active_algorithm_ref(
applepay_verified_domains: None,
modified_at: None,
is_recon_enabled: None,
+ payment_link_config: None,
+ session_expiry: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
.await
diff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rs
index 5dc9871e70..a56f9dcce2 100644
--- a/crates/router/src/db/payment_link.rs
+++ b/crates/router/src/db/payment_link.rs
@@ -42,10 +42,10 @@ impl PaymentLinkInterface for Store {
async fn insert_payment_link(
&self,
- payment_link_object: storage::PaymentLinkNew,
+ payment_link_config: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- payment_link_object
+ payment_link_config
.insert(&conn)
.await
.map_err(Into::into)
diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs
index efe71e49bb..e6c9dba7d6 100644
--- a/crates/router/src/macros.rs
+++ b/crates/router/src/macros.rs
@@ -1 +1,4 @@
-pub use common_utils::{collect_missing_value_keys, newtype};
+pub use common_utils::{
+ async_spawn, collect_missing_value_keys, fallback_reverse_lookup_not_found, newtype,
+ newtype_impl,
+};
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index c7d3b11abb..79b38e03f3 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -186,8 +186,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
+ api_models::admin::BusinessPaymentLinkConfig,
+ api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
- api_models::admin::PaymentLinkColorSchema,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
@@ -318,6 +319,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::IncrementalAuthorizationResponse,
+ api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
@@ -368,7 +370,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
- api_models::payments::PaymentLinkObject,
+ api_models::payments::PaymentLinkStatus
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index ba3607fb7d..54df028551 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1631,7 +1631,7 @@ pub fn build_payment_link_html(
}
fn get_hyper_loader_sdk(sdk_url: &str) -> String {
- format!("<script src=\"{sdk_url}\"></script>")
+ format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
#[cfg(test)]
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index fe99d08422..487cea88d1 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -14,6 +14,7 @@ use masking::Secret;
use crate::{
core::errors,
types::{domain, storage, transformers::ForeignTryFrom},
+ utils::{self},
};
impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {
@@ -46,7 +47,6 @@ impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
- payment_link_config: item.payment_link_config,
})
}
}
@@ -72,6 +72,8 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
frm_routing_algorithm: item.frm_routing_algorithm,
payout_routing_algorithm: item.payout_routing_algorithm,
applepay_verified_domains: item.applepay_verified_domains,
+ payment_link_config: item.payment_link_config,
+ session_expiry: item.session_expiry,
})
}
}
@@ -105,6 +107,18 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.or(merchant_account.payment_response_hash_key)
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
+ let payment_link_config_value = request
+ .payment_link_config
+ .map(|pl_config| {
+ utils::Encode::<api_models::admin::BusinessPaymentLinkConfig>::encode_to_value(
+ &pl_config,
+ )
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config_value",
+ })
+ })
+ .transpose()?;
+
Ok(Self {
profile_id,
merchant_id: merchant_account.merchant_id,
@@ -140,6 +154,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.or(merchant_account.payout_routing_algorithm),
is_recon_enabled: merchant_account.is_recon_enabled,
applepay_verified_domains: request.applepay_verified_domains,
+ payment_link_config: payment_link_config_value,
+ session_expiry: request
+ .session_expiry
+ .map(i64::from)
+ .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
})
}
}
diff --git a/crates/router/src/types/api/payment_link.rs b/crates/router/src/types/api/payment_link.rs
index e56af6b4ae..d0ce8c043b 100644
--- a/crates/router/src/types/api/payment_link.rs
+++ b/crates/router/src/types/api/payment_link.rs
@@ -1,6 +1,7 @@
pub use api_models::payments::RetrievePaymentLinkResponse;
use crate::{
+ consts::DEFAULT_SESSION_EXPIRY,
core::{errors::RouterResult, payment_link},
types::storage::{self},
};
@@ -13,7 +14,11 @@ pub(crate) trait PaymentLinkResponseExt: Sized {
#[async_trait::async_trait]
impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self> {
- let status = payment_link::check_payment_link_status(payment_link.fulfilment_time);
+ let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+ let status = payment_link::check_payment_link_status(session_expiry);
Ok(Self {
link_to_pay: payment_link.link_to_pay,
payment_link_id: payment_link.payment_link_id,
@@ -21,7 +26,7 @@ impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
description: payment_link.description,
created_at: payment_link.created_at,
merchant_id: payment_link.merchant_id,
- link_expiry: payment_link.fulfilment_time,
+ expiry: payment_link.fulfilment_time,
currency: payment_link.currency,
status,
})
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index ce8350bd9e..8f204814ec 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -344,10 +344,8 @@ impl NewUserMerchant {
merchant_details: None,
routing_algorithm: None,
parent_merchant_id: None,
- payment_link_config: None,
sub_merchants_enabled: None,
frm_routing_algorithm: None,
- intent_fulfillment_time: None,
payout_routing_algorithm: None,
primary_business_details: None,
payment_response_hash_key: None,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 5bd03fe833..c3818caf05 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -943,19 +943,27 @@ impl
}
}
-impl ForeignFrom<(storage::PaymentLink, String)>
- for api_models::payments::RetrievePaymentLinkResponse
+impl
+ ForeignFrom<(
+ storage::PaymentLink,
+ api_models::payments::PaymentLinkStatus,
+ )> for api_models::payments::RetrievePaymentLinkResponse
{
- fn foreign_from((payment_link_object, status): (storage::PaymentLink, String)) -> Self {
+ fn foreign_from(
+ (payment_link_config, status): (
+ storage::PaymentLink,
+ api_models::payments::PaymentLinkStatus,
+ ),
+ ) -> Self {
Self {
- payment_link_id: payment_link_object.payment_link_id,
- merchant_id: payment_link_object.merchant_id,
- link_to_pay: payment_link_object.link_to_pay,
- amount: payment_link_object.amount,
- created_at: payment_link_object.created_at,
- link_expiry: payment_link_object.fulfilment_time,
- description: payment_link_object.description,
- currency: payment_link_object.currency,
+ payment_link_id: payment_link_config.payment_link_id,
+ merchant_id: payment_link_config.merchant_id,
+ link_to_pay: payment_link_config.link_to_pay,
+ amount: payment_link_config.amount,
+ created_at: payment_link_config.created_at,
+ expiry: payment_link_config.fulfilment_time,
+ description: payment_link_config.description,
+ currency: payment_link_config.currency,
status,
}
}
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 5ce0818b82..33f1e21153 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -146,6 +146,8 @@ pub async fn generate_sample_data(
common_utils::date_time::now() - time::Duration::days(7)
}),
);
+ let session_expiry =
+ created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
// After some set of payments sample data will have a failed attempt
let is_failed_payment =
@@ -197,6 +199,7 @@ pub async fn generate_sample_data(
request_incremental_authorization: Default::default(),
incremental_authorization_allowed: Default::default(),
authorization_count: Default::default(),
+ session_expiry: Some(session_expiry),
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 1da3df0bde..ee8676106f 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -109,6 +109,7 @@ impl PaymentIntentInterface for MockDb {
request_incremental_authorization: new.request_incremental_authorization,
incremental_authorization_allowed: new.incremental_authorization_allowed,
authorization_count: new.authorization_count,
+ session_expiry: new.session_expiry,
};
payment_intents.push(payment_intent.clone());
Ok(payment_intent)
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 61229ca890..07d70c9056 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -101,6 +101,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
request_incremental_authorization: new.request_incremental_authorization,
incremental_authorization_allowed: new.incremental_authorization_allowed,
authorization_count: new.authorization_count,
+ session_expiry: new.session_expiry,
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
@@ -768,6 +769,7 @@ impl DataModelExt for PaymentIntentNew {
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
+ session_expiry: self.session_expiry,
}
}
@@ -811,6 +813,7 @@ impl DataModelExt for PaymentIntentNew {
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
+ session_expiry: storage_model.session_expiry,
}
}
}
@@ -859,6 +862,7 @@ impl DataModelExt for PaymentIntent {
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
+ session_expiry: self.session_expiry,
}
}
@@ -903,6 +907,7 @@ impl DataModelExt for PaymentIntent {
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
+ session_expiry: storage_model.session_expiry,
}
}
}
@@ -985,6 +990,7 @@ impl DataModelExt for PaymentIntentUpdate {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => DieselPaymentIntentUpdate::Update {
amount,
currency,
@@ -1003,6 +1009,7 @@ impl DataModelExt for PaymentIntentUpdate {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
},
Self::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
diff --git a/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql b/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql
new file mode 100644
index 0000000000..16705c2bf5
--- /dev/null
+++ b/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile DROP COLUMN IF EXISTS payment_link_config;
\ No newline at end of file
diff --git a/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql b/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql
new file mode 100644
index 0000000000..19fbedccbb
--- /dev/null
+++ b/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE business_profile
+ADD COLUMN IF NOT EXISTS payment_link_config JSONB DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql b/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql
new file mode 100644
index 0000000000..4fa87f5f93
--- /dev/null
+++ b/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_link DROP COLUMN profile_id;
\ No newline at end of file
diff --git a/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql b/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql
new file mode 100644
index 0000000000..b48346c763
--- /dev/null
+++ b/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_link ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql
new file mode 100644
index 0000000000..2801a68c67
--- /dev/null
+++ b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent DROP COLUMN IF EXISTS session_expiry;
\ No newline at end of file
diff --git a/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql
new file mode 100644
index 0000000000..f2ee81e847
--- /dev/null
+++ b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS session_expiry TIMESTAMP DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql b/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql
new file mode 100644
index 0000000000..cdc7fe5b81
--- /dev/null
+++ b/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile DROP COLUMN IF EXISTS session_expiry;
\ No newline at end of file
diff --git a/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql b/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql
new file mode 100644
index 0000000000..462dfd234a
--- /dev/null
+++ b/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS session_expiry BIGINT DEFAULT NULL;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 36cc0cbc01..bf373220fd 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4059,6 +4059,22 @@
}
}
},
+ "BusinessPaymentLinkConfig": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "domain_name": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ ]
+ },
"CaptureMethod": {
"type": "string",
"enum": [
@@ -6914,26 +6930,10 @@
"description": "The frm routing algorithm to be used for routing payments to desired FRM's",
"nullable": true
},
- "intent_fulfillment_time": {
- "type": "integer",
- "format": "int32",
- "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
- "example": 900,
- "nullable": true,
- "minimum": 0
- },
"organization_id": {
"type": "string",
"description": "The id of the organization to which the merchant belongs to",
"nullable": true
- },
- "payment_link_config": {
- "allOf": [
- {
- "$ref": "#/components/schemas/PaymentLinkConfig"
- }
- ],
- "nullable": true
}
}
},
@@ -7107,9 +7107,6 @@
},
"recon_status": {
"$ref": "#/components/schemas/ReconStatus"
- },
- "payment_link_config": {
- "nullable": true
}
}
},
@@ -7230,21 +7227,11 @@
"description": "The frm routing algorithm to be used for routing payments to desired FRM's",
"nullable": true
},
- "intent_fulfillment_time": {
- "type": "integer",
- "format": "int32",
- "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
- "nullable": true,
- "minimum": 0
- },
"default_profile": {
"type": "string",
"description": "The default business profile that must be used for creating merchant accounts and payments\nTo unset this field, pass an empty string",
"nullable": true,
"maxLength": 64
- },
- "payment_link_config": {
- "nullable": true
}
}
},
@@ -8597,6 +8584,21 @@
}
}
},
+ "PaymentCreatePaymentLinkConfig": {
+ "allOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ }
+ ],
+ "nullable": true
+ },
+ {
+ "type": "object"
+ }
+ ]
+ },
"PaymentExperience": {
"type": "string",
"enum": [
@@ -8661,35 +8663,51 @@
}
]
},
- "PaymentLinkColorSchema": {
+ "PaymentLinkConfig": {
"type": "object",
+ "required": [
+ "theme",
+ "logo",
+ "seller_name"
+ ],
"properties": {
- "background_primary_color": {
+ "theme": {
"type": "string",
- "nullable": true
+ "description": "custom theme for the payment link"
},
- "sdk_theme": {
+ "logo": {
"type": "string",
- "nullable": true
+ "description": "merchant display logo"
+ },
+ "seller_name": {
+ "type": "string",
+ "description": "Custom merchant name for payment link"
}
}
},
- "PaymentLinkConfig": {
+ "PaymentLinkConfigRequest": {
"type": "object",
"properties": {
- "merchant_logo": {
+ "theme": {
"type": "string",
- "example": "https://i.imgur.com/RfxPFQo.png",
+ "description": "custom theme for the payment link",
+ "example": "#4E6ADD",
"nullable": true,
"maxLength": 255
},
- "color_scheme": {
- "allOf": [
- {
- "$ref": "#/components/schemas/PaymentLinkColorSchema"
- }
- ],
- "nullable": true
+ "logo": {
+ "type": "string",
+ "description": "merchant display logo",
+ "example": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg",
+ "nullable": true,
+ "maxLength": 255
+ },
+ "seller_name": {
+ "type": "string",
+ "description": "Custom merchant name for payment link",
+ "example": "hyperswitch",
+ "nullable": true,
+ "maxLength": 255
}
}
},
@@ -8708,31 +8726,6 @@
}
}
},
- "PaymentLinkObject": {
- "type": "object",
- "required": [
- "payment_link_config"
- ],
- "properties": {
- "link_expiry": {
- "type": "string",
- "format": "date-time",
- "nullable": true
- },
- "merchant_custom_domain_name": {
- "type": "string",
- "nullable": true
- },
- "payment_link_config": {
- "$ref": "#/components/schemas/PaymentLinkConfig"
- },
- "custom_merchant_name": {
- "type": "string",
- "description": "Custom merchant name for payment link",
- "nullable": true
- }
- }
- },
"PaymentLinkResponse": {
"type": "object",
"required": [
@@ -8748,6 +8741,13 @@
}
}
},
+ "PaymentLinkStatus": {
+ "type": "string",
+ "enum": [
+ "Active",
+ "Expired"
+ ]
+ },
"PaymentListConstraints": {
"type": "object",
"properties": {
@@ -9814,10 +9814,17 @@
],
"nullable": true
},
- "payment_link_object": {
+ "payment_link": {
+ "type": "boolean",
+ "description": "Whether to get the payment link (if applicable)",
+ "default": false,
+ "example": true,
+ "nullable": true
+ },
+ "payment_link_config": {
"allOf": [
{
- "$ref": "#/components/schemas/PaymentLinkObject"
+ "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
@@ -9848,6 +9855,14 @@
"description": "Request for an incremental authorization",
"nullable": true
},
+ "session_expiry": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
+ "example": 900,
+ "nullable": true,
+ "minimum": 0
+ },
"frm_metadata": {
"description": "additional data related to some frm connectors",
"nullable": true
@@ -10188,10 +10203,17 @@
],
"nullable": true
},
- "payment_link_object": {
+ "payment_link": {
+ "type": "boolean",
+ "description": "Whether to get the payment link (if applicable)",
+ "default": false,
+ "example": true,
+ "nullable": true
+ },
+ "payment_link_config": {
"allOf": [
{
- "$ref": "#/components/schemas/PaymentLinkObject"
+ "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
@@ -10222,6 +10244,14 @@
"description": "Request for an incremental authorization",
"nullable": true
},
+ "session_expiry": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
+ "example": 900,
+ "nullable": true,
+ "minimum": 0
+ },
"frm_metadata": {
"description": "additional data related to some frm connectors",
"nullable": true
@@ -11866,7 +11896,7 @@
"type": "string",
"format": "date-time"
},
- "link_expiry": {
+ "expiry": {
"type": "string",
"format": "date-time",
"nullable": true
@@ -11876,7 +11906,7 @@
"nullable": true
},
"status": {
- "type": "string"
+ "$ref": "#/components/schemas/PaymentLinkStatus"
},
"currency": {
"allOf": [