delopay 0.3.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>,
    /// 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>,
}

#[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"));
    }
}