delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The saved payment method model, plus the *discovery* response
//! [`PaymentMethods::list`](crate::resources::payment_methods::PaymentMethods::list)
//! returns — a different shape entirely, see [`PaymentMethodListResponse`].

use serde::Deserialize;
use serde_json::Value;

use crate::core::models::common::{Currency, PaymentMethod, PaymentMethodType};

/// A saved payment method as returned by the API.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentMethodResponse {
    /// Merchant account ID.
    pub merchant_id: String,
    /// Unique payment method ID.
    pub payment_method_id: String,
    /// Payment method family.
    pub payment_method: PaymentMethod,
    /// Owning customer, if any.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Payment method sub-type.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Whether this method can be charged off-session (recurring).
    #[serde(default)]
    pub recurring_enabled: Option<bool>,
    /// Token to charge this method on a later payment (pass as `payment_token`).
    #[serde(default)]
    pub payment_token: Option<String>,
    /// Lifecycle status.
    #[serde(default)]
    pub status: Option<String>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created: Option<String>,
    /// Any additional response fields not modeled above (e.g. `card`).
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A customer's saved payment methods, as
/// [`PaymentMethods::list_for_customer`](crate::resources::payment_methods::PaymentMethods::list_for_customer)
/// returns them.
///
/// An envelope, not a bare array: `is_guest_customer` rides alongside the list
/// and would be lost if the methods were returned on their own.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CustomerPaymentMethodsListResponse {
    /// The customer's saved methods.
    #[serde(default = "Vec::new")]
    pub customer_payment_methods: Vec<PaymentMethodResponse>,
    /// Whether the call resolved no stored customer.
    #[serde(default)]
    pub is_guest_customer: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Human-facing name and icon for a payment method type, so a custom checkout
/// can render without maintaining a parallel name/logo table.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentMethodDisplayInfo {
    /// Canonical name, e.g. `"Credit Card"`, `"PayPal"`. English only for now.
    #[serde(default)]
    pub display_name: Option<String>,
    /// Stable lowercase icon identifier, e.g. `"card"`, `"paypal"`. The same
    /// value as `payment_method_type`, except that `credit` and `debit` share
    /// the `card` slug. Safe to map 1:1 onto your own icon set.
    #[serde(default)]
    pub icon_slug: Option<String>,
    /// Absolute URL to a DeloPay-hosted icon, when icon hosting is configured
    /// for the deployment. Always `null` today — map `icon_slug` against your
    /// own assets.
    #[serde(default)]
    pub icon_url: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A closed, inclusive band of order values in minor units.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AmountRange {
    pub min_amount: i64,
    pub max_amount: i64,
}

/// The order values a payment method is available for, so a checkout can
/// re-evaluate its own tiles as the cart total changes instead of re-listing on
/// every keystroke.
///
/// A method is available when `min_amount <= amount <= max_amount` **and** the
/// amount falls in none of [`excluded_ranges`](Self::excluded_ranges). Bounds
/// are inclusive minor units in [`currency`](Self::currency); `None` means
/// unbounded on that side.
///
/// Folds together the connector's own configured limits and the merchant's
/// order-value availability rules. Stated in the payment's currency and never
/// converted, which is how the merchant rules are evaluated — so the field is
/// absent when the call resolves no currency.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentMethodAmountLimits {
    /// The currency the bounds are stated in.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Lowest order value the method stays available for. `None` is unbounded.
    #[serde(default)]
    pub min_amount: Option<i64>,
    /// Highest order value the method stays available for. `None` is unbounded.
    #[serde(default)]
    pub max_amount: Option<i64>,
    /// Bands *inside* `[min_amount, max_amount]` where the method is
    /// nevertheless unavailable, produced by a merchant rule hiding it for a
    /// closed range. Almost always empty — but the backend enforces these rules
    /// on payment create, so a cart total inside one of these bands is
    /// **refused**, not merely untiled. Reading only the outer bounds would
    /// offer a method the API then rejects.
    #[serde(default = "Vec::new")]
    pub excluded_ranges: Vec<AmountRange>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One payment method type offered for a payment, with what is needed to
/// render it.
///
/// The nested connector shapes (`payment_experience`, `card_networks`,
/// `required_fields`, `surcharge_details`, …) stay raw JSON: they are open
/// connector-driven shapes, and modelling them here would fail a response the
/// checkout could otherwise render.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ResponsePaymentMethodTypes {
    /// The method sub-type, e.g. `"credit"`, `"ideal"`.
    pub payment_method_type: PaymentMethodType,

    /// Experiences the method can be presented through (open shapes).
    #[serde(default)]
    pub payment_experience: Option<Vec<Value>>,
    /// Card networks offered, each with its own surcharge detail (open shapes).
    #[serde(default)]
    pub card_networks: Option<Vec<Value>>,
    /// Deprecated bank list; use the bank list from `required_fields` instead.
    #[serde(default)]
    pub bank_names: Option<Vec<Value>>,
    /// Bank-debit specifics (open shape).
    #[serde(default)]
    pub bank_debits: Option<Value>,
    /// Bank-transfer specifics (open shape).
    #[serde(default)]
    pub bank_transfers: Option<Value>,
    /// Fields the customer must supply for this method, keyed by field path.
    #[serde(default)]
    pub required_fields: Option<Value>,
    /// Surcharge applied to this method, when the merchant configures one.
    #[serde(default)]
    pub surcharge_details: Option<Value>,
    /// Merchant-internal; omitted for publishable-key callers.
    #[serde(default)]
    pub pm_auth_connector: Option<String>,
    /// Name and icon slug for rendering.
    #[serde(default)]
    pub display: Option<PaymentMethodDisplayInfo>,
    /// The order values this method stays available for.
    #[serde(default)]
    pub amount_limits: Option<PaymentMethodAmountLimits>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The method types offered under one broad payment method (`card`, `wallet`,
/// …).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ResponsePaymentMethodsEnabled {
    /// The broad method family.
    pub payment_method: PaymentMethod,
    /// The sub-types offered under it.
    #[serde(default = "Vec::new")]
    pub payment_method_types: Vec<ResponsePaymentMethodTypes>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What
/// [`PaymentMethods::list`](crate::resources::payment_methods::PaymentMethods::list)
/// returns: the methods available **for a payment**, already filtered by
/// country, order value and the merchant's availability rules.
///
/// An envelope, not an array of saved methods — `GET /payment-methods` is the
/// discovery endpoint. A customer's stored methods come from
/// [`list_for_customer`](crate::resources::payment_methods::PaymentMethods::list_for_customer).
///
/// Only `payment_methods` is required: everything else is a render hint the
/// server may omit, and a missing hint must not fail a checkout that could
/// otherwise draw its tiles.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentMethodListResponse {
    /// The methods available for this payment, grouped by method family.
    #[serde(default = "Vec::new")]
    pub payment_methods: Vec<ResponsePaymentMethodsEnabled>,

    /// The payment's currency.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Where to send the buyer after an off-site step.
    #[serde(default)]
    pub redirect_url: Option<String>,
    /// Mandate type the payment sets up, when any.
    #[serde(default)]
    pub mandate_payment: Option<Value>,
    /// Merchant display name for the checkout.
    #[serde(default)]
    pub merchant_name: Option<String>,
    /// Whether the checkout must show the surcharge breakup screen.
    #[serde(default)]
    pub show_surcharge_breakup_screen: Option<bool>,
    /// Payment type, e.g. `"normal"`.
    #[serde(default)]
    pub payment_type: Option<String>,
    /// Whether external 3DS authentication is requested.
    #[serde(default)]
    pub request_external_three_ds_authentication: Option<bool>,
    /// Whether wallets should collect shipping details.
    #[serde(default)]
    pub collect_shipping_details_from_wallets: Option<bool>,
    /// Whether wallets should collect billing details.
    #[serde(default)]
    pub collect_billing_details_from_wallets: Option<bool>,
    /// Whether tax calculation runs for this payment.
    #[serde(default)]
    pub is_tax_calculation_enabled: Option<bool>,
    /// The next action the SDK should take (open shape).
    #[serde(default)]
    pub sdk_next_action: Option<Value>,
    /// Whether the call resolved no stored customer.
    #[serde(default)]
    pub is_guest_customer: Option<bool>,
    /// Payment intent details, present when the call was made with a client
    /// secret — so a checkout can render without a second round-trip. Open
    /// shape.
    #[serde(default)]
    pub intent_data: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The discovery endpoint answers with an envelope, not an array of saved
    /// methods. Mutation: typing `list` as `Vec<PaymentMethodResponse>` — the
    /// shape this test pins — makes every field below unreachable.
    #[test]
    fn discovery_response_parses_the_envelope_with_display_and_limits() {
        let listed: PaymentMethodListResponse = serde_json::from_str(
            r#"{
                "currency": "EUR",
                "merchant_name": "Shop",
                "payment_methods": [
                    {
                        "payment_method": "card",
                        "payment_method_types": [
                            {
                                "payment_method_type": "credit",
                                "display": {"display_name": "Credit Card", "icon_slug": "card"},
                                "amount_limits": {
                                    "currency": "EUR",
                                    "min_amount": 100,
                                    "max_amount": 500000,
                                    "excluded_ranges": [{"min_amount": 1000, "max_amount": 1999}]
                                }
                            }
                        ]
                    }
                ]
            }"#,
        )
        .unwrap();

        let group = &listed.payment_methods[0];
        let method = &group.payment_method_types[0];
        assert_eq!(
            method.display.as_ref().unwrap().icon_slug.as_deref(),
            Some("card")
        );
        let limits = method.amount_limits.as_ref().unwrap();
        assert_eq!(limits.min_amount, Some(100));
        // The closed excluded band is the field a client reading only the outer
        // bounds would miss — and the backend refuses a create inside it.
        assert_eq!(limits.excluded_ranges[0].min_amount, 1000);
        assert_eq!(limits.excluded_ranges[0].max_amount, 1999);
    }

    /// Render hints are optional: a response carrying only the method list must
    /// still deserialize, or a checkout that could draw its tiles fails instead.
    #[test]
    fn discovery_response_tolerates_missing_render_hints() {
        let listed: PaymentMethodListResponse = serde_json::from_str(
            r#"{"payment_methods":[{"payment_method":"wallet","payment_method_types":[]}]}"#,
        )
        .unwrap();
        assert_eq!(listed.payment_methods.len(), 1);
        assert_eq!(listed.currency, None);
        assert_eq!(listed.sdk_next_action, None);
    }

    /// `is_guest_customer` rides alongside the list and would be lost if the
    /// saved methods were returned as a bare array.
    #[test]
    fn customer_saved_methods_parse_as_an_envelope() {
        let listed: CustomerPaymentMethodsListResponse = serde_json::from_str(
            r#"{
                "customer_payment_methods": [
                    {"merchant_id":"mer_1","payment_method_id":"pm_1","payment_method":"card"}
                ],
                "is_guest_customer": false
            }"#,
        )
        .unwrap();
        assert_eq!(listed.customer_payment_methods[0].payment_method_id, "pm_1");
        assert_eq!(listed.is_guest_customer, Some(false));
    }
}