Rust
Call the Pay.com API from Rust with typed async methods on Tokio, list streams, and webhook verification.
The pay-com crate has a typed async method for each API operation, named
after its resource: pay.charges().create(), pay.holds().capture(), and
pay.value_lists().items().create(). Types are in pay_com::types, and
fields keep the API's own names, in snake_case.
Requirements and install
You need Rust 1.85 or later, on Tokio. The SDK uses HTTP/1.1 over rustls, so there's no OpenSSL to install.
[dependencies]
pay-com = "0.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }The crate is pay-com, used as pay_com.
Set your key
Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:
export PAY_COM_API_KEY='sk-pay-com-sandbox-…'The SDK selects the sandbox or live environment automatically from the key
prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written
to the SDK's logs or errors.
Create your first charge
Charge a saved payment method. Amounts are integers in minor units (for example,
2000 is $20.00 USD):
use pay_com::Pay;
use pay_com::types::ChargesCreateParams;
#[tokio::main]
async fn main() -> pay_com::Result<()> {
let pay = Pay::new()?;
let charge = pay
.charges()
.create(
ChargesCreateParams::new(2000, "usd")
.source("pm_card_685125127054035968")
.reference("order-6735"),
)
.await?;
println!("{:?} {:?}", charge.id, charge.status);
Ok(())
}new() takes the required fields, and each optional one has a setter. Every
field of a response is an Option, since the API can leave one out. A request
does nothing until it's awaited.
The SDK sends a new idempotency key with each POST and DELETE, and the
same one when it retries. To use your own, set it on the request:
pay.charges().create(params).idempotency_key(key).await.
It retries twice by default after a network error, a timeout,
409 request_in_progress, 421, 429, 502, 503, or 504. To decide
yourself, call .max_retries(0), and set a reference on payments to help
you
find out what was created.
The SDK retries these only after a 429, or when they never left your server:
every PUT and PATCH, webhook_endpoints().create(), and
network_tokens().retrieve_cryptogram(). If one of these requests receives no
response, check whether it succeeded before sending it again.
When you call payment_links().update(), pass every field you want to keep,
amount and currency included. An update
without amount sets the link's amount to 0.
List every item
A list method's request gives its first page when you await it, and every
item on every page with .stream():
use pay_com::Pay;
use pay_com::types::ChargesListParams;
#[tokio::main]
async fn main() -> pay_com::Result<()> {
let pay = Pay::new()?;
let page = pay.charges().list(ChargesListParams::new().limit(10)).await?;
println!("{} on the first page", page.data.unwrap_or_default().len());
let mut charges = pay.charges().list(ChargesListParams::new().created_greater_than("2026-11-01T00:00:00Z")).stream();
while let Some(charge) = charges.next().await {
println!("{:?}", charge?.id);
}
Ok(())
}To collect them, with a limit, use
pay.charges().list(ChargesListParams::new()).collect(500).await?. The
stream ends after an error. Lists that
use page numbers
work the same way.
Catch a decline
A decline is an error of kind ErrorKind::PaymentMethod:
use pay_com::types::ChargesCreateParams;
use pay_com::{ErrorKind, Pay};
#[tokio::main]
async fn main() -> pay_com::Result<()> {
let pay = Pay::new()?;
match pay.charges().create(ChargesCreateParams::new(2000, "usd").source("pm_card_685125127054035968")).await {
Ok(charge) => println!("{:?}", charge.id),
Err(e) if e.kind() == ErrorKind::PaymentMethod => println!("Declined: {:?}", e.decline_code()),
Err(e) if e.is_invalid_request() => println!("Fix the request: {:?} {}", e.code(), e.message()),
Err(e) => return Err(e),
}
Ok(())
}Every error is a pay_com::Error, with kind(), error_type(), code(),
status(), and the API's body as raw(). Include request_id() when
contacting Pay.com support. It is None when the API didn't get or couldn't read the request. After retries, earlier() holds an earlier attempt's error. The
error's kind tells you what happened:
| Error kind | Cause |
|---|---|
PaymentMethod | Payment declined by the issuer or blocked by a risk rule (400) |
InvalidRequest | 400 or 422. is_invalid_request() is true for NotFound, for 404, too |
Authentication | 401 |
Permission | 403 |
Idempotency | An idempotency key in use, or used for another request |
Conflict | Any other 409 |
RateLimit | 429 |
Api | 5xx, a redirect (none is followed), or a response the SDK didn't expect |
Connection | No complete response. is_connection() is true for Timeout too |
Usage | Client-side configuration or usage error detected before sending the request (such as a missing API key) |
See Handle errors for what to do with each.
Verify a webhook
Pass the raw body, the Pay-Signature header, and the endpoint's whole
signing secret. Cap the body, since anyone can send to your URL. An event can
be over 1 MB, so take up to 5 MB, where axum's default limit is 2 MB. Return
HTTP 400 only when ErrorKind::Signature is returned. Let other errors
return 500 so Pay.com retries delivery:
use pay_com::{ErrorKind, EventData, Webhooks};
// The raw body, the Pay-Signature header, and the endpoint's whole signing secret. Returns the HTTP status code to send.
fn handle(body: &[u8], signature: Option<&str>, secret: &str) -> u16 {
let event = match Webhooks.construct_event(body, signature, secret) {
Ok(event) => event,
Err(e) if e.kind() == ErrorKind::Signature => return 400,
Err(_) => return 500, // no secret configured, or a signed body that isn't an event
};
if let EventData::ChargeSucceeded(charge) = &event.data {
println!("Paid: {:?}", charge.id);
}
200
}With axum, take the body as Bytes, and the header from the HeaderMap.
Skip events whose id you've
already handled.
event.data is an EventData, with a variant for each event type that holds
its object. For example, charge.* events carry a Charge. In your tests,
Webhooks.test_header(payload, secret) makes a valid header.
Options
Pass these to Pay::builder(), then call .build()?.
api_keyimpl Into<String>environmentEnvironmentEnvironment::Sandbox or Environment::Live, for a key without either prefix.merchant_idimpl Into<String>timeoutDurationmax_retriesu32base_urlimpl Into<String>default_headername, valuePer-request .merchant_id(), .timeout(), .max_retries(),
.idempotency_key(), and .header() settings override the client defaults. The
sandbox's simulate endpoints are under pay.test_helpers().
pay.documents().upload() takes an Upload, such as
Upload::from_path("receipt.pdf")?. See
Upload and download files.
Logs go through the log crate, with the target pay_com, without keys or
bodies. Turn them on as your logger does, such as RUST_LOG=pay_com=debug.