delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The merchant account model.
//!
//! `Debug` 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]";

/// A merchant account as returned by the API.
///
/// Only [`merchant_id`](MerchantAccountResponse::merchant_id) is required: the
/// delete endpoint answers with a trimmed `{merchant_id, deleted}` object, so
/// every other field is optional rather than a hard deserialization failure.
///
/// Unmodeled fields are preserved in [`extra`](MerchantAccountResponse::extra).
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantAccountResponse {
    /// Unique merchant account ID.
    pub merchant_id: String,

    /// Display name for the merchant.
    #[serde(default)]
    pub merchant_name: Option<String>,
    /// Organization the merchant account belongs to.
    #[serde(default)]
    pub organization_id: Option<String>,
    /// Account kind: `"standard"`, `"platform"` or `"connected"`.
    #[serde(default)]
    pub merchant_account_type: 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>,
    /// Default URL customers are returned to after a payment.
    #[serde(default)]
    pub return_url: Option<String>,
    /// Primary business details (open shapes — see the API reference).
    #[serde(default)]
    pub primary_business_details: Option<Vec<Value>>,
    /// Whether reconciliation is enabled.
    #[serde(default)]
    pub is_recon_enabled: Option<bool>,
    /// Reconciliation status.
    #[serde(default)]
    pub recon_status: Option<String>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials**:
    /// redacted by [`Debug`].
    #[serde(default)]
    pub webhook_details: Option<Value>,
    /// Whether this merchant may own sub-merchants.
    #[serde(default)]
    pub sub_merchants_enabled: Option<bool>,
    /// Parent merchant, when this account is a sub-merchant.
    #[serde(default)]
    pub parent_merchant_id: Option<String>,
    /// Publishable (client-side) key.
    #[serde(default)]
    pub publishable_key: Option<String>,
    /// Arbitrary metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// ISO 8601 last-modified timestamp.
    #[serde(default)]
    pub modified_at: Option<String>,
    /// Whether the account was deleted, on the delete endpoint's response.
    #[serde(default)]
    pub deleted: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for MerchantAccountResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MerchantAccountResponse")
            .field("merchant_id", &self.merchant_id)
            .field("merchant_name", &self.merchant_name)
            .field("organization_id", &self.organization_id)
            .field("merchant_account_type", &self.merchant_account_type)
            .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("primary_business_details", &self.primary_business_details)
            .field("is_recon_enabled", &self.is_recon_enabled)
            .field("recon_status", &self.recon_status)
            .field(
                "webhook_details",
                &self.webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("sub_merchants_enabled", &self.sub_merchants_enabled)
            .field("parent_merchant_id", &self.parent_merchant_id)
            .field("publishable_key", &self.publishable_key)
            .field("metadata", &self.metadata)
            .field("created_at", &self.created_at)
            .field("modified_at", &self.modified_at)
            .field("deleted", &self.deleted)
            .field("extra", &self.extra)
            .finish()
    }
}

#[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: MerchantAccountResponse = serde_json::from_str(
            r#"{
                "merchant_id": "mer_1",
                "merchant_name": "Acme",
                "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("Acme"), "{rendered}");
        assert!(rendered.contains("mer_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: MerchantAccountResponse =
            serde_json::from_str(r#"{"merchant_id":"mer_1"}"#).unwrap();
        let rendered = format!("{parsed:?}");
        assert!(
            rendered.contains("payment_response_hash_key: None"),
            "{rendered}"
        );
    }

    /// The trimmed delete-endpoint shape must deserialize, and unknown fields
    /// must survive. Mutation: making any field other than `merchant_id`
    /// required makes the first call fail.
    #[test]
    fn parses_the_trimmed_delete_shape_and_keeps_unknown_fields() {
        let parsed: MerchantAccountResponse =
            serde_json::from_str(r#"{"merchant_id":"mer_1","deleted":true}"#).unwrap();
        assert_eq!(parsed.deleted, Some(true));
        assert_eq!(parsed.merchant_name, None);

        let parsed: MerchantAccountResponse = serde_json::from_str(
            r#"{"merchant_id":"mer_1","recon_status":"not_requested","brand_new_field":"x"}"#,
        )
        .unwrap();
        assert_eq!(parsed.recon_status.as_deref(), Some("not_requested"));
        assert_eq!(parsed.extra.get("brand_new_field"), Some(&Value::from("x")));
        assert!(!parsed.extra.contains_key("recon_status"));
    }
}