delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation

delopay

Official server-side Rust SDK for the DeloPay payments API. Typed, async, hyper-based, with a constant-time webhook verifier.

Covers the full merchant API: payments, hosted checkout and payment links, webhook verification, refunds, customers, payouts, disputes with evidence, PayPal seller cases, mandates, payment methods, events, subscriptions, ephemeral keys, poll and export, plus account configuration (merchant accounts, shops and business profiles, connectors and their health, API keys, routing and surcharge rules, regions, fees, 3DS authentication, Apple Pay verification, Stripe Connect onboarding) and reporting (projects, billing, settlement, users and roles).

Installation

You also need an async runtime (tokio).

[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
delopay = "0.13"

Webhook-only build (no HTTP client)

If a service only needs to verify incoming webhooks and read the wire models, disable the default client feature. That build has no hyper, tokio, or async runtime, pulls 26 crates instead of 64, and is pure Rust, so no C toolchain is required:

delopay = { version = "0.13", default-features = false }

webhooks::verify, WebhookEvent, DelopayError, and all the *Response models are available; Delopay, the request builders, and the resources module are not.

Create a payment with hosted checkout

use delopay::{Delopay, PaymentCreateRequest};

#[tokio::main]
async fn main() -> delopay::Result<()> {
    // `prd_...` = production, `snd_...` = sandbox (use Delopay::sandbox).
    let client = Delopay::new("prd_your_secret_key");

    let payment = client
        .payments()
        .create_idempotent(
            &PaymentCreateRequest::new(1999, "EUR") // 19.99 EUR, minor units
                .profile_id("pro_your_shop_id")
                .payment_link(true)
                .return_url("https://your-shop.example/return")
                .customer_email("ada@example.com")
                .test_mode(false), // true → the processor's sandbox
            "order_1001", // idempotency key, safe to retry
        )
        .await?;

    // Redirect the shopper to the hosted checkout:
    let url = client.hosted_checkout_url(&payment.merchant_id, &payment.payment_id);
    println!("go to {url}");
    Ok(())
}

The return page is not the source of truth. Reconcile status from the webhook, or client.payments().retrieve_synced(&id).

Test or live

test_mode decides which environment a payment runs in: true runs it against the processor's sandbox and keeps it out of live reporting, false runs it live, and omitting it runs it live. Drive it from the environment your process is in —

.test_mode(std::env::var("APP_ENV").as_deref() != Ok("production"))

— and a staging deploy can never take a real card, while production never has to remember to switch anything back. It is read only at create; confirm and update ignore it, since those can be called from the browser with a client secret.

One caveat worth knowing: a processor with no sandbox credentials stored is called with the only credentials it has, so a payment marked as a test still charges for real. PaymentResponse::test_mode echoes back what actually happened — check it before you act on succeeded.

Verify a webhook

DeloPay signs each webhook with HMAC-SHA512 over the raw body; the hex digest arrives in the X-Webhook-Signature-512 header. Verify the raw bytes before parsing:

use delopay::webhooks;

// raw_body: &[u8] captured before JSON parsing; sig: the header value.
let event = webhooks::verify(raw_body, sig, "whsec_your_shop_secret")?;
if event.event_type == "payment_succeeded" {
    if let Some(payment) = event.content.as_payment() {
        // fulfil the order for payment.payment_id
    }
}

Subscriptions

Subscription endpoints are profile-scoped; the backend requires an x-profile-id header. Scope the resource once:

let subscriptions = client.subscriptions().with_profile_id("pro_your_shop_id");
let sub = subscriptions.retrieve("sub_123").await?;

Idempotency

A key makes a create safe to retry: the server replays the first response instead of charging twice. It also lets the SDK retry the POST itself on a 5xx or network error, which it will not do for an unkeyed one.

let refund = client
    .with_idempotency_key(format!("refund-{order_id}"))
    .refunds()
    .create(&RefundCreateRequest::new("pay_123"))
    .await?;

Scope it to one logical operation, as above — a client held across unrelated calls would make every later one return the first one's result.

Logging

use delopay::{Delopay, LogEvent};

let client = Delopay::builder("prd_your_secret_key")
    .logger(|event: LogEvent<'_>| tracing::debug!(?event, "delopay"))
    .build();

LogEvent covers Request, Response and Retry. Logged URLs carry no query string — only parameter names are exposed, never values — and headers, bodies and the API key are never handed to a logger. .debug(true) is a stderr shorthand for local use.

Checkout branding

delopay::branding encodes and decodes the hosted checkout's branding configuration — the same representation the control center writes and the checkout reads — including a CSS sanitizer for merchant-supplied custom CSS. It is in the always-compiled core, so it is available in the webhook-only build too.

Buyer-side checkout

A hosted checkout page never holds a secret key. CheckoutSession binds the two browser-safe credentials — the merchant's publishable key and the payment's client secret — and sends each route exactly the one it expects:

use delopay::{CheckoutSession, PublishableKey};

let session = CheckoutSession::new(
    "mer_123",
    "pay_456",
    PublishableKey::new("pk_snd_abc")?, // `snd_abc` would not compile past here
    "pay_456_secret_xyz",
);

let catalog = session.epayouts_methods("de").await?; // client secret, as a bearer
let payment = session.retrieve_payment().await?;     // publishable key

There is no way to hand it a secret key: the constructor does not take one. If a page holds only the client secret, PaymentLinkSession exposes exactly the routes that credential authenticates — a call you cannot authenticate is not on the type you built, rather than a runtime error.

Money

Amounts are minor units, and a minor unit is not always a hundredth:

use delopay::Money;

assert_eq!(Money::new(1999, "EUR").to_major_string().as_deref(), Some("19.99"));
assert_eq!(Money::new(1999, "JPY").to_major_string().as_deref(), Some("1999"));
assert_eq!(Money::new(1999, "KWD").to_major_string().as_deref(), Some("1.999"));

// A currency the SDK does not know returns `None` rather than guessing 2.
assert_eq!(Money::new(1999, "XYZ").to_major_string(), None);

Settlement and operation-limit models expose Money accessors next to the raw integers, so an amount never travels without the currency that gives it meaning.

Settlement

For merchants hosting shops on behalf of third-party owners, client.settlement() covers the monthly statements, the live current period, per-line detail, backfills, payout recording, and the statement PDF. Every read takes an explicit test_mode — test and live figures never blend:

let overview = client.settlement().overview(false).await?;
let pdf = client
    .settlement()
    .download_statement_pdf("stmt_1", &StatementPdfParams::new().currency("EUR"))
    .await?;

HTTP proxies

Behind a corporate egress proxy, the SDK reads the usual environment variables (HTTPS_PROXY, HTTP_PROXY, ALL_PROXY, filtered by NO_PROXY), or you can configure it on the builder:

let client = Delopay::builder("prd_your_secret_key")
    .proxy("http://corp-egress.internal:3128") // ignore the environment
    .build();

let client = Delopay::builder("prd_your_secret_key").no_proxy().build();

http:// proxies only, via HTTP CONNECT tunnelling: TLS is negotiated with the API through the tunnel, so the proxy never sees plaintext. A configured but unusable proxy fails every request instead of silently connecting direct, and proxy credentials never appear in Debug output.

Customer identity history

Import the email addresses, names and handles your customers have been known by, kept apart from their current details, then read them back and search them. Merchant-wide API keys only; a shop-scoped key is refused.

use delopay::{CustomerIdentityImportRequest, CustomerIdentityImportRow};

let rows = vec![CustomerIdentityImportRow {
    customer_id: "user_12345".into(),
    kind: "email".into(),
    value: "jane.doe@example.com".into(),
    external_ref: "user-12345-email-0".into(),
    source_label: "account".into(),
    first_seen_at: None,
    last_seen_at: None,
}];
let run = client
    .customers()
    .import_identity_history(&CustomerIdentityImportRequest {
        idempotency_key: "import-2026-10-31-0001".into(),
        rows,
    })
    .await?;
let readback = client.customers().retrieve_identity_import(&run.run_id).await?;
assert_eq!(readback.rows_total, run.rows_total);
  • One request, at most 1,000 rows. Preview first (preview_identity_import): it says what each row would become and writes nothing.
  • The key is the request. idempotency_key deduplicates in the body: the same key answers the first run (replayed: true) and writes nothing; the same key with different rows is refused (IR_38). A network error or 5xx is retried under the unchanged key, so a retry cannot record the rows twice. Keep the key when you resend the same rows yourself.
  • Read back before you delete your copy. retrieve_identity_import returns the run's rows and the entries they map to; compare rows_total and the outcomes with what you sent.
  • Values never reach Debug. The row, the search request and every entry print <redacted> in place of the value.
  • Checked before sending. A first_seen_at or last_seen_at without its UTC offset (2026-10-31T12:00:00Z) would fail the whole request, and a body over MAX_IDENTITY_IMPORT_REQUEST_BYTES (about 7.2 MB) or MAX_IDENTITY_HISTORY_REQUEST_BYTES (128 KiB) would be refused, so both are refused before anything is sent. The API may also hold a merchant to fewer rows or customers per request (422, IR_06) and imports per minute (429, IR_52, retried after its Retry-After).

Upgrading from 0.12

These stop 0.12 code from compiling or change what it does (0.13.0):

  • Operations on routes outside the public API are gone: the analytics, analytics dashboard, search, cards, files, forex and feature-matrix resources, the fee-rule program (fees().rules()) and its builder, the decision manager (routing().decision()), and single operations on API keys, connectors, mandates, merchant accounts, operation limits, payment methods, payments, payouts, profiles, Stripe Connect and users. They called routes the API keeps for its own dashboard or for internal use. The CHANGELOG lists every one.
  • merchant_accounts().kv_status() and users().update_auth_method() are gone: each called a route that only accepts the operator's admin key, so a merchant credential could not use it.
  • export().transactions() takes the payment list's filters: transactions(Some(&json!({"start_time": "2026-09-01T00:00:00Z", "profile_id": ["pro_1"]}))), or None for everything you can see. TransactionExportParams is gone. The same holds for transactions_for_profile and both *_file forms.
  • events().list_delivery_attempts() answers Vec<EventDetailResponse>: read the attempt's fields through .event, and the delivery through .request and .response.
  • CustomerListParams has no email: filter with customer_id, or with search for a prefix of an ID, name or email. The with-count lists read their total from total_count; there is no count.
  • PaymentCreateRequest's amount and currency are Options: PaymentCreateRequest::new(amount, currency) is unchanged; a struct literal writes amount: Some(..) and currency: Some(..).
  • A subscription's price is item_price_id or product_id: wrap item_price_id in Some(..) in CreateSubscriptionRequest and CreateAndConfirmSubscriptionRequest, and build an update with UpdateSubscriptionRequest::for_price(..) (plus .plan_id(..)) or ::for_product(..). Both, or neither, is refused before sending.
  • users().resend_invite() takes a ReInviteUserRequest (ReInviteUserRequest::new(email)) and answers ReInviteUserResponse.
  • users().list_user_roles() answers Vec<GetUserRoleDetailsResponse>: read fields instead of indexing JSON.
  • ReplayIngestRequest::events is an Option: ReplayIngestRequest::new is unchanged; a struct literal writes events: Some(..) and compressed_events: None.
  • payment_links().retrieve() answers RetrievePaymentLinkResponse: the link is link_to_pay, not link. The old type could not decode the answer, so the call already failed.
  • SettlementLine::platform_fee_amount is Option<i64>: None for a viewer who is not the host.
  • Checkout notices replace trust badges as the default: a shop that saved no trust row, or only the stock badges, now decodes to the default notices and no badges. CheckoutBranding literals need the new fields, or ..default_branding().
  • Request structs gained fields: a struct literal without ..Default::default() needs them.

Upgrading

crates.io carries 0.1.0 to 0.7.0 and 0.9.0. 0.8.0, 0.10.0 and 0.11.0 were tagged on GitHub but never published there, so from crates.io you upgrade from 0.9 (or 0.7) straight to 0.12. Read the CHANGELOG for every change.

From 0.9, these stop code from compiling or change what it does:

  • FocusedCheckoutUrlParams has payment_link_id (0.10.0): add payment_link_id: None to a struct literal.
  • blocklist() is gone (0.12.0): the API no longer serves the card and payment-method blocklist it called, so every call already failed. Buyers are blocked through the buyer blocklist (/buyer-blocklist), which this crate does not wrap yet.

The customer identity history (0.11.0) is new, so no 0.9 code uses it.

From 0.7, also:

  • The Paysepro checkout calls are gone (0.8.0): PaymentLinkSession::paysepro_methods, CheckoutSession::paysepro_methods and PayseproMethodsResponse. The API no longer serves them.
  • events().list() answers EventListResponse (0.9.0): read events, not data; EventResponse::primary_object_id is object_id.
  • PerMethodSurchargeItem::payment_method is Option<String> (0.9.0); PerMethodSurchargeItem::new still sets it.
  • export().transactions() takes TransactionExportParams (0.9.0) and answers ExportEnvelope<TransactionExportRecord>; start_date is required.
  • CheckoutBranding gains thirty fields (0.9.0): a literal naming every field needs them, or ..default_branding().
  • PaneRail is #[non_exhaustive] (0.9.0): a match needs a wildcard arm.

Upgrading from 0.2

These are the changes that stop 0.2 code from compiling or change what it does, on top of the ones above:

  • Rust 1.97 or newer, edition 2024 inside the crate (0.4.0).
  • DelopayError::Http(reqwest::Error) is DelopayError::Transport(..) (0.4.0): replace the match arm. Request validation failures arrive as DelopayError::InvalidRequest.
  • List methods take optional parameters (0.4.0): customers().list(None) and disputes().list(None) keep the old behaviour.
  • Typed returns (0.4.0): resources that returned serde_json::Value return structs; read fields instead of indexing.
  • Payment-method lists answer envelopes (0.4.0): payment_methods().list() answers PaymentMethodListResponse and list_for_customer() answers CustomerPaymentMethodsListResponse, not Vec<PaymentMethodResponse>. Iterate .payment_methods and .customer_payment_methods instead of the returned vector.
  • An extra key that collides with a named field is refused (0.4.0) rather than sent.
  • Delopay::new, sandbox and builder take impl Into<SecretKey> (0.5.0): &str and String still work; a publishable key or client secret no longer compiles there.
  • Retrieving one connector no longer returns its credentials (0.6.0).

Nothing in the identity-history methods needs any of these; they are new in 0.11.0.

Design notes

  • HTTP: hyper directly, not reqwest. The Transport trait is the only backend seam; retries, backoff, and error mapping sit above it.
  • TLS: rustls with the ring provider passed explicitly; the SDK never installs a process-global crypto provider. Portable across Linux, macOS, and Windows.
  • Retries: automatic on 429 (always) and on network errors or 5xx for idempotent calls (GET, or a request with an idempotency key), so a create is never silently duplicated. Honors Retry-After.
  • Forward-compatible: responses keep unknown fields in an extra map, so a new API field never breaks deserialization.
  • Bounded memory: response bodies are capped at 10 MiB.
  • Errors: DelopayError distinguishes Api, Authentication (401), Timeout, Transport, InvalidSignature, and InvalidRequest. Api and Authentication carry the API code, type, and x-request-id.

License

MIT.