Python SDK
Typed Python client for the Von Payments Checkout API, published as vonpay-checkout on PyPI.
Requirements: Python 3.9+, httpx
Install
pip install vonpay-checkout
Pin the major you tested against — minor and patch releases are additive under semver, though a minor bump may add options or change defaults. A major bump is breaking and comes with an upgrade section: see Upgrading to 2.0.0.
Initialize
from vonpay.checkout import VonPayCheckout, VonPayError
client = VonPayCheckout("vp_sk_test_...", api_version="2026-04-14")
The api_version parameter pins the API version for all requests made by this client instance. See API Versioning for details.
A live key is sent only to Von Payments (4.0.0+). With a vp_sk_live_* key the constructor raises ValueError unless base_url is unset or https on checkout.vonpay.com or checkout-staging.vonpay.com. If you route API calls through your own proxy on purpose, pass allow_custom_base_url=True where you create the client. The environment variable VONPAY_ALLOW_CUSTOM_BASE_URL=1 on its own still works in 4.x, but from 4.5.0 it emits a one-time FutureWarning, and from 5.0.0 it is refused. An explicit allow_custom_base_url=False is never overridden by the environment variable. Test and publishable keys are never refused; an address other than Von Payments or this machine emits a one-time CustomBaseUrlWarning, which raises under -W error (filter it with ignore::vonpay.checkout.CustomBaseUrlWarning if the address is intended). key_destination_problem(api_key, base_url) returns the same refusal as a sentence (or None) without creating a client.
Sessions
Create a session
session = client.sessions.create(
amount=1499,
currency="USD",
country="US",
)
print(session.id) # "vp_cs_test_abc123"
print(session.checkout_url) # "https://checkout.vonpay.com/checkout?session=..."
Returns a CheckoutSession object.
Get a session
status = client.sessions.get("vp_cs_test_abc123")
print(status.status) # "succeeded"
print(status.amount) # 1499
Returns a SessionStatus object. Requires a secret key.
From 3.6.0 the session read also carries:
retry: aSessionRetrywithallowedandattempts_remaining, whether the session accepts another card after a decline (anelementsorembedsession whose card form is on your own page, on an account with retry enabled). It is the only place to learn this when the decline came after the bank's check.Nonewhen it does not apply.last_payment_error: aSessionLastPaymentErrorwithcode("card_declined"or"payment_failed", open set) anddecline_code(the payment intent'sfailure_codevalues, orNone). From 3.9.0 it also carriesaction(for your server only: it readshardfor a card the bank flagged or one of your own rules), andbuyer_message/buyer_action, the wording and advice that are safe to show the shopper.amount_refunded,remaining_refundableandrefundable: the refund totals,Nonetogether when they could not be read or the session has no single payment.Noneis not zero.
From 4.5.0, last_payment_error.payment_intent_id is the payment intent (vpi_*) of the declined attempt it describes: pass it to payment_intents.retrieve() to read that attempt in full. After more than one attempt it is the latest declined one. It is None when the decline was recorded without a payment intent. It is not the session's payment_intent_id, which names only a payment that took money. Keep it on your server, like code and decline_code.
On an expired session, expired_from of "processing" can later change to "failed" once the provider confirms an abandoned bank check authorized nothing, so a "processing" you read once is not final. The rules are on The session object.
From 4.1.0 the read also carries vp_buyer_id: the buyer (vp_by_*) Von Payments created for this session, when a card saved on it for charges made while the shopper is away belongs to that buyer. It is None when you named the buyer with buyer_id or the shopper's email identified one, always None on the sessions.update() and sessions.expire() answers, and None from an older server.
From 4.11.0 the read also carries payment_method_card_check: whether an approved $0 card check stored the card in payment_method (how the check works). It is a SavedCardCheck, or None. Read payment_method_card_check_known with it, because None alone cannot tell "no check" from "not read":
- Known and a
SavedCardCheck(status="approved",stored_credential_use): a check stored the card. - Known and
None: the card was saved without a check, or it was checked before 13 November 2026 and what the check declared is not on record. - Not known: not read.
payment_methodisNone, the answer came fromsessions.update()orsessions.expire(), or the value was not a valid check. Never read it as "no check".
Change an open session
from vonpay.checkout import SessionNotModifiableError
try:
session = client.sessions.update("vp_cs_test_abc123", amount=5498)
client.sessions.update("vp_cs_test_abc123", metadata={"order_id": "ORD-1234"})
except SessionNotModifiableError as e:
# Nothing was changed. e.reason is not_open, integration_mode,
# setup_session, store_order or in_page_bank_check; e.session has its state.
raise
# A 409 with code "session_update_conflict" is a different error and retryable:
# other changes kept landing, nothing was changed, the session is still open.
# Wait a moment and send the same update again.
Only elements sessions can be changed. Send amount, metadata, or both: metadata keys merge into the session's metadata (a sent key is added or replaced, nothing is removed), and currency and line_items go only with amount. An update that sends none of amount, metadata, card_form_group, recurring or the buyer fields below raises ValueError before anything is sent. From 4.13.0, a restricted key with charge limits cannot set a total over them: the call raises VonPayError with code api_key_limit_exceeded (limit per_session or daily_total) and nothing changes (limits). Added in 2.11.0; metadata from 4.2.0. The rules are on Change an open session's total.
Name a guest (4.9.0+). When you learn the shopper's email after the page opened, send buyer_email, setup_for_future_use="on_session" or stored_credential_use="unscheduled". Any one may be sent alone. Send them in a request of their own: with amount, metadata, card_form_group or recurring, the API answers 400 validation_error and changes nothing. If the email changes, send it again: the last value wins. The card field does not need rebuilding.
client.sessions.update("vp_cs_test_abc123", buyer_email="jane@example.com", setup_for_future_use="on_session")
This works only on an integration_mode="elements" payment session with charge_at_submit=True, no buyer_id, no recurring, no connected-store order and no card_form_group, before any payment is attempted. Otherwise it raises SessionNotModifiableError, which you can ignore: the payment goes ahead on what the session holds, and the card is not saved. Its new reason values are customer_named, subscription_signup, forwarded_gateway, card_form_group and payment_attempted.
Name the customer (4.13.0+). When the shopper creates or signs in to an account after the page opened, send buyer_id, your own customer reference, alone or with the guest fields. It works on the same sessions as naming a guest, and only once: a session that already names a customer refuses a different buyer_id with reason="customer_named". buyer_id alone does not keep the card: that needs reuse consent, as on a session created with buyer_id. A session created with stored_credential_use "recurring" or "installment" refuses buyer details that would change that declaration, with reason="stored_credential_declared". The rules are on Name the customer.
client.sessions.update("vp_cs_test_abc123", buyer_id="cust_1042")
From 4.3.0, sessions.create() and sessions.update() take card_form_group: the session's card-form group, which lets the buyer keep the card they typed when your checkout replaces its session. Derive it on your server, one value per shopper checkout, for example an HMAC of your cart id with a key only your server holds. Never send it to the browser. It is write-once: sessions.update() can set it on an open session that has none, never change it.
Close a session
import time
from vonpay.checkout import SessionNotExpirableError
try:
client.sessions.expire("vp_cs_test_abc123")
except SessionNotExpirableError as err:
if err.reason != "recent_activity":
# Nothing changed, and a payment may exist on it. Do not charge another way.
raise
# A declined session that changed recently: ask again after the wait.
# The SDK never repeats the call itself.
time.sleep(err.retry_after_seconds or 1)
client.sessions.expire("vp_cs_test_abc123")
From 3.5.0 the error carries reason: "recent_activity" (call again after retry_after_seconds), "payment_may_be_in_flight", or "unknown" for a value the SDK does not recognise, handled like "payment_may_be_in_flight". raw_reason keeps the value as sent. A closed session's expired_from can be "failed".
sessions.create() takes buyer_contact (phone, shipping and billing address) from 3.5.0, with the same rules as buyerContact on Create a session: secret key only, never returned on the read, personal data you must not log.
Closes an open, unpaid session so no payment can start on it afterwards. See Close a session so you can charge another way.
Validate (dry run)
result = client.sessions.validate(
amount=1499,
currency="USD",
)
# Validates parameters without creating a session
validate() takes every parameter create() takes (except idempotency_key) and checks the same body, without creating a session. Before 4.3.0 it took only amount, currency, country and description.
Payment intents
Read a payment intent
pi = client.payment_intents.retrieve(stored_intent_id)
print(pi.status) # "succeeded"
if pi.cvv_result_code == "no_match":
... # a real mismatch
Returns a PaymentIntentRead. Requires a secret key. Pass the id you stored when you created the intent, never one read out of a return URL. From 3.6.0 it also carries:
avs_result_codeandcvv_result_code: the address and security-code results.Nonewhen nothing was checked or no result came back."unavailable"and"not_supported"(address) or"not_provided"and"unavailable"(security code) mean the check did not run, not that it failed. This server read is where a payment taken in the browser gets its result, because the browser never receives it. Keep the values on your server.amount_refunded,remaining_refundableandrefundable: the refund totals,Nonetogether when they could not be read.Noneis not zero: read again or callrefunds.list().refundableis False until the charge settles.next_actionwhile the payment isrequires_action: the challenge link ispi.next_action["redirect_to_url"]["url"], and["issued_at"]beside it says when it was issued. If your server lost the create response, send the buyer to the link from here; checkissued_atfirst, since the payment provider decides how long a link stays usable. See 3-D Secure.
From 3.7.0, this read and the create, capture and void responses also carry network_transaction_id: the card network's own identifier for the charge (Visa's Transaction Identifier, Mastercard's trace id). Store it exactly as received if you keep your own records of stored cards; never parse it. None means not reported yet, not "none": some connections report it only once the payment settles, so read the payment again later. Always None for payment methods other than cards. The charge.succeeded and payment_intent.succeeded webhooks carry the same value as event.data.get("network_transaction_id").
From 3.8.0, the read also carries decline_code, action, decline_message and rule_code: filled when status is failed, with the same values as the create response and the charge.failed webhook, and None on any other status. Branch retry logic on action, not decline_code. When decline_code is blocked_by_rule, one of your own rules refused the payment: do not pass decline_code, decline_message or rule_code to the buyer's browser.
From 4.9.0 the read also carries:
late_money_outcome(typeLateMoneyOutcome, importable fromvonpay.checkout): what happened to money that arrived after the payment readfailed,cancelledorvoided. Given back automatically:"reversed"(given back: refunded, or the hold released),"reversing"(in progress) and"reverse_failed"(not given back yet, and the Von Payments team finishes it: do not refund it yourself). Given back by hand (in the type from 4.13.0):"manual_refund_pending"(not given back yet; our team contacts you, or refund it by its settlement row),"manually_refunded"(recorded as given back) and"kept_by_merchant"(you kept it).Nonemeans no late money arrived, or the records could not be read just then: read the payment again. Only from a server from before checkout's 18 November 2026 release, which sent the field only while money was being given back, doesNonenot prove that no late money arrived. Treat a value you do not know as not given back yet.statusdoes not change. See the payment read for each value. It is not on list items, and thecapture()andvoid()answers do not read it: callretrieve().attempts: every time the payment was sent to one of your connections, in order (PaymentIntentAttempt:attempt,processor_connection,result,decline_code,processor_response,outcome,network_advice,network_advice_retry_after_ms,created_at). The last item is the connection that decided the payment. An empty list means no connection was tried.attempts_status:"complete","pending"or"unavailable". Countattemptsonly when it is"complete". On"pending"the list isNone: read again in a few minutes. On"unavailable"no record is held, andattemptsisNone. Payments made before 2 November 2026 read this way. To count approvals and declines per connection, group the items byprocessor_connection.id.processor_response: aProcessorResponsewithcodeanddescription, the card processor's own answer to a declined charge.Nonewhen it was not recorded, and on a payment that is notfailed. The server cutsdescriptionto 200 characters and masks long numbers and repeated values. Usedecline_codeto decide what to do. Use this field to match the processor's own reports.descriptionis untrusted text: read it on your server, escape it where you display it, never show it to the buyer, and keep it out of an AI model's prompt.card: aPaymentIntentCardRecordwithbrand,last4andbin(the card's first six digits), from Von Payments' own records. Each field isNonewhen not known. The full card number is never returned.
bin, description and the connection's name are kept out of repr(), so a printed or logged object does not show them.
read = client.payment_intents.retrieve(stored_intent_id)
if read.attempts_status == "complete" and read.attempts is not None:
for a in read.attempts:
print(a.processor_connection.id if a.processor_connection else None, a.result, a.decline_code)
On the create(), capture() and void() answers, card is now complete (brand and last4 both read) or None when checkout could not read the card. Before 4.9.0, create() could raise KeyError on such a card. The capture() and void() answers also carry card.bin, processor_response, attempts and attempts_status. The create() answer carries none of them.
List payments and read approval rates
From 4.5.0. These read payment reports. Use a restricted key with only payment_intents.read.
from datetime import datetime, timezone
start = datetime(2026, 10, 1, tzinfo=timezone.utc)
# Every bank decline in the window, one request at a time
for pi in client.payment_intents.list_auto_paging(created_gte=start, outcome=["bank_declined"], max_items=5000):
print(pi.id, pi.decline_code, pi.card.brand)
summary = client.payment_intents.summary(created_gte=start, group_by=["day"], time_zone="America/New_York")
print(summary.totals.rates.approval_rate) # None, not 0, when there was no traffic
list()returns one page. To read on, call it again with the same filters and window andstarting_after=page.next_cursor. The cursor lasts 24 hours and works only with the request it came from.list_pages()yields whole pages, each with itsnext_cursor, so you can resume within 24 hours.list_auto_paging()yields one item at a time and stops aftermax_items. Both send one request at a time.summary()returns counts, amounts and rates.generated_atsays when the figures were computed, andage_secondshow old they are: a summary is cached for 45 seconds.- A refused filter raises
VonPayErrorwithparamnaming it. A report that is too big raisesreport_too_large, withmax_groupsortimeout_mssaying which limit. Narrow it rather than retry. - From 4.9.0 each item also carries
attempts,attempts_status,processor_responseandcard.bin, with the same rules as the read. An item never carrieslate_money_outcome.
Re-enter a saved card's security code
from vonpay.checkout import PaymentMethodRef
scs = client.security_code_sessions.create(
payment_method=PaymentMethodRef(id="vp_pmt_test_QAqnXEJF_TCum1jg"),
buyer_id="buyer_123",
)
# hand scs.id to the browser field; after its submit() resolves:
intent = client.payment_intents.create(
amount=1499,
currency="USD",
payment_method=PaymentMethodRef(id="vp_pmt_test_QAqnXEJF_TCum1jg"),
security_code_session=scs.id,
buyer_id="buyer_123",
return_url="https://your-store.example.com/checkout/return",
idempotency_key="ord_42_create",
)
security_code_sessions.create() maps to POST /v1/security_code_sessions and was added in 3.7.0. A session lasts 15 minutes and pays for one charge attempt, whatever the outcome (a 422 security_code_not_collected refusal does not use it up: send the same request again once the buyer submits); at most 10 can be opened per saved card per hour. The browser side and the refusals are on Re-enter a saved card's security code.
Refunds
List a payment's refunds
page = client.refunds.list(
transaction=session.vp_tx_id, # or payment_intent="vpi_...", exactly one
limit=25,
starting_after=cursor,
)
page.data # newest first, every status
page.amount_refunded # succeeded + still in progress, across all pages
page.remaining_refundable # what a refund with no amount would refund now
page.refundable # False until the charge settles, and when disputed or fully refunded
page.next_cursor # pass back as starting_after while has_more; None on the last page
Added in 3.6.0; maps to GET /v1/refunds. Requires a secret key. Pass exactly one of payment_intent or transaction; both or neither raises ValueError before any request. Check each refund's own status, since a requested refund is still in progress and can still fail. Each listed Refund carries idempotency_key and created_at. It never moves money and is retried like any other read. The fields are on List a payment's refunds.
A refunds.create() answer now carries idempotent: True when it replays an earlier request with the same idempotency_key, so no new refund was issued.
Webhooks
Verify signature
Verify the HMAC-SHA256 signature on an incoming webhook request. The webhook secret is per-endpoint (whsec_*), minted when you register the endpoint at /dashboard/developers/webhooks. It returns True or False for every delivery.
A secret that cannot be right raises (4.7.0+). verify_signature and construct_event raise before they verify anything. An empty or whitespace-only secret, an example value from our samples and docs (such as whsec_your_endpoint_signing_secret) and a Von Payments API key raise ValueError. A secret that is not a string, None included (os.environ.get(...) of a variable that is not set), raises TypeError. This is a setup mistake, not a bad delivery, so do not answer it with a 401. A real secret is not checked for its format.
is_valid = client.webhooks.verify_signature(
payload=request_body,
signature_header=request.headers["x-vonpay-signature"],
secret=os.environ["VON_PAY_WEBHOOK_SECRET"], # whsec_*
)
Construct event
Parse and verify a webhook payload into a typed event object. Enforces the asymmetric replay window (5 min past / 30 sec future).
event = client.webhooks.construct_event(
payload=request_body,
signature_header=request.headers["x-vonpay-signature"],
secret=os.environ["VON_PAY_WEBHOOK_SECRET"], # whsec_*
)
print(event.type) # "charge.succeeded"
print(event.data["vp_tx_id"]) # "vp_tx_test_9f2nd..." — the Von transaction id; reconcile and refund on this
event.data is a plain dict, handed through as sent. On a Send test event delivery the event carries test_event: True: check it first, before any lookup or write, and return 2xx without doing anything else.
charge.failed, payment_intent.failed and session.failed carry event.data.get("retry"): {"allowed": bool, "attempts_remaining": int} or None. A failure event is sent for every declined attempt, so one is not final on its own. allowed True means the session was re-opened for another card (keep the order open); allowed False with attempts_remaining 0 is final for this checkout. A missing key means unknown, never final. See A failed charge is not always the end of the checkout.
Webhook management
Read-only access to your registered webhook endpoints and stored event records. These methods all require a secret key (vp_sk_*) — publishable keys are rejected with 403. The wire format is camelCase end-to-end and parsed into typed dataclasses.
List webhook subscriptions
subs = client.webhook_subscriptions.list(
limit=20, # optional
starting_after="b6f2c1a0-3e4d-4c8b-9a1f-2d5e7c9b0a13", # optional cursor
)
for sub in subs.data:
print(sub.id, sub.url, sub.status)
print(subs.has_more) # True if more pages remain
Results are newest-first. To page, pass the last item's id as starting_after. A cursor that doesn't reference a subscription owned by your merchant raises a 400 validation_error (pagination is not silently restarted from the top).
Returns a WebhookSubscriptionsList object with object, data (a list of WebhookSubscription), has_more, and url. Requires a secret key.
Retrieve a webhook subscription
sub = client.webhook_subscriptions.retrieve("b6f2c1a0-3e4d-4c8b-9a1f-2d5e7c9b0a13")
print(sub.url) # the registered endpoint URL
print(sub.enabled_events) # ["charge.succeeded", ...]
print(sub.status) # "active" | "paused" | "disabled"
Returns a WebhookSubscription object. A cross-merchant or soft-deleted id returns 404 (opaque — never 403). The signing secret is never present on a read response. Requires a secret key.
From 3.7.0, sub.auto_paused_at is the time we paused deliveries after repeated failures, while status still reads "active". None alone does not mean "not paused": treat the endpoint as not paused only when sub.auto_paused_at_known is True and auto_paused_at is None. auto_paused_at_known is False when the pause state is unknown. Fix the endpoint, then set status back to "active" to resume.
Send a test event
Sends one signed test event to the endpoint through the real delivery path and returns the outcome in the same call. Added in 3.6.0. Requires a secret key.
outcome = client.webhook_subscriptions.send_test_event(
sub.id,
event_type="charge.succeeded",
session_id="vp_cs_test_abc123", # optional
)
print(outcome.delivered) # True when the endpoint answered 2xx
print(outcome.response_status) # the endpoint's HTTP status, or None if nothing answered
print(outcome.error) # why it was not delivered; None when delivered
Returns a SendTestEventOutcome with delivered, response_status, delivery_attempt_id, signature_preview and error. delivered False with a response_status is a successful test of an endpoint that answered non-2xx. If the endpoint could not be reached or timed out, the call raises 422 webhook_test_delivery_failed and the SDK does not repeat it: check the URL and send again. A 429 or 503 is retried as usual.
The delivered event carries test_event: True, the only marker that it is synthetic. Your handler must check it before touching an order: with session_id, the payload carries that session's real ids and will match a real order.
Retrieve a stored webhook event
record = client.webhook_events.retrieve("vp_wh_5x9k2m4n")
print(record.type) # "charge.succeeded"
print(record.processed) # True | False
print(record.retry_count) # int
Returns a WebhookEventRecord — our stored record of an event received from the processor, keyed by the id in the dashboard's Events view (not a delivered payload's vp_evt_* id, which webhooks.construct_event parses). Requires a secret key.
Confirming a return redirect
When the buyer is redirected back to your success_url, read the outcome from the API — the redirect itself only tells you they came back.
client = VonPayCheckout(os.environ["VON_PAY_SECRET_KEY"])
outcome = client.sessions.confirm_return(
dict(request.args),
expected_session_id=order.vonpay_session_id, # stored with YOUR order, not from the URL
)
if outcome.paid:
... # show the confirmation page; if outcome.needs_review, check the payments before you fulfil
elif outcome.reason == "still_pending":
... # IN FLIGHT, not declined — "confirming your payment", never a failure
elif outcome.reason == "refunded":
... # the money went back: do not fulfil; show "this payment was returned"
else:
... # not succeeded
sessions.confirm_return(params) reads the payment from the server with your API key
and returns a ReturnOutcome with paid, needs_review, review_reason, signature_valid,
status and reason. Branch on paid, then read needs_review. The return link carries only
session, so nothing in the URL can tell you the result (Handle the Return).
Tie the answer to this order (4.0.0+). On its own, paid being true means the session in the URL is one of your paid sessions, so a buyer could paste the return link of a different, cheaper order they paid for. Pass what your server recorded when it created the session: expected_session_id, and/or expected_amount with expected_currency (always together). A different session reads paid=False with reason="session_mismatch"; a different amount or currency reads paid=False with reason="amount_mismatch". A bad value raises TypeError before any request.
A refund changes the answer (4.7.0+). A session's status keeps reading succeeded after its payment is refunded, disputed or paid a second time, so confirm_return also reads the refund totals on the session:
| What happened | paid | Also | What to do |
|---|---|---|---|
| Nothing left of the payment: refunded in full (a full refund in progress counts until it fails), or refunded in part with the rest disputed | False | reason="refunded" | Do not fulfill. Show a neutral message ("this payment is being returned or has been returned"), not "payment failed". |
| Refunded in part | True | needs_review=False | What a partial refund means for the order is your decision. |
| Two or more payments on the session | True | needs_review=True, review_reason="second_payment" | Check both payments before you fulfill or refund. |
| Refund totals not sent: for a few moments after the payment, while a manual-capture payment is on hold, or when the totals could not be read | True | needs_review=True, review_reason="refund_state_unknown" | Check the payment before you fulfill. Unknown never reads as "nothing refunded", and never as "not paid". |
A dispute with no refund is not on the session: listen for the dispute.* webhooks.
The checks run in this order: no session id (missing_session), expected_session_id differs (session_mismatch), expected_amount or expected_currency differs (amount_mismatch), status not succeeded (still_pending or not_succeeded), then the refund totals. Among those, a second payment and missing totals are read before refunded, and both report paid with review.
Do not pass a secret. The secret argument is optional, and return links no longer carry a signature to check. Leaving it out is the normal path: signature_valid then reads None, which means "not checked", a healthy value, not a failure.
⚠️ paid being true is not "safe to fulfill". The status keeps reading
succeeded on every replay of the same URL, so record which session IDs you have
already fulfilled; and on a captureMethod: "manual" session succeeded means authorized and held, not paid. Fulfill the order from the charge.succeeded webhook rather than
here — a buyer who pays and closes the tab never loads this page. See
Handle the Return.
verify_return_signature is deprecatedReturn links no longer carry a signature, so this static method returns False for every one of them and logs a one-time warning. It does not raise, and it is removed in 5.0. Use confirm_return above: it needs no secret.
Signature verification belongs on webhooks, where each endpoint has its own whsec_* secret — see Webhooks.
Health Check
health = client.health()
print(health.status) # "ok" — the only value this call can return
print(health.latency_ms) # float — measured dependency latency (ms)
print(health.version) # always "" — the endpoint sends no version field
Returns a HealthStatus dataclass with status, latency_ms, and version.
Branch on neither. status is always "ok" — this call sends no query
parameters, so it gets the liveness ping; "healthy"/"degraded" need the deep
check, which health() cannot request (call ?deep=true directly), and
"error" is a 503, which raises. version is always "": the endpoint sends
no such field. The signal is whether the call raised.
Error Handling
All API errors raise VonPayError with structured fields for programmatic handling.
from vonpay.checkout import VonPayCheckout, VonPayError
try:
session = client.sessions.create(amount=-1, currency="USD")
except VonPayError as e:
print(e.status) # 400
print(e.code) # "validation_invalid_amount"
print(e.fix) # "Amount must be a positive integer in minor units (cents). 1499 = $14.99"
print(e.docs) # "https://docs.vonpay.com/integration/create-session#amount-format"
Buyer profiles
New in 2.0.0. A buyer profile is a stored shopper record you can attach payments to and look up later.
buyer = client.buyers.upsert(external_id="cust_4471", email="ada@example.com")
client.buyers.retrieve(buyer.id)
client.buyers.find(email="ada@example.com") # None when not found
client.buyers.update(buyer.id, phone="+15551234567")
Six methods: upsert, retrieve, find, list, update, erase_email. find
returns None rather than raising when there is no match. Several of your buyers may share an
email, so find(email=...) returns one of them: the most recently seen. To see every
buyer with that email, use client.buyers.list(email=...) (4.11.0 and later). It returns a
BuyerList whose data is most recently seen first, at most 100. By external_id it holds zero or one buyer.
Erasing an email is its own method, on purpose
⛔ This is the one part of the buyers API where the SDK deliberately refuses to
do what the endpoint allows. PATCH /v1/buyers/{id} treats email: null as a
permanent erase — and a routine update built from a half-populated object can
send that null without anyone intending it.
So the SDK separates "not supplied" from "explicitly None": update() raises
on email=None, and erase_email() is the only path that sends it.
client.buyers.erase_email(buyer.id) # the only way to erase
⛔ erase_email is not a complete deletion and must never be described to a
shopper as one. It clears the address on the profile. Copies elsewhere keep
their own retention rules and this call does not touch them.
⚠ And a success does not confirm the provider's copy is gone. We ask your payment provider to drop theirs, but that request is dispatched after we answer you and reports no failure back. For a buyer you only ever identified by email, the retraction cannot be performed at all — the key it needs was derived from the address just erased.
Buyers is the full model — which copies survive, why that list is examples rather than an inventory, and what to do when you are answering a formal erasure request. Read it before you build on this.
Wallet domains
New in 3.11.0. Register the domains your checkout runs on for Apple Pay and Google Pay from code, instead of in the dashboard (maps to /v1/wallet-domains). Every call needs a secret key. How entries work (one per domain and wallet, stable ids, the check limit, what Verified means) is in How domain entries work.
from pathlib import Path
# 1. Register. Safe to repeat: the same domain + wallet returns the existing entry.
apple = client.wallet_domains.create(domain="shop.example.com", wallet_type="apple_pay")
# 2. Apple Pay only: fetch the file once and deploy it as a static file.
file = client.wallet_domains.retrieve_file(apple.id)
Path("public/.well-known/apple-developer-merchantid-domain-association").write_bytes(file.content)
# 3. Once the file is live, ask for a check and read the outcome on the entry.
checked = client.wallet_domains.verify(apple.id)
print(checked.verification_status) # "pending" | "verified" | "failed" | "revoked"
print(checked.failure_reason) # why it is not verified yet, or None
# Google Pay: its own entry, no file.
client.wallet_domains.create(domain="shop.example.com", wallet_type="google_pay")
- Store the
id(why it is safe to). create()does not check again. Repeating it returns the saved entry as it is. After you host the file, callverify().verify()returns the entry whatever the outcome. A check that does not pass is not an error: readverification_statusandfailure_reason, which can be set on"pending"too. Over the check limit, the SDK waits out the429and checks again, so the call can take about 30 seconds. If the429still comes back, the domain was not checked again. Pollwallet_domains.retrieve(id)between checks.- Host the Apple Pay file as a static file.
retrieve_file()returns the exact bytes (content,bytes) andverification_statusfrom theX-Vonpay-Verification-Statusheader. Serve the bytes unchanged at/.well-known/apple-developer-merchantid-domain-association, over HTTPS, with no redirect. Never callretrieve_file()from a public route on each request: it uses your secret key and spends its rate limit. A Google Pay entry has no file (404 wallet_domain_wrong_type). failure_reasonis one of five codes; Why a check failed says what each means and what to do.create()refusals:409 wallet_domain_no_binder(your account cannot take wallet payments yet),422 wallet_domain_invalid(send a bare hostname: no scheme, port or path) and503 wallet_domain_provider_unavailable(temporary; safe to retry). See error codes.wallet_domains.remove(id)stops the button on that domain. Removing it again answers404 wallet_domain_not_found, so after a retried call checklist()before treating a404as a failure.wallet_domains.list(limit=None, cursor=None)returns entries newest first (25 by default, at most 100); passnext_cursorascursorwhilehas_moreis True.- Can a wallet payment actually go through? (4.0.0+) Each
list()row carriescharge_readiness(can_charge,reasons), and the page carrieswallet_readiness(one entry per wallet, withset_up) andwallet_settings. Verified only means the button can show;can_chargestays False until every step is in place, including a first approved payment with that wallet on your account. Checkrow.charge_readiness is not None and row.charge_readiness.can_charge is True:Nonemeans not reported, a not-ready answer is still a truthy object, and a reasoncodeyou do not recognise means not ready. The three areNoneon the answers ofcreate(),retrieve()andverify(); read them fromlist().
The dashboard flow and per-framework hosting recipes are in Apple Pay setup.
Subscriptions
For businesses with Subscriptions switched on (4.4.0 and later). Start a subscription with recurring on payment_intents.create(), then read and change it here:
terms = client.subscription_products.terms("vsprod_live_Hk29sLq0")
page = client.subscriptions.list(buyer_id="cust_1042", status="active")
client.subscriptions.pause(page.data[0].id, resumes_on="2026-12-01", idempotency_key="pause_cust_1042_1")
From 4.6.0, client.subscription_products.list(product_ref=…, status=…, limit=…, starting_after=…) lists your products, newest first, each with its sign-up terms. While has_more is true, pass next_cursor as starting_after to read the next page.
Every change (cancel, unschedule_cancel, pause, resume, skip, set_next_bill_date, set_interval, set_price, set_discount, remove_discount) takes the keyword arguments idempotency_key, dry_run and actor_label, and returns a SubscriptionChange. From 4.5.0, pause() and skip() also take customer_requested= and note=, and a Subscription carries paid_through: give the customer access by it, never by status. The SDK refuses a change without idempotency_key before sending it, unless dry_run is True. From 4.10.0, a Subscription carries held_reason: why it is held, and None for any other status (the reasons). From 4.13.0, client.subscriptions.list_attempts(subscription_id, limit=…, starting_after=…) lists every payment try for the subscription, newest first: pass next_cursor as starting_after while has_more is true. A subscription event's data is a SubscriptionEventData, which from 4.13.0 carries attempt_number, retries_left and final_attempt. Every call, field and event is on the Subscriptions reference; the steps in order are in the Integration guide.
From 4.11.0:
- Customer pauses. A
Subscriptioncarriescustomer_pause:allowed,reasonandmax_resumes_on. Read it before you offer the customer a pause (customer pauses). A pause sent withcustomer_requested=Truecan be refused with409 subscription_pause_not_allowed, or with400 subscription_pause_too_long, which carrieserr.max_cyclesanderr.max_resumes_on. - Brand and store. A
Subscriptioncarriesbrand(id,name) andstore(platform,domain). Each isNonewhen the subscription has none. - Product changes.
client.subscription_products.retrieve(product)reads one product, by id or by reference. Five calls change products:create(),update(),change_price(),archive()andunarchive(). Each needsidempotency_key=: the SDK raisesTypeErrorbefore sending a call without one.change_price()requiresapply_to_existing=(Falsechanges the price for new sign-ups only). A restricted key needssubscription_products.write. A product also carriespublic_url,public_url_allowedandwarnings. The fields, rules and refusals are on Subscription products.
Upgrading to 4.13.0
Check:
- Late money.
late_money_outcomeisNonewhen no late money arrived, andLateMoneyOutcomelists the three values for money given back by hand (the values). - Exhaustive checks.
SessionNotModifiableReasongains"stored_credential_declared", the key limits gain"per_session", and the warning codes gain"mit_anchor_not_used".
New:
- Name the customer with
buyer_idonsessions.update(). - Session limits on a restricted key. A session total over the key's charge limits gets
422 api_key_limit_exceededwithlimitper_session, onsessions.create()andsessions.update().daily_totalnow also counts the key's open sessions (limits). - A customer-initiated charge of a saved card may leave out
MITBlock.original_transaction_id. An id that cannot be used is not used either:mit_original_transaction_idisNoneandwarningscarriesmit_anchor_not_used. derived_amountonorder_total_mismatchandline_indexon the two mirror-line refusals, onVonPayError.vp_tx_id_sourceon thecharge.succeeded,charge.refunded,refund.failedandcharge.faileddata: howvp_tx_idwas matched (webhook events).subscriptions.list_attempts()and the try fields on subscription events.
Upgrading to 4.12.0
Additive. Check:
- New values.
ErrorCodegainscard_brand_not_acceptedandshopper_attempt_limit_reached.ApiKeyLimitgainsper_refundandrefund_daily_total.
New:
- The in-page bank check. Pass
next_action_presentation="in_page"topayment_intents.create()(typeNextActionPresentation; leave it out for"redirect", the default). Hand the answer'sclient_read_secretto your page in the response body, and from there only tovora.handleNextAction(). Never log or store it. The SDK leaves it out ofrepr(), butdataclasses.asdict()andvars()still carry it, so do not serialize the whole object. The rules and refusals: show the check in a pop-up on your page. payment_intents.create_client_read_secret(id)mints a new secret for a payment still waiting on the bank, for a page that reloaded. It returns aPaymentIntentClientReadSecret(payment_intent,client_read_secret,expires_at). The SDK never repeats this call. A timeout or network error raisesClientReadSecretOutcomeUnknownError, because a secret may have been minted: read the payment before you call again.- Refund limits on a restricted key. A refund that does not fit the key's refund limits gets
422 api_key_limit_exceededwithlimitper_refundorrefund_daily_total, and nothing is refunded.refund_daily_totalclears by waiting (retryableisTrue). Its advice is exported asAPI_KEY_REFUND_DAILY_TOTAL_HELP.
Upgrading to 4.11.0
Additive. Check:
- Test doubles.
SavedPaymentMethodhas a new required field,card_check, with no default. ASavedPaymentMethod(...)you build by hand in a test must passcard_check=None, or it raisesTypeError. The other new fields have defaults. subscription_products.terms()raisesTypeErrorfor aproductthat is not a string. It raisedValueErrorbefore.- New values.
ErrorCodegainspayment_under_review,subscription_pause_not_allowed,subscription_pause_too_long,public_url_not_allowedand the product refusals.RestrictedKeyPermissiongainssubscription_products.write.
New:
card_checkon each saved card frompayment_methods.list()(aSavedCardCheck):status="approved"andstored_credential_usewhen an approved $0 card check stored the card, orNonewhen it was saved without one.Nonealso covers a card checked before 13 November 2026 whose declaration is not on record. Read how it works before its first merchant-initiated charge.payment_method_card_checkandpayment_method_card_check_knownon the session read.customer_pause,brand,storeand the product calls on Subscriptions.buyers.list()for every buyer with one email.warningson thesessions.create()answer:test_store_order_not_writtensays a test checkout writes no order in its store (test orders).
Upgrading to 4.10.0
Additive. Check:
- Restricted keys that change billing.
RestrictedKeyPermissionnow includessubscriptions.write_billing. The API already asks a restricted key for it onset_next_bill_date,set_interval,set_price,set_discount,remove_discountandcreate_portal_link, whatever SDK version you use (permissions). The upgrade does not change that.
New: held_reason on the subscription.
Upgrading to 4.9.0
Additive. Check:
- Tests against a local server. A client whose
base_urlis onlocalhost,127.0.0.1or[::1]no longer sends SDK telemetry by default. - The card on
create(),capture()andvoid().cardis complete orNone. Check forNonebefore you readcard.brand. - New
SessionNotModifiableError.reasonvalues (Change an open session) and the error codemirror_test_order_limit_reached(Auto-Retry).
New: late_money_outcome, attempts, attempts_status, processor_response and card on the payment read and the list items, and the guest fields on sessions.update().
Upgrading to 4.7.0
Check:
confirm_returnreads refunds. A return with nothing left of the payment now readspaid=Falsewithreason="refunded". It readpaid=Truebefore. If you branch onreasonexhaustively, add it, and readneeds_reviewbefore you fulfill (details).verify_return_signature. It returnsFalsefor every return withoutsig, which is every return link today. Move toconfirm_return. It is removed in 5.0.- Webhook secrets.
verify_signatureandconstruct_eventraise on an empty, example or non-string secret or on an API key. Nothing changes for a realwhsec_*secret.
New: key_mode(key) and held_as_live(key), importable from vonpay.checkout. key_mode answers "test", "live", "publishable_test", "publishable_live" or "unknown". held_as_live is True for a live secret key and for every "unknown" key: use it to decide whether to ask a person before an action that moves money. Both read the prefix only, never call the API and never raise.
Upgrading to 4.5.0
Additive for every call you can make today. Check:
- A proxy opted in by the environment variable alone. A live key sent to a
base_urlthat is not a Von Payments address because onlyVONPAY_ALLOW_CUSTOM_BASE_URL=1is set still works, with a one-timeFutureWarning. Passallow_custom_base_url=Trueinstead: from 5.0.0 the environment variable alone is refused.
New:
- Payment reports:
payment_intents.list(),list_pages(),list_auto_paging()andsummary(), withVonPayError.param,max_groupsandtimeout_ms, and the error codereport_too_large. - Subscriptions:
paid_through,pending_product_change,customer_schedule_change_usedandcustomer_schedule_change_available_atonSubscription;customer_requested=andnote=onpause()andskip();VonPayError.next_change_allowed_onon409 subscription_customer_change_limit_reached(limits). last_payment_error.payment_intent_idon the session read (above).
Upgrading to 4.4.0
Additive for every call you can make today. Check:
- Exhaustive checks.
ErrorCodegainspayment_intent_not_found,transaction_not_found,payment_method_not_storedandrecurring_mandate_required. Amatchwith a default case is unaffected. - Code that reads
session_not_foundafter a payment lookup. A payment or transaction that is not found now answerspayment_intent_not_foundortransaction_not_found. This comes from the API, so it applies to every SDK version. It affectspayment_intents.retrieve(),capture()andvoid(),refunds.create()andrefunds.list(), andpayment_intents.create()whenmit.original_transaction_idnames no payment intent of yours.
New:
payment_intent_idonVonPayError: on a422frompayment_intents.create()that was refused before any money moved, the failed payment intent that records the attempt (The record of a refused charge). Nothing was charged and no webhook is sent for it. Send the corrected charge with a newidempotency_key.Nonewhen no record was written.- Error help for the four new codes, and for
payment_method_unvaultedandcapability_not_supported, which read as unknown codes before.payment_method_unvaultedisretryableTruewithnext_action == "wait_and_retry": the saved card is still being stored. The SDK never repeats a422, so wait a few seconds and send the charge again yourself, with a newidempotency_key.payment_method_not_storedandrecurring_mandate_requiredarenext_action == "ignore", as for a decline: the customer must enter the card again or pay while present. CardTestingSuspectedDatatypes thedataof themerchant.card_testing_suspectedalert.- Subscriptions:
subscriptions.list(),retrieve(),cancel(),unschedule_cancel(),pause(),resume(),skip(),set_next_bill_date(),set_interval(),set_price(),set_discount(),remove_discount()andcreate_portal_link(),subscription_products.terms(), therecurringsign-up onpayment_intents.create(), andSubscriptionEventData. See above.
Upgrading to 4.3.0
Additive for every call you can make today. Check:
- Exhaustive checks.
ErrorCodegains members, among themapi_key_permission_denied,api_key_limit_exceeded, the threemirror_settle_only_*refusals,platform_fee_exceeds_amount,request_body_too_largeandrequest_body_timeout. Amatchwith a default case is unaffected. - Objects you build yourself.
SavedPaymentMethodgains a required field,consent: a test double that constructs one must pass it (Noneis accepted). - Custom base URLs. Every key that is not a sandbox secret key (
vp_sk_test_*) or a publishable key (vp_pk_*) is now held to the live-key rule: the client refuses to send it to an address that is not Von Payments' own, including localhost, unless you passallow_custom_base_url=True.
New:
sessions.validate()takes every parametersessions.create()takes (exceptidempotency_key) and sends the same body. Through 4.2.0 it took onlyamount,currency,countryanddescription.processor_connection(dataclassProcessorConnection,idandname) on payment intents fromcreate(),retrieve(),capture()andvoid(), and on thecharge.*andpayment_intent.*webhook payloads, where it is a plain dict (read it withdata.get("processor_connection")): which of your payment connections processed the payment. Match and group onid.nameis your own label, free text and possiblyNone: keep it internal and never show it to shoppers.Nonewhen no connection was reached. It is not returned to a publishable key, andsession.faileddoes not send it.network_adviceandnetwork_advice_retry_after_mson payment intents, and as plain keys on thecharge.failed,payment_intent.failedandsession.failedpayloads (read them withdata.get(...)): the card network's own advice about the card (Decline handling). Treat a word you do not recognise as"do_not_try_again".Noneis never permission to retry.mit_anchor_source: what a merchant-initiated charge is linked to,"payment"or"card_check".Noneon a charge without anmitblock.fraud_evidenceonpayment_intents.create()(dataclassFraudEvidence) andfraud_evidence_forwardedon the create response (Fraud evidence).- Store facts on a settle-only refusal. On the three
mirror_settle_only_*codes,VonPayErrorcarriescharge_amount,charge_currency,order_balance(on an amount mismatch, the amount to charge instead),order_balance_raw,order_currency,order_statusandorder_payment_status(the order's payment status, not this request's). A store fact readsNonewhen the store could not be read. - Restricted-key details. On
api_key_limit_exceeded,VonPayErrorcarrieslimit,limit_minor,used_minorandlimit_currency. Withlimit == "daily_total"retryableisTrue: the 24-hour total clears by waiting. Onapi_key_permission_deniedit carriesrefused_fields. - Error help for
platform_fee_exceeds_amount(an account setting: contact support),request_body_too_largeandrequest_body_timeout. The SDK does not resend arequest_body_timeoutfor you: resend the same request, with the sameidempotency_keywhere the call takes one.
Upgrading to 4.2.0
Additive: nothing was removed or renamed, and no dataclass gains a field without a default. Check:
- Exhaustive checks.
ErrorCodegains"mirror_line_invalid_variant_ref"(Shopify order lines). A match with a fallback case is unaffected.
New:
sessions.update()takesmetadata, alone or withamount, which is now optional.- Error help for
mirror_line_missing_product_ref:retryable=False,next_action="fix_input". - The
invalid_transitionhelp now namescancelledas a final status: do not retry, and do not charge the buyer again on your own.
Upgrading to 4.1.0
Additive: nothing was removed or renamed. Check:
- Objects you build yourself.
SavedPaymentMethodgainssetup_for_future_use_methodwith no default, so code that constructs one itself, such as a test double, must now pass it (Nonefor "not recorded"). Objects the SDK builds from a response are unaffected. - Exhaustive checks. The
PaymentIntentStatusliteral gains"cancelled"(final, no money taken: see Status lifecycle), theSessionExpiredFromliteral gains"authentication_cancelled", andErrorCodegains members. A match with a fallback case is unaffected.
New:
- How the buyer agreed to reuse.
tokens.create(..., setup_for_future_use_method=...)takes"checkbox"or"checkout_terms"(SetupForFutureUseMethod), recorded on the card only beside asetup_for_future_usein the same call.payment_methods.list()rows read it back assetup_for_future_use_method, and thepayment_method.attachedwebhook asevent.data.get("setup_for_future_use_method")(SetupForFutureUseMethodStored, an open set typedstr: treat a value you do not recognise as "recorded, method unknown"). See Recurring & saved cards. vp_buyer_idonsessions.get(), and on thepayment_method.attachedwebhook asevent.data.get("vp_buyer_id"): the buyer Von Payments created for a session that named none.SessionExpiredFromgains"authentication_cancelled", a session closed while its payment waited on the bank's security check (Close a session). If the bank's check completes later anyway, the payment is still recorded, so checkpayment_statustoo.- Error help (
retryable,next_action) forsession_payment_in_progress,provider_operation_refused,refund_declined,refund_before_settlement,wallet_session_refused,wallet_not_savedandpayment_form_used. Thecurrency_not_supportedhelp now lists UGX.
Upgrading to 4.0.0
Two changes can break code that worked on 3.x. Nothing was removed or renamed.
- A live key with your own
base_url. With avp_sk_live_*key,VonPayCheckout(...)now raisesValueErrorunlessbase_urlis unset or https oncheckout.vonpay.com/checkout-staging.vonpay.com. Removebase_url, or opt in for a proxy you run on purpose (Initialize). - Retry logic that reads
err.retryable. An error withretry_withheld=Truenow carriesretryable=Falseandnext_action="reconcile": read the payment back before anything else (Auto-Retry).
Also check:
- Warnings treated as errors. A test or publishable key with a
base_urlthat is not a Von Payments host or this machine now emits a one-timeCustomBaseUrlWarning, which raises under-W error(or pytest'sfilterwarnings = error). - Webhook
card. On the charge, refund and saved-card events thecardkey can be absent fromdata: read it withevent.data.get("card"), sinceevent.data["card"]raisesKeyErroron such a payload. - Exhaustive checks.
ReturnOutcome.reasongainssession_mismatch/amount_mismatch(only when you pass the newconfirm_returnarguments).
New: the confirm_return order check, wallet charge readiness, wallet_type on the tokens.revoke() result, and error help for charge_in_progress and charge_already_in_flight.
Upgrading to 3.11.0
Additive. New: wallet_domains (list, create, retrieve, retrieve_file, verify, remove). The six wallet_domain_* error codes now carry their own retry advice (retryable, next_action) instead of a generic fallback.
Upgrading to 3.10.0
Additive. New: a buyer's saved cards.
payment_methods.list(*, buyer_id, limit=None, starting_after=None)lists one buyer's saved cards, newest first.buyer_idis your own customer reference.tokens.revoke(token_id, *, buyer_id=None, initiated_by=None)revokes a saved card permanently. When a shopper removes their own card, passbuyer_id=...andinitiated_by="buyer"so the card is revoked only if it is theirs; takebuyer_idfrom your signed-in session, never from the shopper's request.already_revokedTrue or False are both success.
Both need a secret key. A blank buyer_id raises ValueError before anything is sent. Tokens has the full behaviour, including which cards are listed and revoking.
Upgrading to 3.9.0
Additive. New:
security_code_verification="strict"onpayment_intents.create(), only withsecurity_code_session: the charge completes only on an issuer security-code match (strict check). NewErrorCodememberssecurity_code_not_verifiedandsecurity_code_check_in_progress.MITBlock.original_transaction_idis optional on a merchant-initiated charge of a saved card; the linked payment comes back asmit_original_transaction_id. A card with no customer-present payment is refused withmit_anchor_unknown.SessionStatus.retry_after_msandSessionStatus.outcome, andaction,buyer_messageandbuyer_actiononSessionLastPaymentError(session object).session_attempt_limit_reachedjoinsErrorCode.
Upgrading to 3.8.0
Additive. New: the decline reason on payment_intents.retrieve() (decline_code, action, decline_message, rule_code), and the ErrorCode member buyer_reference_conflict: buyers.upsert() is refused with 409 when the external_id belongs to a buyer created with your other-mode key.
Upgrading to 3.7.0
Additive. New: network_transaction_id on payment intents and on the two success webhooks (see Read a payment intent), and auto_paused_at / auto_paused_at_known on webhook subscriptions (see Retrieve a webhook subscription). ErrorCode gains payment_form_expired, and NextAction gains "reload_payment_form": if you match exhaustively on err.next_action, add it. No SDK method calls the route that returns that code; it is named so a server that relays the browser's answer can match it.
Upgrading to 3.6.0
Check your code before upgrading: saved-card details can now be None at runtime. When the payment provider's details for a saved card cannot be read, the card is still saved and usable and the API returns each detail as null. Before 3.6.0 the SDK filled those in with "" or 0; now token.card.brand, .last4, .exp_month and .exp_year are None, as is a missing card. Code that uses them directly, such as token.card.last4.upper() or token.card.exp_year + 1, raises on such a card. Guard each read:
label = token.card.last4 or "unknown"
Cards whose details were read are unaffected. If you match exhaustively on resolved_descriptor.reason, add "invalid_for_provider": the charge was sent without your configured descriptor because it breaks a provider limit. See Statement descriptors.
Upgrading to 3.0.0
Two breaking changes. Nothing was removed or renamed.
Pass idempotency_key to void() to keep automatic retries. A void now follows the same rule as capture and refunds: after a timeout or a 500/502/503/504 it is retried only when you passed a key. Without one, the first error is raised with retry_withheld=True. A void releases the hold for good, and an unclear failure does not mean it was not applied.
vonpay.payment_intents.void(payment_intent_id, idempotency_key=f"order_{order_id}_void")
A redirect from the API is now an error. The API never redirects, so a 3xx means something else answered: a proxy, a mistyped base_url, or a hijacked connection. The SDK no longer follows it and raises unexpected_redirect with retryable false and a new next_action value, check_configuration. Do not retry: check that base_url is https://checkout.vonpay.com with no path, then any proxy and the network. If you match exhaustively on error codes or next actions, add both values.
Upgrading to 2.0.0
One breaking change, and it is a type change rather than a behaviour change.
rejectReason dropped five values it could never receive. not_authorized,
already_captured, already_voided, already_refunded and
amount_exceeds_remaining are gone; the server never sent any of them, so every
comparison against one was already dead code. Those comparisons now fail to
compile. Delete them.
⭐ The value worth adding a branch for is concurrent_update — another
capture or void is in flight for the same payment right now. Before 2.0.0 the SDK
replaced any value it did not recognise with nothing at all, so a branch checking
for a race never fired and a payment still in flight was read as terminal.
That is how a live payment gets cancelled or refunded. Treat it as "unknown
outcome, read again", never as an end state.
The full list and what each value means is on Error codes.
Error reporting
The SDK accepts an optional error_reporter callback so integrators can pipe SDK failures into their own observability stack (Sentry, Datadog, custom logger). Your reporter is invoked synchronously, fire-and-forget; if it raises, the SDK swallows it (with a logging.warning on the vonpay.checkout logger) and continues.
When it fires
- API request failures: non-retryable 4xx, retry-exhaustion on 5xx, network/timeout errors after retry exhaustion
webhooks.construct_eventverification failures (signature mismatch, stale timestamp, malformed header)
It does not fire on:
verify_signature/verify_return_signature: these returnboolfor a delivery or a return- The error for an unusable webhook secret: it is raised before any verification
- The constructor's invalid-key-prefix
ValueError— that's a dev-time error before the reporter is wired
Callback shape
from vonpay.checkout import ErrorReporter, ErrorReporterContext, VonPayError
def reporter(err: Exception, ctx: ErrorReporterContext) -> None:
# err is VonPayError or another Exception subclass
# ctx fields:
# method: str — "sessions.create" / "webhooks.construct_event" / etc.
# sdk_version: str
# url: str | None — origin + path, no query string (no PII via params)
# status: int | None — HTTP status if from API response
# request_id: str | None — X-Request-Id for correlation
# code: str | None — server error code
# attempt: int | None — 0-indexed retry attempt
...
Sentry example
import sentry_sdk
from vonpay.checkout import VonPayCheckout
def report_to_sentry(err, ctx):
sentry_sdk.capture_exception(
err,
tags={"sdk": "vonpay-python", "method": ctx.method, "code": ctx.code},
contexts={"vonpay": ctx.__dict__},
)
client = VonPayCheckout(
api_key=os.environ["VON_PAY_SECRET_KEY"],
error_reporter=report_to_sentry,
)
Logging example
import logging
from vonpay.checkout import VonPayCheckout
log = logging.getLogger("myapp")
client = VonPayCheckout(
api_key=os.environ["VON_PAY_SECRET_KEY"],
error_reporter=lambda err, ctx: log.error(
"vonpay sdk error", extra={"err": str(err), "ctx": ctx.__dict__}
),
)
error_reporter is opt-in and additive — if you don't configure it, errors still propagate via raise and nothing else changes.
A separate SDK-telemetry channel can send error events back to Von Payments. From 4.9.0 it is off by default when base_url is on localhost, 127.0.0.1 or [::1], whatever the key, because such a client is a test against a local server. Pass telemetry={"enabled": True} to keep it on.
Charges without an idempotency key
From the 28 October 2026 cut-off the API can refuse a charge that carries no Idempotency-Key with 400 idempotency_key_required, before anything is charged (Idempotency). From 3.2.0 the SDK emits one FutureWarning per process the first time payment_intents.create() is called without idempotency_key. The charge is still sent. An empty string counts as no key. VONPAY_QUIET=1 silences the warning.
If you run with warnings as errors (python -W error, PYTHONWARNINGS=error or pytest's filterwarnings = error), a keyless payment_intents.create() raises FutureWarning locally, before anything is sent. Nothing is charged, but the call fails. Pass idempotency_key on every charge before you upgrade.
from vonpay.checkout import PaymentMethodRef
vonpay.payment_intents.create(
amount=1499,
currency="USD",
payment_method=PaymentMethodRef(id=payment_method_id),
idempotency_key=f"order_{order_id}_create",
)
Auto-Retry
The SDK automatically retries on 429 (rate limited) and 5xx (server error) responses using exponential backoff. Default is 2 retries; configure with the max_retries constructor argument.
From 4.9.0 the SDK never repeats 429 mirror_test_order_limit_reached, and err.retryable is False. It means a sandbox account whose test orders go into a real connected store has too many open at once. Nothing was charged. Cancel the open test orders in the store, or wait about a day for them to clear, then send the request again.
⛔ Money-moving calls are the exception. On a charge, capture, void (from 3.0.0) or refund the SDK
retries an ambiguous response only when you passed an idempotency_key.
Without one it stops and raises rather than repeating the call, because a 5xx
or a timeout there means the provider was reached and the answer was lost —
repeating it can charge the buyer twice. 429 still retries without a key
(nothing reached the handler), and non-money writes are unchanged.
From 3.3.0 there is one case a key does not cover: when the 5xx reply to a money call (payment_intents.create, capture, void, refunds.create) cannot be read, because it was cut off or replaced by a proxy's HTML error page, the SDK stops after the first attempt with or without a key. The error carries retry_withheld=True; read the payment intent back before repeating anything.
From 4.0.0 a charge, capture, void or refund error with retry_withheld=True carries retryable=False and next_action="reconcile" (the advice is exported as RETRY_WITHHELD_HELP), so retry logic keyed on err.retryable does not fire for it. Read the payment back first (payment_intents.retrieve(), or refunds.list() for a refund). Send it again only if it did not happen, and only with the same idempotency_key.
In 2.11.0 and later, a 502 payment_outcome_unknown is never retried, key or no key: the provider accepted the capture or void and only the record of it failed. The raised error carries capture_outcome or void_outcome set to "unknown". Read the payment intent back before doing anything else.
Sample app
Clone-and-run reference integration using this SDK lives in Von-Payments/vonpay-samples:
checkout-flask— Flask hosted checkout with server-side return confirmation + webhook handler
Ships with .env.example, a per-sample README, and pinned to a known-working SDK version.