delopay 0.2.1

Official Rust SDK for the DeloPay payments API
Documentation
//! The `ephemeral_keys` resource: short-lived keys for secure client-side
//! access to one customer's data.

use std::sync::Arc;

use serde::Serialize;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::ephemeral_key::EphemeralKeyResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

/// The `ephemeral_keys` resource, obtained via [`crate::Delopay::ephemeral_keys`].
///
/// Ephemeral keys grant a mobile or browser client temporary access to a
/// specific customer's data (e.g. to display saved payment methods) without
/// exposing your secret API key.
#[derive(Debug, Clone)]
pub struct EphemeralKeys {
    inner: Arc<Inner>,
}

#[derive(Serialize)]
struct EphemeralKeyCreateBody<'a> {
    customer_id: &'a str,
}

impl EphemeralKeys {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create an ephemeral key scoped to one customer. Hand the returned
    /// [`secret`](EphemeralKeyResponse::secret) to your client app.
    pub async fn create(&self, customer_id: &str) -> Result<EphemeralKeyResponse> {
        let body = to_json_vec(&EphemeralKeyCreateBody { customer_id })?;
        self.inner
            .request(HttpMethod::Post, "/ephemeral-keys", Some(&body), &[], None)
            .await
    }

    /// Invalidate an ephemeral key before it expires.
    pub async fn delete(&self, key_id: &str) -> Result<EphemeralKeyResponse> {
        let path = format!("/ephemeral-keys/{}", encode_segment(key_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }
}

#[cfg(test)]
mod tests {
    use crate::http::mock::{Step, client_with};

    const KEY_JSON: &str = r#"{
        "customer_id": "cus_1", "created_at": 1700000000,
        "expires": 1700003600, "secret": "epk_secret"
    }"#;

    #[tokio::test]
    async fn create_posts_the_customer_id() {
        let (client, mock) = client_with(vec![Step::ok(KEY_JSON)]);
        let key = client.ephemeral_keys().create("cus_1").await.unwrap();
        assert_eq!(key.secret, "epk_secret");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/ephemeral-keys");
        assert_eq!(seen[0].body_json()["customer_id"], "cus_1");
    }

    #[tokio::test]
    async fn delete_targets_the_key_path() {
        let (client, mock) = client_with(vec![Step::ok(KEY_JSON)]);
        client.ephemeral_keys().delete("epk_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/ephemeral-keys/epk_1");
    }
}