delopay 0.2.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `payment_links` resource: retrieve and list hosted payment links.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::common::ListResponse;
use crate::core::models::payment_link::PaymentLinkResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

/// The `payment_links` resource, obtained via [`crate::Delopay::payment_links`].
#[derive(Debug, Clone)]
pub struct PaymentLinks {
    inner: Arc<Inner>,
}

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

    /// Retrieve a payment link by its ID.
    pub async fn retrieve(&self, link_id: &str) -> Result<PaymentLinkResponse> {
        let path = format!("/payment-link/{}", encode_segment(link_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List payment links, optionally filtered by creation time.
    ///
    /// The API takes the filters as a JSON body on a POST, not as query
    /// parameters.
    pub async fn list(
        &self,
        params: Option<&PaymentLinkListParams>,
    ) -> Result<ListResponse<PaymentLinkResponse>> {
        let body: Option<Vec<u8>> = match params {
            Some(p) => Some(to_json_vec(p)?),
            None => None,
        };
        self.inner
            .request(
                HttpMethod::Post,
                "/payment-link/list",
                body.as_deref(),
                &[],
                None,
            )
            .await
    }

    /// Initiate (render) a payment link page. Open response shape.
    pub async fn initiate(&self, merchant_id: &str, payment_id: &str) -> Result<Value> {
        let path = format!(
            "/payment-link/{}/{}",
            encode_segment(merchant_id),
            encode_segment(payment_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Get the status of a payment link. Open response shape.
    pub async fn status(&self, merchant_id: &str, payment_id: &str) -> Result<Value> {
        let path = format!(
            "/payment-link/status/{}/{}",
            encode_segment(merchant_id),
            encode_segment(payment_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// Filter parameters for [`PaymentLinks::list`], sent as the JSON body.
///
/// The time filters use dotted wire names (`created.lt`, `created.gte`, …),
/// mapped here to underscore field names.
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentLinkListParams {
    /// Maximum number of links to return.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Only links created at exactly this ISO 8601 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<String>,
    /// Only links created strictly before this ISO 8601 timestamp.
    #[serde(rename = "created.lt", skip_serializing_if = "Option::is_none")]
    pub created_lt: Option<String>,
    /// Only links created strictly after this ISO 8601 timestamp.
    #[serde(rename = "created.gt", skip_serializing_if = "Option::is_none")]
    pub created_gt: Option<String>,
    /// Only links created at/before this ISO 8601 timestamp.
    #[serde(rename = "created.lte", skip_serializing_if = "Option::is_none")]
    pub created_lte: Option<String>,
    /// Only links created at/after this ISO 8601 timestamp.
    #[serde(rename = "created.gte", skip_serializing_if = "Option::is_none")]
    pub created_gte: Option<String>,
}

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

    const LINK_JSON: &str = r#"{
        "link": "https://checkout.test/pay/mer_1/pay_1",
        "payment_link_id": "plink_1"
    }"#;

    #[tokio::test]
    async fn retrieve_gets_the_payment_link_path() {
        let (client, mock) = client_with(vec![Step::ok(LINK_JSON)]);
        let out = client.payment_links().retrieve("plink_1").await.unwrap();
        assert_eq!(out.payment_link_id, "plink_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/payment-link/plink_1");
    }

    #[tokio::test]
    async fn list_posts_filters_with_dotted_wire_names() {
        // The list endpoint POSTs its filters as a body, and the range keys
        // are dotted (`created.lte`) — dropping either the POST or the serde
        // rename must fail here.
        let (client, mock) = client_with(vec![Step::ok(r#"{"size":0,"data":[]}"#)]);
        let params = PaymentLinkListParams {
            limit: Some(10),
            created_lte: Some("2026-01-01T00:00:00Z".to_string()),
            ..Default::default()
        };
        client.payment_links().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payment-link/list");
        let body = seen[0].body_json();
        assert_eq!(body["limit"], 10);
        assert_eq!(body["created.lte"], "2026-01-01T00:00:00Z");
    }

    #[tokio::test]
    async fn initiate_and_status_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"html":"..."}"#),
            Step::ok(r#"{"status":"paid"}"#),
        ]);
        client
            .payment_links()
            .initiate("mer_1", "pay_1")
            .await
            .unwrap();
        client
            .payment_links()
            .status("mer_1", "pay_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/payment-link/mer_1/pay_1");
        assert_eq!(
            seen[1].url,
            "https://api.test/payment-link/status/mer_1/pay_1"
        );
    }
}