delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The shop (business profile) models, plus the acquirer identities a shop
//! presents per card network.
//!
//! `Debug` on [`ProfileResponse`] is hand-written: the API echoes
//! `payment_response_hash_key` (the secret used to sign payment responses) and
//! `webhook_details` (which can hold outgoing-webhook credentials), so a
//! derived `Debug` would leak both into logs.

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

/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";

/// Custom format for generated payment ids (cloaking), e.g. `ORD-74219807`.
///
/// Absent means the default `pay_<random>` ids. Every field is optional: the
/// API may add or drop parts of the config without breaking deserialization.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentIdFormatConfig {
    /// Static prefix, e.g. `"ORD-"`. May be empty.
    #[serde(default)]
    pub prefix: Option<String>,
    /// Charset used for the random body of the id.
    #[serde(default)]
    pub style: Option<String>,
    /// Length of the random body.
    #[serde(default)]
    pub length: Option<i64>,
    /// Any additional fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A shop (business profile) as returned by the API.
///
/// Only [`profile_id`](ProfileResponse::profile_id) is required: the delete and
/// toggle endpoints answer with trimmed objects, so every other field is
/// optional rather than a hard deserialization failure.
///
/// Unmodeled fields are preserved in [`extra`](ProfileResponse::extra).
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileResponse {
    /// Unique shop (business profile) ID.
    pub profile_id: String,

    /// Merchant account that owns the shop.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Display name for the shop.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// Whether payment responses are signed.
    #[serde(default)]
    pub enable_payment_response_hash: Option<bool>,
    /// Signing key for payment response hashes. **Secret**: redacted by
    /// [`Debug`].
    #[serde(default)]
    pub payment_response_hash_key: Option<String>,
    /// Whether the customer is redirected back with an HTTP POST.
    #[serde(default)]
    pub redirect_to_merchant_with_http_post: Option<bool>,
    /// URL customers are returned to after a payment.
    #[serde(default)]
    pub return_url: Option<String>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials**:
    /// redacted by [`Debug`].
    #[serde(default)]
    pub webhook_details: Option<Value>,
    /// Whether a tax connector is enabled for the shop.
    #[serde(default)]
    pub is_tax_connector_enabled: Option<bool>,
    /// Whether network tokenization is enabled.
    #[serde(default)]
    pub is_network_tokenization_enabled: Option<bool>,
    /// Whether automatic retries are enabled.
    #[serde(default)]
    pub is_auto_retries_enabled: Option<bool>,
    /// Whether Click to Pay is enabled.
    #[serde(default)]
    pub is_click_to_pay_enabled: Option<bool>,
    /// Whether retries with a clear PAN are enabled.
    #[serde(default)]
    pub is_clear_pan_retries_enabled: Option<bool>,
    /// Whether every card payment is forced through a 3DS challenge.
    #[serde(default)]
    pub force_3ds_challenge: Option<bool>,
    /// Whether pre-network tokenization is enabled.
    #[serde(default)]
    pub is_pre_network_tokenization_enabled: Option<bool>,
    /// Origins permitted to embed this shop's hosted checkout in an iframe.
    /// Each entry is a full origin (`scheme://host[:port]`, no path). Empty or
    /// absent means same-origin only.
    #[serde(default)]
    pub iframe_allowed_origins: Option<Vec<String>>,
    /// Merchant connector account ID of the billing processor (e.g. Stripe
    /// Billing / PayPal) that owns this shop's native subscriptions.
    #[serde(default)]
    pub billing_processor_id: Option<String>,
    /// Custom format for generated payment ids (cloaking).
    #[serde(default)]
    pub payment_id_format: Option<PaymentIdFormatConfig>,
    /// Arbitrary metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ProfileResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProfileResponse")
            .field("profile_id", &self.profile_id)
            .field("merchant_id", &self.merchant_id)
            .field("profile_name", &self.profile_name)
            .field(
                "enable_payment_response_hash",
                &self.enable_payment_response_hash,
            )
            .field(
                "payment_response_hash_key",
                &self.payment_response_hash_key.as_ref().map(|_| REDACTED),
            )
            .field(
                "redirect_to_merchant_with_http_post",
                &self.redirect_to_merchant_with_http_post,
            )
            .field("return_url", &self.return_url)
            .field(
                "webhook_details",
                &self.webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("is_tax_connector_enabled", &self.is_tax_connector_enabled)
            .field(
                "is_network_tokenization_enabled",
                &self.is_network_tokenization_enabled,
            )
            .field("is_auto_retries_enabled", &self.is_auto_retries_enabled)
            .field("is_click_to_pay_enabled", &self.is_click_to_pay_enabled)
            .field(
                "is_clear_pan_retries_enabled",
                &self.is_clear_pan_retries_enabled,
            )
            .field("force_3ds_challenge", &self.force_3ds_challenge)
            .field(
                "is_pre_network_tokenization_enabled",
                &self.is_pre_network_tokenization_enabled,
            )
            .field("iframe_allowed_origins", &self.iframe_allowed_origins)
            .field("billing_processor_id", &self.billing_processor_id)
            .field("payment_id_format", &self.payment_id_format)
            .field("metadata", &self.metadata)
            .field("extra", &self.extra)
            .finish()
    }
}

/// An acquirer identity a shop (business profile) presents for one card
/// network: the acquirer BIN, the merchant ID the acquirer assigned, and the
/// acquirer-reported fraud rate.
///
/// Carries no credential, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileAcquirerResponse {
    /// Unique profile-acquirer ID.
    pub profile_acquirer_id: String,
    /// Shop (business profile) the identity belongs to.
    pub profile_id: String,

    /// Merchant ID the acquirer assigned to this shop.
    #[serde(default)]
    pub acquirer_assigned_merchant_id: Option<String>,
    /// Merchant name as registered with the acquirer.
    #[serde(default)]
    pub merchant_name: Option<String>,
    /// Card network this identity applies to, e.g. `"Visa"`.
    #[serde(default)]
    pub network: Option<String>,
    /// Acquirer BIN.
    #[serde(default)]
    pub acquirer_bin: Option<String>,
    /// Acquirer ICA, where the network requires one.
    #[serde(default)]
    pub acquirer_ica: Option<String>,
    /// Acquirer-reported fraud rate.
    #[serde(default)]
    pub acquirer_fraud_rate: Option<f64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    /// The response-signing key and webhook credentials must not reach a log
    /// line. Mutation: print `&self.payment_response_hash_key` instead of the
    /// redacted map — the first assertion goes red.
    #[test]
    fn debug_redacts_the_signing_key_and_webhook_details() {
        let parsed: ProfileResponse = serde_json::from_str(
            r#"{
                "profile_id": "pro_1",
                "profile_name": "Shop",
                "payment_response_hash_key": "hashkey_supersecret",
                "webhook_details": {"webhook_password": "hunter2"}
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("hashkey_supersecret"), "{rendered}");
        assert!(!rendered.contains("hunter2"), "{rendered}");
        assert!(
            rendered.contains("payment_response_hash_key: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(
            rendered.contains("webhook_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("Shop"), "{rendered}");
        assert!(rendered.contains("pro_1"), "{rendered}");
    }

    /// An absent secret must be distinguishable from a present one. Mutation:
    /// redacting unconditionally makes this red.
    #[test]
    fn debug_shows_none_for_absent_secrets() {
        let parsed: ProfileResponse = serde_json::from_str(r#"{"profile_id":"pro_1"}"#).unwrap();
        let rendered = format!("{parsed:?}");
        assert!(
            rendered.contains("payment_response_hash_key: None"),
            "{rendered}"
        );
    }

    /// The nested id-format config is typed, and unknown top-level fields
    /// survive. Mutation: typing `payment_id_format` as `Option<String>` makes
    /// the parse fail; dropping `#[serde(flatten)]` on `extra` makes the last
    /// lookup return `None`.
    #[test]
    fn parses_the_payment_id_format_and_keeps_unknown_fields() {
        let parsed: ProfileResponse = serde_json::from_str(
            r#"{
                "profile_id": "pro_1",
                "force_3ds_challenge": true,
                "iframe_allowed_origins": ["https://shop.test"],
                "payment_id_format": {"prefix": "ORD-", "style": "alphanumeric", "length": 8},
                "brand_new_field": "x"
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.force_3ds_challenge, Some(true));
        assert_eq!(
            parsed.iframe_allowed_origins.as_deref(),
            Some(["https://shop.test".to_string()].as_slice())
        );
        let format = parsed.payment_id_format.as_ref().unwrap();
        assert_eq!(format.prefix.as_deref(), Some("ORD-"));
        assert_eq!(format.length, Some(8));
        assert_eq!(parsed.extra.get("brand_new_field"), Some(&Value::from("x")));
        assert!(!parsed.extra.contains_key("force_3ds_challenge"));
    }

    /// The acquirer identity deserializes with its numeric fraud rate and keeps
    /// unknown fields. Mutation: typing `acquirer_fraud_rate` as
    /// `Option<String>` makes this fail to parse.
    #[test]
    fn profile_acquirer_parses_and_keeps_unknown_fields() {
        let parsed: ProfileAcquirerResponse = serde_json::from_str(
            r#"{
                "profile_acquirer_id": "pa_1",
                "profile_id": "pro_1",
                "acquirer_assigned_merchant_id": "acq_mid_1",
                "merchant_name": "Acme",
                "network": "Visa",
                "acquirer_bin": "412345",
                "acquirer_fraud_rate": 0.02,
                "brand_new_field": true
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.profile_acquirer_id, "pa_1");
        assert_eq!(parsed.acquirer_fraud_rate, Some(0.02));
        assert_eq!(parsed.acquirer_ica, None);
        assert_eq!(
            parsed.extra.get("brand_new_field"),
            Some(&Value::from(true))
        );
        assert!(!parsed.extra.contains_key("network"));
    }
}