delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The payment intent model.

use std::fmt;

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

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

/// A payment intent as returned by the API.
///
/// Unmodeled fields are preserved in [`extra`](PaymentResponse::extra) so new
/// API fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentResponse {
    /// Unique payment intent ID.
    pub payment_id: String,
    /// Merchant account ID that owns this payment.
    pub merchant_id: String,
    /// Current lifecycle status.
    pub status: IntentStatus,
    /// Authorized amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,

    /// Net amount after discounts and tax, in minor units.
    #[serde(default)]
    pub net_amount: Option<i64>,
    /// Amount still available to capture, in minor units.
    #[serde(default)]
    pub amount_capturable: Option<i64>,
    /// Actual captured amount, in minor units (present after capture).
    #[serde(default)]
    pub amount_received: Option<i64>,
    /// Client secret for client-side confirmation. Do not log or share it:
    /// it authorises completing this payment. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Connector used to process this payment.
    #[serde(default)]
    pub connector: Option<String>,
    /// Associated customer ID.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Payment method family used.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Gateway error code, if the payment failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, if the payment failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Instructions for additional customer action (3DS redirect, etc.).
    #[serde(default)]
    pub next_action: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created: Option<String>,
    /// Arbitrary metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Which environment this payment ran in. Echoes the `test_mode` sent at
    /// create; filled in from the processor's own setting when none was sent,
    /// and `None` for a payment that never reached a processor. `None` counts
    /// as live wherever it is filtered on.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `client_secret` authorises client-side
// confirmation of this payment, so anything holding it can complete the
// charge. A `{:?}` on a payment is the most likely way it reaches a log, and
// payments are logged constantly. The field's presence is still visible --
// `Some("[redacted]")` vs `None` -- because whether a secret was issued is
// often what you are debugging.
//
// Only the *modeled* secret is covered: `extra` is printed in full, so a
// secret the API starts returning under an unmodeled key would still show up
// here until it is modeled.
impl fmt::Debug for PaymentResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PaymentResponse")
            .field("payment_id", &self.payment_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field("net_amount", &self.net_amount)
            .field("amount_capturable", &self.amount_capturable)
            .field("amount_received", &self.amount_received)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("connector", &self.connector)
            .field("customer_id", &self.customer_id)
            .field("profile_id", &self.profile_id)
            .field("payment_method", &self.payment_method)
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("next_action", &self.next_action)
            .field("created", &self.created)
            .field("metadata", &self.metadata)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A single attempt made on a payment, with its full failure detail. Returned
/// in the `data` array of `Payments::list_attempts` — useful for surfacing
/// retries across connectors (e.g. "attempt 1 stripe → insufficient_funds,
/// attempt 2 adyen → success").
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentAttemptResponse {
    /// Unique identifier for this attempt.
    pub attempt_id: String,
    /// Status of this attempt (distinct from the parent intent's status).
    pub status: AttemptStatus,

    /// Attempt amount in minor units.
    #[serde(default)]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Connector (gateway) this attempt was routed to, e.g. `"stripe"`.
    #[serde(default)]
    pub connector: Option<String>,
    /// Connector's transaction identifier for this attempt.
    #[serde(default)]
    pub connector_transaction_id: Option<String>,
    /// Payment method family used for this attempt.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Payment method sub-type used for this attempt.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Raw connector error code, when the attempt failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the attempt failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Delopay-unified decline code (from the gateway status map).
    #[serde(default)]
    pub unified_code: Option<String>,
    /// Delopay-unified, human-readable decline message.
    #[serde(default)]
    pub unified_message: Option<String>,
    /// When the attempt was created (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// When the attempt was last modified (RFC 3339).
    #[serde(default)]
    pub modified_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One event on a payment's status timeline: the creation of, or a status
/// transition on, the payment intent or one of its attempts / refunds /
/// disputes.
///
/// [`entity_type`](Self::entity_type) is a plain `String` rather than an enum
/// so a new timeline event kind does not fail the whole response. The values
/// sent today are `"payment"`, `"attempt"`, `"refund"`, `"dispute"`, `"risk"`
/// and `"checkout"`. The last two are timeline events with **no underlying
/// status change**: `status` holds the event name rather than a payment state,
/// and `entity_id` names what it is about (the processor's risk-signal id, or
/// the native-pane method key).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryEvent {
    /// What the event is about: `"payment"`, `"attempt"`, `"refund"`,
    /// `"dispute"`, `"risk"` or `"checkout"`.
    pub entity_type: String,
    /// RFC 3339 timestamp of the event.
    pub timestamp: String,

    /// Id of the attempt / refund / dispute the event belongs to. Absent for
    /// intent-level events.
    #[serde(default)]
    pub entity_id: Option<String>,
    /// The attempt this event is associated with, where known.
    #[serde(default)]
    pub attempt_id: Option<String>,
    /// The status before this event. Absent on creation and derived events.
    #[serde(default)]
    pub previous_status: Option<String>,
    /// The status after this event. Absent only on a derived creation event,
    /// where the initial status was not recorded.
    #[serde(default)]
    pub status: Option<String>,
    /// Connector involved in the event, where known.
    #[serde(default)]
    pub connector: Option<String>,
    /// Raw connector error code recorded with the event.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message recorded with the event.
    #[serde(default)]
    pub error_message: Option<String>,
    /// `true` when this event records the creation of the entity.
    #[serde(default)]
    pub is_creation: bool,
    /// `true` when this event was reconstructed from current records (payments
    /// predating the persisted status log) — its timestamp is approximate and
    /// intermediate transitions may be missing.
    #[serde(default)]
    pub derived: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The status timeline of a payment, returned by
/// [`Payments::list_status_history`](crate::resources::payments::Payments::list_status_history).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryResponse {
    /// The payment this timeline belongs to.
    pub payment_id: String,
    /// `true` when every event comes from the persisted status-transition log;
    /// `false` when any event had to be reconstructed from current records.
    #[serde(default)]
    pub complete: bool,
    /// The number of events returned.
    #[serde(default)]
    pub count: i64,
    /// All recorded events, oldest first.
    #[serde(default = "Vec::new")]
    pub events: Vec<PaymentStatusHistoryEvent>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    const WITH_SECRET: &str = r#"{
        "payment_id": "pay_1", "merchant_id": "mer_1", "status": "requires_confirmation",
        "amount": 1999, "currency": "EUR", "client_secret": "pay_1_secret_abc123"
    }"#;

    /// Kills a `Debug` that prints `&self.client_secret`, and a derived one.
    #[test]
    fn payment_response_debug_redacts_the_client_secret() {
        let res: PaymentResponse = serde_json::from_str(WITH_SECRET).unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("pay_1_secret_abc123"));
        assert!(printed.contains("client_secret: Some(\"[redacted]\")"));
        // Non-secret fields must still be readable, or the redaction has cost
        // more than it bought.
        assert!(printed.contains("pay_1"));
        assert!(printed.contains("1999"));
    }

    /// Kills a `Debug` that hard-codes `Some("[redacted]")` regardless of the
    /// field, which would hide whether a secret was ever issued.
    #[test]
    fn payment_response_debug_shows_none_when_no_client_secret() {
        let res: PaymentResponse = serde_json::from_str(
            r#"{"payment_id":"pay_1","merchant_id":"mer_1","status":"succeeded",
                "amount":1999,"currency":"EUR"}"#,
        )
        .unwrap();
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    /// A partially reconstructed timeline must stay readable, and a `risk` /
    /// `checkout` event — which carries an event name in `status` and no
    /// transition — must not be rejected. Mutation: typing `entity_type` as a
    /// closed enum makes the last two events fail to parse.
    #[test]
    fn status_history_parses_derived_and_non_status_events() {
        let history: PaymentStatusHistoryResponse = serde_json::from_str(
            r#"{
                "payment_id": "pay_1",
                "complete": false,
                "count": 3,
                "events": [
                    {
                        "entity_type": "payment",
                        "timestamp": "2026-08-01T10:00:00Z",
                        "status": "requires_confirmation",
                        "is_creation": true,
                        "derived": true
                    },
                    {
                        "entity_type": "attempt",
                        "entity_id": "pay_1_1",
                        "attempt_id": "pay_1_1",
                        "previous_status": "pending",
                        "status": "charged",
                        "connector": "stripe",
                        "timestamp": "2026-08-01T10:00:05Z",
                        "is_creation": false,
                        "derived": false
                    },
                    {
                        "entity_type": "checkout",
                        "entity_id": "apple_pay",
                        "status": "native_pane_selected",
                        "timestamp": "2026-08-01T10:00:03Z",
                        "is_creation": false,
                        "derived": false
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(history.payment_id, "pay_1");
        assert!(!history.complete);
        assert_eq!(history.count, 3);
        assert!(history.events[0].derived);
        assert!(history.events[0].is_creation);
        assert_eq!(history.events[0].previous_status, None);
        assert_eq!(history.events[1].connector.as_deref(), Some("stripe"));
        assert_eq!(history.events[2].entity_type, "checkout");
        assert_eq!(
            history.events[2].status.as_deref(),
            Some("native_pane_selected")
        );
    }

    /// A timeline with no events must deserialize to an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn status_history_defaults_to_no_events() {
        let history: PaymentStatusHistoryResponse =
            serde_json::from_str(r#"{"payment_id":"pay_1"}"#).unwrap();
        assert!(history.events.is_empty());
        assert!(!history.complete);
    }
}