use std::collections::BTreeMap;
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PaneRail {
Wallet,
Redirect,
HostedElement,
}
impl PaneRail {
pub fn as_wire(self) -> &'static str {
match self {
Self::Wallet => "wallet",
Self::Redirect => "redirect",
Self::HostedElement => "hosted_element",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum PaneVisibility {
#[default]
Always,
EmbeddedOnly,
ExternalOnly,
}
impl PaneVisibility {
pub fn as_wire(self) -> &'static str {
match self {
Self::Always => "always",
Self::EmbeddedOnly => "embedded_only",
Self::ExternalOnly => "external_only",
}
}
pub fn from_wire(raw: Option<&Value>) -> Self {
match raw.and_then(Value::as_str) {
Some("embedded_only") => Self::EmbeddedOnly,
Some("external_only") => Self::ExternalOnly,
_ => Self::Always,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum PaneOpenTarget {
#[default]
Tab,
Popup,
}
impl PaneOpenTarget {
pub fn as_wire(self) -> &'static str {
match self {
Self::Tab => "tab",
Self::Popup => "popup",
}
}
pub fn from_wire(raw: Option<&Value>) -> Self {
match raw.and_then(Value::as_str) {
Some("popup") => Self::Popup,
_ => Self::Tab,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pane {
pub method: String,
pub enabled: bool,
pub label: String,
pub label_translations: BTreeMap<String, String>,
pub sublabel: Option<String>,
pub sublabel_translations: BTreeMap<String, String>,
pub category: String,
pub icon: String,
pub icon_svg: String,
pub display_order: i64,
pub visibility: PaneVisibility,
pub open_in: PaneOpenTarget,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaneView {
pub method: String,
pub connector: Option<String>,
pub merchant_connector_id: Option<String>,
pub rail: String,
pub connector_method_name: Option<String>,
pub label: String,
pub sublabel: String,
pub label_is_default: Option<bool>,
pub sublabel_is_default: Option<bool>,
pub connector_display_name: Option<String>,
pub category: String,
pub icon: Option<String>,
pub icon_svg: Option<String>,
pub icon_image: Option<String>,
pub method_logos: Vec<String>,
pub display_order: i64,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub payment_method_data: Option<Value>,
pub requires_billing_country: Option<bool>,
pub embedded_only: Option<bool>,
pub visibility: Option<String>,
pub open_in: Option<String>,
pub native_element: Option<String>,
pub surcharge: Option<PaneSurcharge>,
pub routed: Option<bool>,
pub rapyd_toolkit: Option<RapydToolkitConfig>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RapydToolkitConfig {
pub sandbox: bool,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaneSurcharge {
pub surcharge_amount: i64,
pub tax_amount: i64,
pub total_amount: i64,
pub display_total_amount: i64,
pub direction: String,
#[serde(default)]
pub percent_of_order: Option<f64>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneMethodInfo {
pub key: &'static str,
pub rail: PaneRail,
pub payment_method: &'static str,
pub payment_method_type: &'static str,
pub requires_billing_country: bool,
pub default_label: &'static str,
pub default_sublabel: &'static str,
pub default_category: &'static str,
pub default_icon: &'static str,
}
pub const STRIPE_FALLBACK_PANE_METHODS: &[PaneMethodInfo] = &[
PaneMethodInfo {
key: "apple_pay",
rail: PaneRail::Wallet,
payment_method: "wallet",
payment_method_type: "apple_pay",
requires_billing_country: false,
default_label: "Apple Pay",
default_sublabel: "Pay with Apple Pay",
default_category: "wallet",
default_icon: "apple",
},
PaneMethodInfo {
key: "google_pay",
rail: PaneRail::Wallet,
payment_method: "wallet",
payment_method_type: "google_pay",
requires_billing_country: false,
default_label: "Google Pay",
default_sublabel: "Pay with Google Pay",
default_category: "wallet",
default_icon: "google",
},
PaneMethodInfo {
key: "link",
rail: PaneRail::Wallet,
payment_method: "wallet",
payment_method_type: "link",
requires_billing_country: false,
default_label: "Link",
default_sublabel: "Pay with saved details",
default_category: "wallet",
default_icon: "wallet",
},
PaneMethodInfo {
key: "klarna",
rail: PaneRail::Redirect,
payment_method: "pay_later",
payment_method_type: "klarna",
requires_billing_country: true,
default_label: "Klarna",
default_sublabel: "Pay later or in instalments",
default_category: "bnpl",
default_icon: "bnpl",
},
PaneMethodInfo {
key: "affirm",
rail: PaneRail::Redirect,
payment_method: "pay_later",
payment_method_type: "affirm",
requires_billing_country: false,
default_label: "Affirm",
default_sublabel: "Pay over time",
default_category: "bnpl",
default_icon: "bnpl",
},
PaneMethodInfo {
key: "ideal",
rail: PaneRail::Redirect,
payment_method: "bank_redirect",
payment_method_type: "ideal",
requires_billing_country: false,
default_label: "iDEAL",
default_sublabel: "Pay from your bank",
default_category: "bank_redirect",
default_icon: "bank",
},
PaneMethodInfo {
key: "alipay",
rail: PaneRail::Redirect,
payment_method: "wallet",
payment_method_type: "ali_pay",
requires_billing_country: false,
default_label: "Alipay",
default_sublabel: "Pay with Alipay",
default_category: "wallet",
default_icon: "wallet",
},
PaneMethodInfo {
key: "revolut_pay",
rail: PaneRail::Redirect,
payment_method: "wallet",
payment_method_type: "revolut_pay",
requires_billing_country: false,
default_label: "Revolut Pay",
default_sublabel: "Pay with Revolut",
default_category: "wallet",
default_icon: "wallet",
},
PaneMethodInfo {
key: "amazon_pay",
rail: PaneRail::Redirect,
payment_method: "wallet",
payment_method_type: "amazon_pay",
requires_billing_country: false,
default_label: "Amazon Pay",
default_sublabel: "Pay with Amazon",
default_category: "wallet",
default_icon: "wallet",
},
];
pub const PANE_ICON_KEYS: &[&str] = &[
"wallet", "card", "bank", "apple", "google", "bnpl", "cash",
"paypal", "klarna", "crypto",
];
pub const PANE_CATEGORY_KEYS: &[&str] = &[
"wallet",
"card",
"bnpl",
"bank_redirect",
"bank_transfer",
"crypto",
"game_items",
"cash",
];
pub const PANES_MAX: usize = 12;
pub const PANES_METADATA_KEY: &str = "native_panes";
pub const CHECKOUT_EVENT_KINDS: &[&str] = &[
"native_pane_selected",
"native_pane_tab_opened",
"native_pane_tab_blocked",
"native_pane_abandoned",
"native_pane_returned",
];
pub fn pane_method_info(method: &str) -> Option<&'static PaneMethodInfo> {
STRIPE_FALLBACK_PANE_METHODS
.iter()
.find(|m| m.key == method)
}
pub fn default_pane(method: &str, catalog: &PanesConnectorCatalog) -> Pane {
let defaults = pane_display_defaults(pane_capability(method, catalog));
Pane {
method: method.to_owned(),
enabled: true,
label: String::new(),
label_translations: BTreeMap::new(),
sublabel: None,
sublabel_translations: BTreeMap::new(),
category: defaults.category.to_owned(),
icon: defaults.icon.to_owned(),
icon_svg: String::new(),
display_order: 0,
visibility: PaneVisibility::Always,
open_in: PaneOpenTarget::Tab,
}
}
fn str_or_empty(row: &Map<String, Value>, key: &str) -> String {
row.get(key)
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned()
}
fn parse_translations(raw: Option<&Value>) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
if let Some(Value::Object(map)) = raw {
for (locale, value) in map {
if let Some(text) = value.as_str()
&& !text.is_empty()
{
out.insert(locale.clone(), text.to_owned());
}
}
}
out
}
fn int_or_zero(raw: Option<&Value>) -> i64 {
let wide = match raw {
Some(Value::Number(n)) => n
.as_i64()
.or_else(|| n.as_f64().filter(|f| f.is_finite()).map(|f| f as i64))
.unwrap_or(0),
Some(Value::String(s)) => s
.trim()
.parse::<f64>()
.ok()
.filter(|f| f.is_finite())
.map(|f| f as i64)
.unwrap_or(0),
_ => 0,
};
wide.clamp(i64::from(i32::MIN), i64::from(i32::MAX))
}
pub fn decode_panes(raw: &Value) -> Option<Vec<Pane>> {
let rows = raw.as_array()?;
let decode_row = |row: &Map<String, Value>, method: String| Pane {
method,
enabled: row.get("enabled") != Some(&Value::Bool(false)),
label: str_or_empty(row, "label"),
label_translations: parse_translations(row.get("label_translations")),
sublabel: row
.get("sublabel")
.and_then(Value::as_str)
.map(str::to_owned),
sublabel_translations: parse_translations(row.get("sublabel_translations")),
category: str_or_empty(row, "category"),
icon: str_or_empty(row, "icon"),
icon_svg: str_or_empty(row, "icon_svg"),
display_order: int_or_zero(row.get("display_order")),
visibility: PaneVisibility::from_wire(row.get("visibility")),
open_in: PaneOpenTarget::from_wire(row.get("open_in")),
};
let mut index_by_method: BTreeMap<String, usize> = BTreeMap::new();
let mut out: Vec<Pane> = Vec::new();
for entry in rows {
if out.len() >= PANES_MAX {
break;
}
let Some(row) = entry.as_object() else {
continue;
};
let method = str_or_empty(row, "method").trim().to_owned();
if method.is_empty() {
continue;
}
if let Some(&kept) = index_by_method.get(&method) {
let enabled = row.get("enabled") != Some(&Value::Bool(false));
if enabled && !out[kept].enabled {
out[kept] = decode_row(row, method);
}
continue;
}
index_by_method.insert(method.clone(), out.len());
out.push(decode_row(row, method));
}
Some(out)
}
pub fn encode_panes(panes: &[Pane]) -> Value {
let non_empty = |map: &BTreeMap<String, String>| -> Option<Map<String, Value>> {
let entries: Map<String, Value> = map
.iter()
.filter(|(_, v)| !v.trim().is_empty())
.map(|(k, v)| (k.clone(), Value::String(v.clone())))
.collect();
(!entries.is_empty()).then_some(entries)
};
let rows: Vec<Value> = panes
.iter()
.take(PANES_MAX)
.map(|pane| {
let mut row = Map::new();
row.insert("method".into(), Value::String(pane.method.clone()));
row.insert("enabled".into(), Value::Bool(pane.enabled));
if !pane.label.trim().is_empty() {
row.insert("label".into(), Value::String(pane.label.trim().to_owned()));
}
if let Some(translations) = non_empty(&pane.label_translations) {
row.insert("label_translations".into(), Value::Object(translations));
}
if let Some(sublabel) = &pane.sublabel {
row.insert("sublabel".into(), Value::String(sublabel.clone()));
}
if let Some(translations) = non_empty(&pane.sublabel_translations) {
row.insert("sublabel_translations".into(), Value::Object(translations));
}
if !pane.category.trim().is_empty() {
row.insert(
"category".into(),
Value::String(pane.category.trim().to_owned()),
);
}
if !pane.icon.trim().is_empty() {
row.insert("icon".into(), Value::String(pane.icon.trim().to_owned()));
}
if !pane.icon_svg.trim().is_empty() {
row.insert(
"icon_svg".into(),
Value::String(pane.icon_svg.trim().to_owned()),
);
}
row.insert(
"display_order".into(),
Value::from(
pane.display_order
.clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
),
);
row.insert(
"visibility".into(),
Value::String(pane.visibility.as_wire().to_owned()),
);
row.insert(
"open_in".into(),
Value::String(pane.open_in.as_wire().to_owned()),
);
Value::Object(row)
})
.collect();
Value::Array(rows)
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PaneCapability {
pub key: String,
pub rail: String,
pub payment_method: String,
pub payment_method_type: String,
#[serde(default)]
pub requires_billing_country: bool,
#[serde(default)]
pub supports_native_element: bool,
}
impl PaneCapability {
pub fn rail(&self) -> Option<PaneRail> {
match self.rail.as_str() {
"wallet" => Some(PaneRail::Wallet),
"redirect" => Some(PaneRail::Redirect),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PanesConnectorCatalog {
pub connector: String,
#[serde(default)]
pub allowed_rails: Vec<String>,
#[serde(default)]
pub methods: Vec<PaneCapability>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PanesCatalogResponse {
pub connectors: Vec<PanesConnectorCatalog>,
}
pub static STRIPE_FALLBACK_PANE_CATALOG: LazyLock<PanesConnectorCatalog> =
LazyLock::new(|| PanesConnectorCatalog {
connector: "stripe".to_owned(),
allowed_rails: vec!["wallet".to_owned(), "redirect".to_owned()],
methods: STRIPE_FALLBACK_PANE_METHODS
.iter()
.map(|info| PaneCapability {
key: info.key.to_owned(),
rail: info.rail.as_wire().to_owned(),
payment_method: info.payment_method.to_owned(),
payment_method_type: info.payment_method_type.to_owned(),
requires_billing_country: info.requires_billing_country,
supports_native_element: false,
})
.collect(),
});
pub fn empty_pane_catalog(connector: &str) -> PanesConnectorCatalog {
PanesConnectorCatalog {
connector: connector.to_owned(),
allowed_rails: Vec::new(),
methods: Vec::new(),
}
}
pub fn pane_catalog_for(response: &PanesCatalogResponse, connector: &str) -> PanesConnectorCatalog {
response
.connectors
.iter()
.find(|entry| entry.connector == connector)
.cloned()
.unwrap_or_else(|| empty_pane_catalog(connector))
}
pub fn pane_capability<'a>(
method: &str,
catalog: &'a PanesConnectorCatalog,
) -> Option<&'a PaneCapability> {
catalog.methods.iter().find(|info| info.key == method)
}
pub fn pane_rail_allowed(rail: &str, catalog: &PanesConnectorCatalog) -> bool {
catalog.allowed_rails.iter().any(|r| r == rail)
}
pub fn offerable_pane_methods(catalog: &PanesConnectorCatalog) -> Vec<&PaneCapability> {
catalog
.methods
.iter()
.filter(|info| pane_rail_allowed(&info.rail, catalog))
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneDisplayDefaults {
pub icon: &'static str,
pub category: &'static str,
}
const DISPLAY_DEFAULTS_BY_KEY: &[(&str, PaneDisplayDefaults)] = &[
(
"apple_pay",
PaneDisplayDefaults {
icon: "apple",
category: "wallet",
},
),
(
"google_pay",
PaneDisplayDefaults {
icon: "google",
category: "wallet",
},
),
(
"paypal",
PaneDisplayDefaults {
icon: "paypal",
category: "wallet",
},
),
(
"klarna",
PaneDisplayDefaults {
icon: "klarna",
category: "bnpl",
},
),
];
const DISPLAY_DEFAULTS_BY_PAYMENT_METHOD: &[(&str, PaneDisplayDefaults)] = &[
(
"wallet",
PaneDisplayDefaults {
icon: "wallet",
category: "wallet",
},
),
(
"card",
PaneDisplayDefaults {
icon: "card",
category: "card",
},
),
(
"card_redirect",
PaneDisplayDefaults {
icon: "card",
category: "card",
},
),
(
"pay_later",
PaneDisplayDefaults {
icon: "bnpl",
category: "bnpl",
},
),
(
"bank_redirect",
PaneDisplayDefaults {
icon: "bank",
category: "bank_redirect",
},
),
(
"bank_transfer",
PaneDisplayDefaults {
icon: "bank",
category: "bank_transfer",
},
),
(
"bank_debit",
PaneDisplayDefaults {
icon: "bank",
category: "bank_transfer",
},
),
(
"crypto",
PaneDisplayDefaults {
icon: "crypto",
category: "crypto",
},
),
(
"game_items",
PaneDisplayDefaults {
icon: "wallet",
category: "game_items",
},
),
(
"cash",
PaneDisplayDefaults {
icon: "cash",
category: "cash",
},
),
(
"voucher",
PaneDisplayDefaults {
icon: "cash",
category: "cash",
},
),
];
const DISPLAY_DEFAULTS_FALLBACK: PaneDisplayDefaults = PaneDisplayDefaults {
icon: "wallet",
category: "wallet",
};
pub fn pane_display_defaults(info: Option<&PaneCapability>) -> PaneDisplayDefaults {
let Some(info) = info else {
return DISPLAY_DEFAULTS_FALLBACK;
};
if let Some((_, d)) = DISPLAY_DEFAULTS_BY_KEY.iter().find(|(k, _)| *k == info.key) {
return *d;
}
if let Some((_, d)) = DISPLAY_DEFAULTS_BY_PAYMENT_METHOD
.iter()
.find(|(k, _)| *k == info.payment_method)
{
return *d;
}
DISPLAY_DEFAULTS_FALLBACK
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaneIssueCode {
MethodUnknown,
RailNotAllowed,
OverCap,
DuplicateMethod,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PaneIssue {
pub index: usize,
pub method: String,
pub code: PaneIssueCode,
}
pub fn validate_panes(panes: &[Pane], catalog: &PanesConnectorCatalog) -> Vec<PaneIssue> {
let mut issues = Vec::new();
let mut claimed: Vec<&str> = Vec::new();
for (index, pane) in panes.iter().enumerate() {
match pane_capability(&pane.method, catalog) {
None => issues.push(PaneIssue {
index,
method: pane.method.clone(),
code: PaneIssueCode::MethodUnknown,
}),
Some(info) if !pane_rail_allowed(&info.rail, catalog) => issues.push(PaneIssue {
index,
method: pane.method.clone(),
code: PaneIssueCode::RailNotAllowed,
}),
Some(info) if pane.enabled => {
if claimed.contains(&info.key.as_str()) {
issues.push(PaneIssue {
index,
method: pane.method.clone(),
code: PaneIssueCode::DuplicateMethod,
});
} else {
claimed.push(info.key.as_str());
}
}
Some(_) => {}
}
if index >= PANES_MAX {
issues.push(PaneIssue {
index,
method: pane.method.clone(),
code: PaneIssueCode::OverCap,
});
}
}
issues
}
pub fn pane_view_visibility(view: &PaneView) -> PaneVisibility {
match view.visibility.as_deref() {
Some("always") => PaneVisibility::Always,
Some("embedded_only") => PaneVisibility::EmbeddedOnly,
Some("external_only") => PaneVisibility::ExternalOnly,
_ if view.embedded_only == Some(true) => PaneVisibility::EmbeddedOnly,
_ => PaneVisibility::Always,
}
}
#[derive(Debug, Clone, Copy)]
pub struct FocusedCheckoutUrlParams<'a> {
pub checkout_base_url: &'a str,
pub merchant_id: &'a str,
pub payment_id: &'a str,
pub payment_link_id: Option<&'a str>,
pub method: &'a str,
pub connector: Option<&'a str>,
pub merchant_connector_id: Option<&'a str>,
pub locale: Option<&'a str>,
pub custom_fields_collected: bool,
}
fn is_opaque_payment_link_id(id: &str) -> bool {
id.len() == 36
&& id.char_indices().all(|(i, c)| match i {
8 | 13 | 18 | 23 => c == '-',
_ => matches!(c, '0'..='9' | 'a'..='f'),
})
}
pub fn focused_checkout_url(params: &FocusedCheckoutUrlParams<'_>) -> String {
let base = params.checkout_base_url.trim_end_matches('/');
let path = match params
.payment_link_id
.filter(|id| is_opaque_payment_link_id(id))
{
Some(payment_link_id) => format!("{base}/pay/{payment_link_id}"),
None => format!(
"{base}/pay/{}/{}",
encode_path_segment(params.merchant_id),
encode_path_segment(params.payment_id),
),
};
let mut url = format!("{path}?pane={}", encode_query_value(params.method));
if let Some(connector) = params.connector.map(str::trim).filter(|c| !c.is_empty()) {
url.push_str("&connector=");
url.push_str(&encode_query_value(connector));
}
if let Some(mca) = params
.merchant_connector_id
.map(str::trim)
.filter(|m| !m.is_empty())
{
url.push_str("&mca=");
url.push_str(&encode_query_value(mca));
}
if let Some(locale) = params.locale.filter(|l| !l.is_empty()) {
url.push_str("&locale=");
url.push_str(&encode_query_value(locale));
}
if params.custom_fields_collected {
url.push_str("&cf=1");
}
url
}
fn encode_path_segment(s: &str) -> String {
percent_encode(s, false)
}
fn encode_query_value(s: &str) -> String {
percent_encode(s, true)
}
fn percent_encode(s: &str, form: bool) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(b as char),
b'~' if !form => out.push('~'),
b'*' if form => out.push('*'),
b' ' if form => out.push('+'),
_ => {
out.push('%');
out.push_str(&format!("{b:02X}"));
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn catalog_has_unique_keys() {
let mut keys: Vec<_> = STRIPE_FALLBACK_PANE_METHODS.iter().map(|m| m.key).collect();
keys.sort_unstable();
keys.dedup();
assert_eq!(keys.len(), STRIPE_FALLBACK_PANE_METHODS.len());
}
#[test]
fn catalog_never_offers_the_card_rail() {
for key in ["card", "credit", "debit"] {
assert!(pane_method_info(key).is_none());
}
}
#[test]
fn catalog_marks_exactly_the_browser_wallets_as_the_wallet_rail() {
let wallets: Vec<_> = STRIPE_FALLBACK_PANE_METHODS
.iter()
.filter(|m| m.rail == PaneRail::Wallet)
.map(|m| m.key)
.collect();
assert_eq!(wallets, ["apple_pay", "google_pay", "link"]);
}
#[test]
fn decode_returns_none_for_a_non_array() {
assert!(decode_panes(&Value::Null).is_none());
assert!(decode_panes(&json!({})).is_none());
assert!(decode_panes(&json!("[]")).is_none());
}
#[test]
fn decode_reads_a_stored_row() {
let decoded = decode_panes(&json!([{
"method": "apple_pay",
"enabled": true,
"label": "Apple Pay",
"label_translations": {"de": "Apple Pay DE"},
"sublabel": "",
"category": "wallet",
"icon": "apple",
"display_order": 2,
}]))
.unwrap();
assert_eq!(decoded.len(), 1);
let pane = &decoded[0];
assert_eq!(pane.method, "apple_pay");
assert!(pane.enabled);
assert_eq!(pane.label, "Apple Pay");
assert_eq!(pane.label_translations["de"], "Apple Pay DE");
assert_eq!(pane.sublabel.as_deref(), Some(""));
assert_eq!(pane.category, "wallet");
assert_eq!(pane.icon, "apple");
assert_eq!(pane.display_order, 2);
}
#[test]
fn decode_drops_methodless_rows_and_keeps_the_first_duplicate() {
let decoded = decode_panes(&json!([
{"label": "nameless"},
{"method": "klarna", "label": "first"},
{"method": "klarna", "label": "second"},
]))
.unwrap();
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].label, "first");
}
#[test]
fn decode_keeps_the_enabled_duplicate_the_router_renders() {
let decoded = decode_panes(&json!([
{"method": "klarna", "enabled": false},
{"method": "klarna", "enabled": true, "label": "Later"},
]))
.unwrap();
assert_eq!(decoded.len(), 1);
assert!(decoded[0].enabled);
assert_eq!(decoded[0].label, "Later");
}
#[test]
fn decode_caps_the_list() {
let rows: Vec<Value> = (0..PANES_MAX + 5)
.map(|i| json!({"method": format!("m{i}")}))
.collect();
assert_eq!(decode_panes(&Value::Array(rows)).unwrap().len(), PANES_MAX);
}
#[test]
fn decode_distinguishes_an_absent_sublabel_from_a_deliberately_blank_one() {
let absent = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
assert_eq!(absent[0].sublabel, None);
let blank = decode_panes(&json!([{"method": "apple_pay", "sublabel": ""}])).unwrap();
assert_eq!(blank[0].sublabel.as_deref(), Some(""));
}
#[test]
fn decode_tolerates_junk_in_every_optional_field() {
let decoded = decode_panes(&json!([{
"method": "ideal",
"enabled": "yes",
"label": 42,
"label_translations": {"de": 7, "fr": "Banque"},
"category": null,
"display_order": "nope",
}]))
.unwrap();
let pane = &decoded[0];
assert_eq!(pane.method, "ideal");
assert!(pane.enabled);
assert_eq!(pane.label, "");
assert_eq!(pane.label_translations.len(), 1);
assert_eq!(pane.label_translations["fr"], "Banque");
assert_eq!(pane.category, "");
assert_eq!(pane.display_order, 0);
}
#[test]
fn decode_accepts_a_numeric_string_display_order() {
let decoded = decode_panes(&json!([{"method": "ideal", "display_order": "3"}])).unwrap();
assert_eq!(decoded[0].display_order, 3);
}
#[test]
fn decode_clamps_display_order_into_the_router_i32_range() {
let decoded = decode_panes(&json!([
{"method": "ideal", "display_order": 3_000_000_000_i64},
{"method": "klarna", "display_order": -3_000_000_000_i64},
]))
.unwrap();
assert_eq!(decoded[0].display_order, i64::from(i32::MAX));
assert_eq!(decoded[1].display_order, i64::from(i32::MIN));
let round_tripped = decode_panes(&encode_panes(&decoded)).unwrap();
assert_eq!(round_tripped, decoded);
}
#[test]
fn encode_clamps_display_order_that_never_went_through_decode() {
let mut pane = default_pane("ideal", &STRIPE_FALLBACK_PANE_CATALOG);
pane.display_order = 1_753_000_000_000;
let encoded = encode_panes(&[pane]);
assert_eq!(
encoded[0].get("display_order"),
Some(&Value::from(i32::MAX))
);
}
#[test]
fn encode_round_trips_through_decode() {
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.label = "Wallet".into();
pane.label_translations
.insert("de".into(), "Geldbörse".into());
pane.display_order = 3;
let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
assert_eq!(round_tripped[0], pane);
}
#[test]
fn encode_omits_the_copy_and_keeps_the_presentation() {
let encoded = encode_panes(&[default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG)]);
let row = encoded[0].as_object().unwrap();
assert!(!row.contains_key("label"));
assert!(!row.contains_key("sublabel"));
assert!(!row.contains_key("icon_svg"));
assert_eq!(row["method"], "apple_pay");
assert_eq!(row["category"], "wallet");
assert_eq!(row["icon"], "apple");
}
#[test]
fn encode_preserves_a_deliberately_blank_sublabel() {
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.sublabel = Some(String::new());
let encoded = encode_panes(std::slice::from_ref(&pane));
assert_eq!(encoded[0]["sublabel"], "");
}
#[test]
fn encode_drops_blank_translation_entries() {
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.label_translations.insert("de".into(), " ".into());
pane.label_translations
.insert("fr".into(), "Portefeuille".into());
let encoded = encode_panes(std::slice::from_ref(&pane));
assert_eq!(
encoded[0]["label_translations"],
json!({"fr": "Portefeuille"})
);
}
#[test]
fn visibility_defaults_to_always_and_round_trips_embedded_only() {
let decoded = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
assert_eq!(decoded[0].visibility, PaneVisibility::Always);
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.visibility = PaneVisibility::EmbeddedOnly;
let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
assert_eq!(round_tripped[0].visibility, PaneVisibility::EmbeddedOnly);
}
#[test]
fn visibility_degrades_an_unknown_stored_value_instead_of_dropping_the_row() {
let decoded =
decode_panes(&json!([{"method": "apple_pay", "visibility": "sometimes"}])).unwrap();
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].visibility, PaneVisibility::Always);
}
#[test]
fn open_in_defaults_to_tab_and_round_trips_popup() {
let decoded = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
assert_eq!(decoded[0].open_in, PaneOpenTarget::Tab);
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.open_in = PaneOpenTarget::Popup;
let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
assert_eq!(round_tripped[0].open_in, PaneOpenTarget::Popup);
}
#[test]
fn open_in_degrades_an_unknown_stored_value_instead_of_dropping_the_row() {
let decoded = decode_panes(&json!([{"method": "apple_pay", "open_in": "modal"}])).unwrap();
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].open_in, PaneOpenTarget::Tab);
}
#[test]
fn native_pane_view_keeps_open_in_optional() {
let older: PaneView =
serde_json::from_value(json!({"method": "apple_pay", "rail": "wallet"})).unwrap();
assert_eq!(older.open_in, None);
let newer: PaneView = serde_json::from_value(
json!({"method": "apple_pay", "rail": "wallet", "open_in": "popup"}),
)
.unwrap();
assert_eq!(newer.open_in.as_deref(), Some("popup"));
}
#[test]
fn clone_copies_the_translation_maps_rather_than_sharing_them() {
let mut pane = default_pane("klarna", &STRIPE_FALLBACK_PANE_CATALOG);
pane.label_translations.insert("de".into(), "Klarna".into());
let mut copy = pane.clone();
copy.label_translations
.insert("de".into(), "changed".into());
assert_eq!(pane.label_translations["de"], "Klarna");
}
#[test]
fn focused_url_builds_a_top_level_single_method_link() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id: None,
method: "apple_pay",
connector: None,
merchant_connector_id: None,
locale: None,
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay"
);
}
#[test]
fn focused_url_tolerates_a_trailing_slash_and_adds_the_locale() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net/",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id: None,
method: "klarna",
connector: None,
merchant_connector_id: None,
locale: Some("de"),
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/merchant_1/pay_123?pane=klarna&locale=de"
);
}
#[test]
fn focused_url_names_only_the_opaque_payment_link_id() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "ORD-08467086",
payment_link_id: Some("0b9a6e3c-6f1d-4a57-9a1e-2f4c8d7b5e10"),
method: "apple_pay",
connector: None,
merchant_connector_id: None,
locale: None,
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/0b9a6e3c-6f1d-4a57-9a1e-2f4c8d7b5e10?pane=apple_pay"
);
}
#[test]
fn focused_url_keeps_the_merchant_and_payment_path_for_other_link_ids() {
for payment_link_id in [
Some("plink_abcdefghij0123456789"),
Some("0B9A6E3C-6F1D-4A57-9A1E-2F4C8D7B5E10"),
Some("0b9a6e3c6f1d4a579a1e2f4c8d7b5e10"),
None,
] {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id,
method: "apple_pay",
connector: None,
merchant_connector_id: None,
locale: None,
custom_fields_collected: false,
});
assert_eq!(
url, "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay",
"{payment_link_id:?}"
);
}
}
#[test]
fn focused_url_escapes_path_segments() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "a/b",
payment_id: "c d",
payment_link_id: None,
method: "ideal",
connector: None,
merchant_connector_id: None,
locale: None,
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/a%2Fb/c%20d?pane=ideal"
);
}
#[test]
fn focused_url_adds_the_custom_fields_hint() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id: None,
method: "apple_pay",
connector: None,
merchant_connector_id: None,
locale: None,
custom_fields_collected: true,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay&cf=1"
);
}
#[test]
fn native_pane_view_reads_routing_artwork_and_rapyd_toolkit() {
let view: PaneView = serde_json::from_value(json!({
"method": "rapyd_card",
"rail": "hosted_element",
"label": "Card",
"display_order": 2,
"icon_image": "<svg xmlns='http://www.w3.org/2000/svg'/>",
"method_logos": ["visa", "mastercard"],
"routed": true,
"rapyd_toolkit": {"sandbox": true, "future_toolkit_field": 1},
}))
.unwrap();
assert_eq!(view.routed, Some(true));
assert_eq!(view.method_logos, ["visa", "mastercard"]);
assert_eq!(
view.icon_image.as_deref(),
Some("<svg xmlns='http://www.w3.org/2000/svg'/>")
);
let toolkit = view.rapyd_toolkit.as_ref().unwrap();
assert!(toolkit.sandbox);
assert_eq!(toolkit.extra["future_toolkit_field"], 1);
assert!(view.extra.is_empty(), "{:?}", view.extra);
let older: PaneView =
serde_json::from_value(json!({"method": "klarna", "rail": "redirect"})).unwrap();
assert_eq!(older.routed, None);
assert!(older.method_logos.is_empty());
assert!(older.icon_image.is_none());
assert!(older.rapyd_toolkit.is_none());
}
#[test]
fn native_pane_view_deserializes_from_the_wire_shape() {
let view: PaneView = serde_json::from_value(json!({
"method": "klarna",
"rail": "redirect",
"label": "Klarna",
"sublabel": "Pay later",
"category": "bnpl",
"icon": "bnpl",
"display_order": 1,
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_method_data": {"pay_later": {"klarna_redirect": {}}},
"requires_billing_country": true,
"some_future_field": "kept",
}))
.unwrap();
assert_eq!(view.method, "klarna");
assert_eq!(view.rail, "redirect");
assert_eq!(view.display_order, 1);
assert_eq!(view.payment_method.as_deref(), Some("pay_later"));
assert_eq!(view.payment_method_type.as_deref(), Some("klarna"));
assert_eq!(view.requires_billing_country, Some(true));
assert_eq!(view.embedded_only, None);
assert_eq!(
view.extra.get("some_future_field"),
Some(&Value::String("kept".into()))
);
let reserialized = serde_json::to_value(&view).unwrap();
assert_eq!(reserialized["some_future_field"], "kept");
}
#[test]
fn checkout_event_vocabulary_matches_the_router_enum() {
assert_eq!(
CHECKOUT_EVENT_KINDS,
[
"native_pane_selected",
"native_pane_tab_opened",
"native_pane_tab_blocked",
"native_pane_abandoned",
"native_pane_returned",
]
);
}
fn catalog_response() -> PanesCatalogResponse {
serde_json::from_value(json!({
"connectors": [
{
"connector": "cryptomus",
"allowed_rails": ["redirect"],
"methods": [
{
"key": "crypto",
"rail": "redirect",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"requires_billing_country": false
},
{
"key": "apple_pay",
"rail": "wallet",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"requires_billing_country": false
}
]
}
]
}))
.unwrap()
}
#[test]
fn an_unknown_connector_gets_an_empty_catalogue() {
let empty = pane_catalog_for(&catalog_response(), "adyen");
assert_eq!(empty.connector, "adyen");
assert!(empty.methods.is_empty());
assert!(empty.allowed_rails.is_empty());
}
#[test]
fn a_method_on_a_disallowed_rail_is_not_offerable() {
let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
let offerable: Vec<&str> = offerable_pane_methods(&catalog)
.into_iter()
.map(|m| m.key.as_str())
.collect();
assert_eq!(offerable, ["crypto"]);
assert!(!pane_rail_allowed("wallet", &catalog));
}
#[test]
fn a_pane_for_an_unknown_connector_is_designed_not_blank() {
let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
let pane = default_pane("crypto", &catalog);
assert_eq!(pane.icon, "crypto");
assert_eq!(pane.category, "crypto");
}
#[test]
fn an_unknown_method_falls_back_to_a_wallet_tile() {
let pane = default_pane("what_is_this", &empty_pane_catalog("mystery"));
assert_eq!(pane.icon, "wallet");
assert_eq!(pane.category, "wallet");
}
#[test]
fn validation_reports_what_the_router_would_drop() {
let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
let mut disabled_crypto = default_pane("crypto", &catalog);
disabled_crypto.enabled = false;
let panes = vec![
disabled_crypto,
default_pane("crypto", &catalog),
default_pane("crypto", &catalog),
default_pane("apple_pay", &catalog),
default_pane("not_a_method", &catalog),
];
let issues = validate_panes(&panes, &catalog);
assert_eq!(
issues,
vec![
PaneIssue {
index: 2,
method: "crypto".to_string(),
code: PaneIssueCode::DuplicateMethod,
},
PaneIssue {
index: 3,
method: "apple_pay".to_string(),
code: PaneIssueCode::RailNotAllowed,
},
PaneIssue {
index: 4,
method: "not_a_method".to_string(),
code: PaneIssueCode::MethodUnknown,
},
]
);
}
#[test]
fn validation_reports_rows_past_the_cap() {
let catalog = &STRIPE_FALLBACK_PANE_CATALOG;
let mut panes: Vec<Pane> = (0..=PANES_MAX)
.map(|_| default_pane("apple_pay", catalog))
.collect();
for pane in panes.iter_mut().skip(1) {
pane.enabled = false;
}
let issues = validate_panes(&panes, catalog);
assert_eq!(
issues,
vec![PaneIssue {
index: PANES_MAX,
method: "apple_pay".to_string(),
code: PaneIssueCode::OverCap,
}]
);
}
#[test]
fn placement_reads_both_fields_across_payload_versions() {
let newer = PaneView {
visibility: Some("external_only".to_string()),
embedded_only: Some(false),
..PaneView::default()
};
assert_eq!(pane_view_visibility(&newer), PaneVisibility::ExternalOnly);
let older = PaneView {
visibility: None,
embedded_only: Some(true),
..PaneView::default()
};
assert_eq!(pane_view_visibility(&older), PaneVisibility::EmbeddedOnly);
let unknown = PaneView {
visibility: Some("only_on_tuesdays".to_string()),
embedded_only: None,
..PaneView::default()
};
assert_eq!(pane_view_visibility(&unknown), PaneVisibility::Always);
}
#[test]
fn external_only_survives_the_codec() {
let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
pane.visibility = PaneVisibility::ExternalOnly;
let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
assert_eq!(round_tripped[0].visibility, PaneVisibility::ExternalOnly);
}
#[test]
fn the_focused_link_can_name_the_connector_and_the_account() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id: None,
method: "klarna",
connector: Some("klarna"),
merchant_connector_id: Some("mca_1"),
locale: Some("de"),
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/merchant_1/pay_123\
?pane=klarna&connector=klarna&mca=mca_1&locale=de"
);
}
#[test]
fn a_blank_connector_is_omitted_rather_than_sent_empty() {
let url = focused_checkout_url(&FocusedCheckoutUrlParams {
checkout_base_url: "https://checkout.delopay.net",
merchant_id: "merchant_1",
payment_id: "pay_123",
payment_link_id: None,
method: "apple_pay",
connector: Some(" "),
merchant_connector_id: None,
locale: None,
custom_fields_collected: false,
});
assert_eq!(
url,
"https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay"
);
}
}