Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payment-links): add test mode for PL previews (#11724)
Kashifb8ccce4660eb
diff --git a/Cargo.lock b/Cargo.lockindex 584450b7e7..99edb754e0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6537,7 +6537,7 @@ dependencies = ["api_models","common_utils","error-stack 0.4.1",- "getrandom 0.2.16",+ "getrandom 0.3.3","router_env","serde","serde_json",diff --git a/crates/payment_link/Cargo.toml b/crates/payment_link/Cargo.tomlindex da9e1591d9..1dbe169bce 100644--- a/crates/payment_link/Cargo.toml+++ b/crates/payment_link/Cargo.toml@@ -13,7 +13,7 @@ crate-type = ["rlib", "cdylib"]default = ["v1"]v1 = ["api_models/v1"]v2 = ["api_models/v2"]-wasm = ["dep:wasm-bindgen", "getrandom/js"]+wasm = ["dep:wasm-bindgen", "getrandom/wasm_js"][dependencies]serde = { version = "1.0.219", features = ["derive"] }@@ -28,7 +28,7 @@ wasm-bindgen = { version = "0.2", optional = true }# First party cratesapi_models = { path = "../api_models", default-features = false }common_utils = { path = "../common_utils" }-getrandom = { version = "0.2.16", optional = true }+getrandom = { version = "0.3", optional = true }[build-dependencies]router_env = { path = "../router_env" }diff --git a/crates/payment_link/src/js_generator.rs b/crates/payment_link/src/js_generator.rsindex 1b9f0dcd7b..e9903795d1 100644--- a/crates/payment_link/src/js_generator.rs+++ b/crates/payment_link/src/js_generator.rs@@ -49,14 +49,44 @@ fn camel_case_json(value: &mut Value) {/// Only convert the `custom_message_for_payment_method_types` field to camelCasepub fn convert_custom_message_keys_to_camel(value: &mut Value) {+ if let Some(test_mode) = value+ .as_object_mut()+ .and_then(|map| map.remove("test_mode"))+ {+ if let Some(map) = value.as_object_mut() {+ map.insert("isTestMode".to_string(), test_mode);+ }+ }++ // Rename the outer key to `preloadSDKWithParams` and camelCase all of its+ // direct children. Their values are left untouched, since the SDK expects+ // those nested contents verbatim (snake_case).+ if let Some(mut preload_params) = value+ .as_object_mut()+ .and_then(|map| map.remove("preload_sdk_with_params"))+ {+ if let Some(inner) = preload_params.as_object_mut() {+ let keys: Vec<String> = inner.keys().cloned().collect();+ for k in keys {+ if let Some(v) = inner.remove(&k) {+ inner.insert(camel_case_key(&k), v);+ }+ }+ }+ if let Some(map) = value.as_object_mut() {+ map.insert("preloadSDKWithParams".to_string(), preload_params);+ }+ }+if let Some(custom_msg) = value.get_mut("custom_message_for_payment_method_types") {camel_case_json(custom_msg);}}-pub fn get_js_script(- payment_details: &api_models::payments::PaymentLinkData,-) -> Result<String, PaymentLinkError> {+pub fn get_js_script<T>(payment_details: &T) -> Result<String, PaymentLinkError>+where+ T: serde::Serialize,+{let mut json =serde_json::to_value(payment_details).map_err(|_| PaymentLinkError::SerializationFailed)?;diff --git a/crates/payment_link/src/types.rs b/crates/payment_link/src/types.rsindex d91ee08c6b..6630117f6e 100644--- a/crates/payment_link/src/types.rs+++ b/crates/payment_link/src/types.rs@@ -19,4 +19,20 @@ pub struct PaymentLinkStatusData {pub css_script: String,}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct PreloadSDKParams {+ pub payment_methods_list: Option<serde_json::Value>,+ pub customer_methods_list: Option<serde_json::Value>,+ pub session_tokens: Option<serde_json::Value>,+ pub blocked_bins: Option<serde_json::Value>,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct PaymentLinkPreviewConfig {+ pub test_mode: Option<bool>,+ pub preload_sdk_with_params: Option<PreloadSDKParams>,+ #[serde(flatten)]+ pub payment_link_details: api_models::payments::PaymentLinkDetails,+}+impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, PaymentLinkStatusData));diff --git a/crates/payment_link/src/wasm.rs b/crates/payment_link/src/wasm.rsindex 4acbc1e12c..613e9c50cc 100644--- a/crates/payment_link/src/wasm.rs+++ b/crates/payment_link/src/wasm.rs@@ -1,7 +1,8 @@-use api_models::{admin::PaymentLinkConfig, payments::PaymentLinkData};+use api_models::admin::PaymentLinkConfig;use crate::{- build_payment_link_html, get_css_script, get_js_script, get_meta_tags_html, PaymentLinkFormData,+ build_payment_link_html, get_css_script, get_js_script, get_meta_tags_html,+ types::PaymentLinkPreviewConfig, PaymentLinkFormData,};const SDK_URL: &str = env!("SDK_URL");@@ -9,9 +10,10 @@ const SDK_URL: &str = env!("SDK_URL");/// Implementation function for generating payment link preview/// Called by the wasm_bindgen wrapper in lib.rspub fn generate_payment_link_preview_impl(config_json: &str) -> Result<String, String> {- let payment_link_details: api_models::payments::PaymentLinkDetails =- serde_json::from_str(config_json)- .map_err(|e| format!("Failed to deserialize PaymentLinkDetails: {}", e))?;+ let preview_config: PaymentLinkPreviewConfig = serde_json::from_str(config_json)+ .map_err(|e| format!("Failed to deserialize PaymentLinkPreviewConfig: {}", e))?;++ let payment_link_details = &preview_config.payment_link_details;let mut payment_link_config = PaymentLinkConfig {theme: payment_link_details.theme.clone(),@@ -55,15 +57,13 @@ pub fn generate_payment_link_preview_impl(config_json: &str) -> Result<String, Slet sdk_url = url::Url::parse(SDK_URL).map_err(|e| format!("Invalid SDK URL: {}", e))?;- let js_script = get_js_script(&PaymentLinkData::PaymentLinkDetails(Box::new(- payment_link_details.clone(),- )))- .map_err(|e| format!("Failed to generate JS script: {:?}", e))?;+ let js_script = get_js_script(&preview_config)+ .map_err(|e| format!("Failed to generate JS script: {:?}", e))?;let css_script = get_css_script(&payment_link_config).map_err(|e| format!("Failed to generate CSS script: {:?}", e))?;- let html_meta_tags = get_meta_tags_html(&payment_link_details);+ let html_meta_tags = get_meta_tags_html(payment_link_details);let payment_link_form_data = PaymentLinkFormData {js_script,@@ -79,9 +79,12 @@ pub fn generate_payment_link_preview_impl(config_json: &str) -> Result<String, S/// Implementation function for validating payment link config/// Called by the wasm_bindgen wrapper in lib.rspub fn validate_payment_link_config_impl(config_json: &str) -> Result<String, String> {- let config: api_models::payments::PaymentLinkDetails =+ let preview_config: PaymentLinkPreviewConfig =serde_json::from_str(config_json).map_err(|e| format!("Failed to parse config: {}", e))?;+ let config = &preview_config.payment_link_details;+ let is_test_mode = preview_config.test_mode == Some(true);+let mut errors = Vec::new();let mut warnings = Vec::new();@@ -111,10 +114,25 @@ pub fn validate_payment_link_config_impl(config_json: &str) -> Result<String, Sterrors.push("Merchant name is required".to_string());}- if config.client_secret.is_empty() {+ // Skip client_secret validation if test_mode is enabled+ if config.client_secret.is_empty() && !is_test_mode {errors.push("Client secret is required".to_string());}+ // Validate preload_sdk_with_params if provided+ if let Some(ref preload_params) = preview_config.preload_sdk_with_params {+ let has_valid_params = preload_params.payment_methods_list.is_some()+ || preload_params.customer_methods_list.is_some()+ || preload_params.session_tokens.is_some()+ || preload_params.blocked_bins.is_some();++ if !has_valid_params {+ errors.push(+ "preload_sdk_with_params must have at least one valid field (payment_methods_list, customer_methods_list, session_tokens, or blocked_bins)".to_string(),+ );+ }+ }+if config.pub_key.is_empty() {errors.push("Publishable key is required".to_string());}diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.jsindex b7a61e6111..e9aa1808fd 100644--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js@@ -15,6 +15,8 @@ function initializeSDK() {var sdkUiRules = paymentDetails.sdk_ui_rules;var labelType = paymentDetails.payment_form_label_type;var colorIconCardCvcError = paymentDetails.color_icon_card_cvc_error;+ var isTestMode = paymentDetails.isTestMode === true;+ var preloadSDKWithParams = paymentDetails.preloadSDKWithParams;var appearance = {variables: {colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)",@@ -37,9 +39,22 @@ function initializeSDK() {if (colorIconCardCvcError !== null && typeof colorIconCardCvcError === "string") {appearance.variables.colorIconCardCvcError = colorIconCardCvcError;}++ var isPreloadEnabled = false;+ if (isTestMode) {+ isPreloadEnabled = true;+ } else if (preloadSDKWithParams != null && typeof preloadSDKWithParams === "object") {+ isPreloadEnabled = true;+ }++ if (isTestMode) {+ console.warn("The SDK is running in test mode. API calls are bypassed and wallet interactions are disabled.");+ }+// @ts-ignorehyper = window.Hyper(pub_key, {- isPreloadEnabled: false,+ isTestMode: isTestMode,+ isPreloadEnabled: isPreloadEnabled,// TODO: Remove in next deploymentshouldUseTopRedirection: true,redirectionFlags: {@@ -47,12 +62,20 @@ function initializeSDK() {shouldUseTopRedirection: true,},});- // @ts-ignore- widgets = hyper.widgets({++ var widgetOptions = {appearance: appearance,clientSecret: clientSecret,- locale: paymentDetails.locale,- });+ locale: paymentDetails.locale+ };++ if (preloadSDKWithParams != null && typeof preloadSDKWithParams === "object") {+ // @ts-ignore+ widgetOptions.preloadSDKWithParams = preloadSDKWithParams;+ }++ // @ts-ignore+ widgets = hyper.widgets(widgetOptions);var type =paymentDetails.sdk_layout === "spaced_accordion" ||paymentDetails.sdk_layout === "accordion"diff --git a/justfile b/justfileindex 2cc3514506..e3ef449718 100644--- a/justfile+++ b/justfile@@ -148,6 +148,16 @@ euclid-wasm features='dummy_connector':{{ source_directory() }}/crates/euclid_wasm \--features '{{ features }}'+# Build the `payment_link` crate as WASM+# Usage: just payment-link-wasm [features=''] [version='v1'] [environment='development']+payment-link-wasm features='' version='v1' environment='development':+ ENVIRONMENT={{ environment }} ~/.cargo/bin/wasm-pack build \+ --target web \+ --out-dir {{ source_directory() }}/wasm_output \+ --out-name payment_link \+ {{ source_directory() }}/crates/payment_link \+ -- --features wasm,{{ version }},{{ features }}+# Run pre-commit checksprecommit: fmt clippy