Python
Call the Pay.com API from Python with typed methods, sync and async clients, automatic paging, and webhook verification.
pay-com has a typed method for each API operation, named after its
resource: pay.charges.create(), pay.holds.capture(), and
pay.value_lists.items.create(). Parameters and fields keep the API's own
names, in snake_case. Pay is the client, and AsyncPay has the same
methods for asyncio and trio.
Requirements and install
You need Python 3.9 or later.
pip install pay-comImport it as pay_com. Parameters are dicts with the API's field names. Each
operation's parameters are a TypedDict in pay_com.types, such as
ChargesCreateParams, so mypy and your editor check them.
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):
from pay_com import Pay
pay = Pay()
charge = pay.charges.create({
"amount": 2000,
"currency": "usd",
"source": "pm_card_685125127054035968",
"reference": "order-6735",
})
print(charge.id, charge.status)A response is a typed object, such as a Charge, and also a dict of what the
API sent. A field the response leaves out reads as None.
The SDK sends a new idempotency key with each POST and DELETE, and the
same one when it retries. To use your own, pass it to the method:
pay.charges.create(params, idempotency_key=key).
It retries twice by default after a network error, a timeout,
409 request_in_progress, 421, 429, 502, 503, or 504. To decide
yourself, pass 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 returns its first page. Looping over the page goes through every item on it and on every page after:
from pay_com import Pay
pay = Pay()
page = pay.charges.list({"limit": 10})
print(len(page.data or []), page.has_more)
for charge in pay.charges.list({"created.greater_than": "2026-11-01T00:00:00Z"}):
print(charge.id)To collect them, with a limit, use
list(itertools.islice(pay.charges.list(), 500)). With AsyncPay, await
the call for its first page, or loop over it with async for. Lists that
use page numbers
work the same way.
Catch a decline
A decline raises PaymentMethodError:
from pay_com import InvalidRequestError, Pay, PaymentMethodError
pay = Pay()
try:
pay.charges.create({"amount": 2000, "currency": "usd", "source": "pm_card_685125127054035968"})
except PaymentMethodError as err:
print("Declined:", err.decline_code)
except InvalidRequestError as err:
print("Fix the request:", err.code, err.message)Every error is a PayError, with type, code, status_code, 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,
__cause__ holds an earlier attempt's error. The error's class tells you what
happened:
| Error class | Cause |
|---|---|
PaymentMethodError | Payment declined by the issuer or blocked by a risk rule (400) |
InvalidRequestError | 400 or 422. NotFoundError, for 404, is one too |
AuthenticationError | 401 |
PermissionDeniedError | 403 |
IdempotencyError | An idempotency key in use, or used for another request |
ConflictError | Any other 409 |
RateLimitError | 429 |
APIError | 5xx, a redirect (none is followed), or a response the SDK didn't expect |
APIConnectionError | No complete response. APITimeoutError is one too |
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. Return HTTP
400 only when SignatureVerificationError is raised. Let other errors return
500 so Pay.com retries delivery:
import os
from flask import Flask, request
from pay_com import Pay, SignatureVerificationError
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024
@app.post("/webhooks")
def webhooks():
try:
event = Pay.webhooks.construct_event(request.get_data(), request.headers.get("Pay-Signature"), os.environ["PAY_COM_WEBHOOK_SECRET"])
except SignatureVerificationError:
return "Invalid signature", 400
if event.type == "charge.succeeded":
print("Paid:", event.data.id)
return "", 200The raw body is request.body in Django, and await request.body() in
FastAPI. An event can be over 1 MB, and Django refuses bodies over 2.5 MB
unless you raise DATA_UPLOAD_MAX_MEMORY_SIZE.
Skip events whose id you've
already handled.
construct_event() returns the event's class, such as ChargeSucceededEvent,
whose data is a Charge. In your tests,
Pay.webhooks.generate_test_header(payload, secret) makes a valid header.
Options
Pass these to Pay() or AsyncPay().
api_keystrenvironmentstrsandbox or live, for a key without either prefix.merchant_idstrtimeoutfloatmax_retriesintbase_urlstrdefault_headersdicthttp_clienthttpx.ClientAsyncPay takes an httpx.AsyncClient.idempotency_key, merchant_id, timeout, max_retries, and headers can
also be set for one request, as keyword arguments of the method. The
sandbox's simulate endpoints are under pay.test_helpers.
pay.documents.upload() takes bytes, a path, or a file opened in binary mode.
See Upload and download files.
Close the client when you're done, with pay.close() or with Pay() as pay:,
or keep one for your app's life. Logs go to the pay_com logger, without keys
or bodies. Set PAY_COM_LOG=debug to see them.