delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The connector (merchant connector account) models.
//!
//! `Debug` on [`ConnectorResponse`] and [`ConnectorWebhookRegisterResponse`] is
//! hand-written: the API echoes back credential-shaped fields
//! (`connector_account_details`, `connector_webhook_details`, and the
//! connector-minted `webhook_secret`), and a derived `Debug` would put them in
//! a log line.

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

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

/// A merchant connector account as returned by the API.
///
/// Only [`merchant_connector_id`](ConnectorResponse::merchant_connector_id) is
/// required: the delete endpoint answers with a trimmed object carrying just
/// the ids, so everything else is optional rather than a hard deserialization
/// failure.
///
/// Unmodeled fields are preserved in [`extra`](ConnectorResponse::extra).
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorResponse {
    /// Unique connector account ID, e.g. `"mca_…"`.
    pub merchant_connector_id: String,

    /// Connector category, e.g. `"payment_processor"`, `"payout_processor"`.
    #[serde(default)]
    pub connector_type: Option<String>,
    /// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
    #[serde(default)]
    pub connector_name: Option<String>,
    /// Shop (business profile) the connector belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account that owns the connector.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Connector status, e.g. `"active"` or `"inactive"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Human-readable label, unique within the merchant account.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// Gateway credentials, masked by the API. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_account_details: Option<Value>,
    /// Payment methods enabled on this connector (open shapes).
    #[serde(default)]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled.
    #[serde(default)]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_webhook_details: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// Whether the connector 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 ConnectorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorResponse")
            .field("merchant_connector_id", &self.merchant_connector_id)
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("profile_id", &self.profile_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("connector_label", &self.connector_label)
            .field(
                "connector_account_details",
                &self.connector_account_details.as_ref().map(|_| REDACTED),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &self.connector_webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("created_at", &self.created_at)
            .field("deleted", &self.deleted)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Result of registering a webhook endpoint with a connector.
///
/// `webhook_secret` is the signing secret the connector minted for the new
/// endpoint (e.g. Stripe's `whsec_…`). It is already persisted server-side into
/// the connector's webhook verification details; [`Debug`] redacts it.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookRegisterResponse {
    /// Whether the registration succeeded: `"success"` or `"failure"`.
    pub webhook_registration_status: String,

    /// Event scope registered: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set registered against: `"live"` or `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// The connector's identifier for the registered endpoint.
    #[serde(default)]
    pub connector_webhook_id: Option<String>,
    /// Signing secret the connector minted for the endpoint. **Secret**:
    /// redacted by [`Debug`].
    #[serde(default)]
    pub webhook_secret: Option<String>,
    /// Error code, when the registration failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the registration failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorWebhookRegisterResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorWebhookRegisterResponse")
            .field(
                "webhook_registration_status",
                &self.webhook_registration_status,
            )
            .field("event_type", &self.event_type)
            .field("environment", &self.environment)
            .field("connector_webhook_id", &self.connector_webhook_id)
            .field(
                "webhook_secret",
                &self.webhook_secret.as_ref().map(|_| REDACTED),
            )
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("extra", &self.extra)
            .finish()
    }
}

/// One webhook endpoint registered with a connector.
///
/// Carries no secret: the signing secret is only ever returned at registration
/// time, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookEntry {
    /// The connector's identifier for this endpoint.
    pub connector_webhook_id: String,

    /// Event scope: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set the endpoint belongs to. Absent for registrations stored
    /// before environments were tracked (those are all live).
    #[serde(default)]
    pub environment: Option<String>,
    /// Callback URL the endpoint is registered to. Present when the list is
    /// sourced live from the connector (e.g. Stripe); absent for entries
    /// reconstructed from stored registration metadata only.
    #[serde(default)]
    pub webhook_url: Option<String>,
    /// Endpoint status as the connector reports it, e.g. `"enabled"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Events the endpoint is subscribed to at the connector.
    #[serde(default)]
    pub enabled_events: Option<Vec<String>>,
    /// Unix timestamp (seconds) the endpoint was created at the connector.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The webhook endpoints registered for one connector.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookListResponse {
    /// Snake-case connector identifier the endpoints belong to.
    pub connector: String,
    /// The registered endpoints.
    #[serde(default = "Vec::new")]
    pub webhooks: Vec<ConnectorWebhookEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    /// Credentials the API echoes back must not reach a log line. Mutation:
    /// print `&self.connector_account_details` instead of the redacted map —
    /// the first assertion goes red.
    #[test]
    fn connector_response_debug_redacts_credentials() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{
                "merchant_connector_id": "mca_1",
                "connector_name": "stripe",
                "connector_account_details": {"api_key": "sk_live_supersecret"},
                "connector_webhook_details": {"merchant_secret": "whsec_topsecret"}
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(
            rendered.contains("connector_account_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(
            rendered.contains("connector_webhook_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("stripe"), "{rendered}");
        assert!(rendered.contains("mca_1"), "{rendered}");
    }

    /// An absent credential must be distinguishable from a present one.
    /// Mutation: `map(|_| REDACTED)` -> `map_or(Some(REDACTED), ...)`-style
    /// unconditional redaction makes this red.
    #[test]
    fn connector_response_debug_shows_none_for_absent_credentials() {
        let parsed: ConnectorResponse =
            serde_json::from_str(r#"{"merchant_connector_id":"mca_1"}"#).unwrap();
        let rendered = format!("{parsed:?}");
        assert!(
            rendered.contains("connector_account_details: None"),
            "{rendered}"
        );
    }

    /// Unknown fields land in `extra`, and known ones do not. Mutation:
    /// dropping `#[serde(flatten)]` from `extra` makes the lookup return
    /// `None`.
    #[test]
    fn connector_response_keeps_unknown_fields() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{"merchant_connector_id":"mca_1","status":"active","brand_new_field":42}"#,
        )
        .unwrap();
        assert_eq!(parsed.status.as_deref(), Some("active"));
        assert_eq!(parsed.extra.get("brand_new_field"), Some(&Value::from(42)));
        assert!(!parsed.extra.contains_key("status"));
    }

    /// The register response's minted signing secret must not print. Mutation:
    /// print `&self.webhook_secret` directly.
    #[test]
    fn register_response_debug_redacts_the_webhook_secret() {
        let parsed: ConnectorWebhookRegisterResponse = serde_json::from_str(
            r#"{
                "webhook_registration_status": "success",
                "event_type": "all_events",
                "environment": "sandbox",
                "connector_webhook_id": "we_1",
                "webhook_secret": "whsec_minted",
                "error_code": null,
                "error_message": null
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("whsec_minted"), "{rendered}");
        assert!(
            rendered.contains("webhook_secret: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(rendered.contains("we_1"), "{rendered}");
        assert_eq!(parsed.webhook_registration_status, "success");
        assert_eq!(parsed.environment.as_deref(), Some("sandbox"));
        assert_eq!(parsed.error_code, None);
    }

    /// A specific-event scope stays a structured value, and the list endpoint's
    /// entries deserialize. Mutation: typing `event_type` as `Option<String>`
    /// makes the object form fail to parse.
    #[test]
    fn webhook_list_parses_entries_and_structured_event_types() {
        let parsed: ConnectorWebhookListResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "webhooks": [
                    {
                        "connector_webhook_id": "we_1",
                        "event_type": {"specific_event": "payment_intent.succeeded"},
                        "enabled_events": ["payment_intent.succeeded"],
                        "created_at": 1700000000
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.connector, "stripe");
        assert_eq!(parsed.webhooks.len(), 1);
        let entry = &parsed.webhooks[0];
        assert_eq!(entry.connector_webhook_id, "we_1");
        assert_eq!(
            entry.event_type.as_ref().unwrap()["specific_event"],
            "payment_intent.succeeded"
        );
        assert_eq!(entry.created_at, Some(1_700_000_000));
        assert_eq!(entry.environment, None);
    }

    /// A response with no `webhooks` key must yield an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn webhook_list_defaults_to_no_webhooks() {
        let parsed: ConnectorWebhookListResponse =
            serde_json::from_str(r#"{"connector":"adyen"}"#).unwrap();
        assert!(parsed.webhooks.is_empty());
    }
}