Ir para o conteúdo

tempest_fastapi_sdk.integrations.payment.adapters

Os provedores traduzidos para o contrato canônico de pagamento.

« Integrações e pagamentos


OpenPixPixProvider

OpenPixPixProvider(client: OpenPixClient)

OpenPix as a :class:~...payment.base.PixProvider.

Satisfies the protocol structurally — nothing is inherited, matching how every other provider seam in the SDK works.

Attributes:

Name Type Description
provider_name str

Always "openpix".

Wrap an already-configured OpenPix client.

Parameters:

Name Type Description Default
client OpenPixClient

The generated client, built over an HTTPClient that already carries the AppID in Authorization and points at the right environment.

required

create_pix_charge async

create_pix_charge(request: PixChargeRequest) -> PixCharge

Create a charge at OpenPix.

amount_cents goes across unchanged: OpenPix states value in cents already, and since v0.259.0 the generated model types it as int. The response still goes back through to_cents, which now narrows nothing and validates everything — a value that is negative or not whole means the assumption about the field is wrong, and that is worth an error rather than a plausible number.

expires_in is sent in seconds, truncated to a whole one: the field is an integer count, and timedelta.total_seconds() answers a float. OpenPix refuses anything under five minutes with a 400; that floor is not re-checked here, because duplicating a provider's validation is how the copy drifts from the original.

The create is idempotent on reference: it goes out with ?return_existing=true, so a retry after a timeout — when the first request may have landed — answers the charge that already exists for that correlationID, as Woovi's specification describes the parameter (not measured against the sandbox). That is the same guarantee the Mercado Pago adapter gives through X-Idempotency-Key, and the one the protocol documents for :attr:PixChargeRequest.reference.

Parameters:

Name Type Description Default
request PixChargeRequest

What to charge, and for whom.

required

Returns:

Name Type Description
PixCharge PixCharge

The created charge, carrying the copy-and-paste code.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer from OpenPix.

ValueError

If OpenPix answers 2xx without a charge body, which would otherwise surface later as an attribute error far from the call that caused it.

get_pix_charge async

get_pix_charge(charge_id: str) -> PixCharge

Read a charge back from OpenPix.

Parameters:

Name Type Description Default
charge_id str

The charge's identifier. OpenPix accepts its own id or the correlationID on this route, so either works.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge as OpenPix currently reports it.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer from OpenPix.

ValueError

If the answer carries no charge body.

cancel_pix_charge async

cancel_pix_charge(charge_id: str) -> PixCharge

Withdraw an unpaid charge.

OpenPix answers this route with {"status": ..., "id": ...} and nothing else — no amount, no code, no timestamps. The charge that comes back therefore has those fields empty rather than refetched: a second round-trip the caller did not ask for would hide latency and could fail on its own after the cancellation already happened.

Parameters:

Name Type Description Default
charge_id str

The charge's identifier.

required

Returns:

Name Type Description
PixCharge PixCharge

The cancelled charge, with only what OpenPix

PixCharge

reported plus the amount the caller cannot recover from this

PixCharge

call, which is 0.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer from OpenPix.

refund_pix_charge async

refund_pix_charge(
    charge_id: str, amount_cents: int | None = None, *, refund_reference: str
) -> PixRefund

Refund a paid charge, idempotently on refund_reference.

OpenPix keys a charge refund by a correlationID of the caller's and lists the charge's refunds with it (GET /api/v1/charge/{id}/refund), so idempotency is checked here rather than trusted to the provider: the charge's refunds are read first, and a refund already carrying refund_reference is answered as it is, without a second POST. Whether OpenPix itself refuses a repeated refund correlationID is not documented in its specification and was not measured; what is guaranteed is the read before the write, and the read after a failed write: when the POST raises, the refunds are read again and a refund carrying the reference is answered instead of the error — the answer was lost, not the refund. Two calls racing on the same reference can still both reach the POST; the recipe serializes per reference.

The charge is read first because the refund route is addressed by the charge's correlationID (the route's id parameter, per the specification) while :attr:PixCharge.provider_charge_id is OpenPix's own id. The amount always goes out explicit — what is left, for a full refund — so a retry carries the same body.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required
amount_cents int | None

How much to refund; None refunds what is left.

None
refund_reference str

The refund's correlationID.

required

Returns:

Name Type Description
PixRefund PixRefund

The refund — the existing one when the reference was

PixRefund

already used on this charge.

Raises:

Type Description
PixRefundExceedsBalanceException

When the charge has less left than asked, counting every refund not REJECTED.

PixRefundReferenceConflictException

When the reference names an existing refund of another amount.

HTTPStatusError

For any non-2xx answer from OpenPix.

ValueError

If amount_cents is not positive, or the charge cannot be read.

get_refunded_cents async

get_refunded_cents(charge_id: str) -> int

Sum the charge's refunds that are not REJECTED.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
int int

Cents refunded or in flight; 0 with no refund.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer from OpenPix.

ValueError

If the charge cannot be read.

parse_webhook

parse_webhook(event: object) -> PixPaymentEvent

Turn a verified OpenPix delivery into a canonical event.

Parameters:

Name Type Description Default
event object

An :class:~...payment.openpix.OpenPixWebhookEvent, as produced by make_openpix_webhook_dependency. Typed object because the protocol cannot name a per-provider type.

required

Returns:

Name Type Description
PixPaymentEvent PixPaymentEvent

The canonical event. Its charge is filled

PixPaymentEvent

only when the delivery carried a charge object; the raw body

PixPaymentEvent

is always kept.

Raises:

Type Description
TypeError

If handed something other than an OpenPixWebhookEvent. Signature verification is not optional, so accepting a bare dict here would let an unverified body through the front door.

OpenPixPayoutProvider

OpenPixPayoutProvider(http: HTTPClient)

OpenPix as a :class:~...payment.base.PayoutProvider.

Sends with autoApprove: true: one call creates and approves the payment. The two-step form (create, then approve) leaves a window in which a payment exists but is not approved, and a crash inside that window is a payout nobody knows whether to retry. Reading the answer depends on v0.304.0's overlay fix, which lets Payment.status carry the "APPROVED" that the autoApproved response documents.

Error mapping (the contract the wallet relies on):

  • HTTP 4xx, or a payment answered DENIED/FAILED -> :class:~tempest_fastapi_sdk.exceptions.PayoutRejectedException;
  • anything else that goes wrong — HTTP 5xx, timeout, connection error, a body that does not validate — propagates unchanged, because the payment may have been made.

Attributes:

Name Type Description
provider_name str

Always "openpix".

Build the provider over a transport that never re-sends.

Takes the HTTPClient rather than an OpenPixClient so it can check the one setting that decides whether a payout can be paid twice. HTTPClient retries every method, POST included, on HTTP 429/5xx and on a read timeout — measured with the default policy: one POST answered 500 goes out three times. For a payout that is the worst case: the first request may have created the payment, and the retry gets an answer the adapter would report as a refusal, so the wallet would give back money that already left.

Parameters:

Name Type Description Default
http HTTPClient

Transport carrying the AppID, pointed at the right environment, built with retry_policy=RetryPolicy(max_attempts=1).

required

Raises:

Type Description
ValueError

If http would retry a request.

transfer_to_pix_key async

transfer_to_pix_key(request: PayoutRequest) -> PayoutResult

Create and approve a Pix-key payment in one call.

Parameters:

Name Type Description Default
request PayoutRequest

The transfer.

required

Returns:

Name Type Description
PayoutResult PayoutResult

CONFIRMED when OpenPix says so, PENDING

PayoutResult

for CREATED, APPROVED or a state this mapping does not

PayoutResult

know; the raw value stays in provider_status.

Raises:

Type Description
PayoutRejectedException

On HTTP 4xx, or a DENIED / FAILED payment.

MercadoPagoPixProvider

MercadoPagoPixProvider(
    http: HTTPClient,
    *,
    idempotency_key: Callable[[str], str] | None = None,
    action_retry_delays: Sequence[float] = DEFAULT_ACTION_RETRY_DELAYS,
)

Bases: _OrdersClient

Mercado Pago Pix as a :class:~...payment.base.PixProvider, over Orders.

A create is idempotent on :attr:PixChargeRequest.reference by default, as the contract promises and as :class:OpenPixPixProvider behaves: the X-Idempotency-Key is :func:reference_idempotency_key of the reference, so repeating a create answers the order that already exists. Through v0.357.0 the default was a fresh UUID4 per call, and a repeated create opened a second order with the same external_reference.

Attributes:

Name Type Description
provider_name str

Always "mercado_pago".

create_pix_charge async

create_pix_charge(request: PixChargeRequest) -> PixCharge

Create a Pix order.

expires_in becomes expiration_time as an ISO 8601 duration in whole seconds (PT1800S), which the sandbox accepted. Without it, the order expired 24 hours after creation.

Parameters:

Name Type Description Default
request PixChargeRequest

What to charge, and for whom.

required

Returns:

Name Type Description
PixCharge PixCharge

The created charge, PENDING, with br_code and

PixCharge

qr_code_base64.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer — including 400 for an order without a payer, and 409 idempotency_key_already_used when the reference was already used for a create with another body (another amount, payer, description or expiry). That 409 is a conflict in the caller's data, not a transient failure: the existing order is not read back on its behalf, because answering it would hand over a charge for an amount nobody asked for.

ValueError

If the answer is not an order with an id and amount.

Repeating the create with the same request answers the order the first call opened — see :func:reference_idempotency_key.

get_pix_charge async

get_pix_charge(charge_id: str) -> PixCharge

Read a Pix order back.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id, the order id.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge as Mercado Pago reports it now.

cancel_pix_charge async

cancel_pix_charge(charge_id: str) -> PixCharge

Cancel an unpaid Pix order (POST /v1/orders/{id}/cancel).

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
PixCharge PixCharge

The order after cancellation, CANCELLED.

refund_pix_charge async

refund_pix_charge(
    charge_id: str, amount_cents: int | None = None, *, refund_reference: None = None
) -> PixCharge
refund_pix_charge(
    charge_id: str, amount_cents: int | None = None, *, refund_reference: str
) -> PixRefund
refund_pix_charge(
    charge_id: str,
    amount_cents: int | None = None,
    *,
    refund_reference: str | None = None,
) -> PixCharge | PixRefund

Refund a paid Pix order in full or in part.

Two forms, told apart by refund_reference:

  • With it — the :class:~...payment.base.PixRefundProvider form. The X-Idempotency-Key is derived from the order id and the reference (:func:_refund_idempotency_key), so repeating the call replays the refund instead of applying it twice. The order is read first: asking for more than is left raises :class:~tempest_fastapi_sdk.exceptions.PixRefundExceedsBalanceException — after the request still goes out under the derived key, so a retry of a refund that already landed (which is why nothing is left) gets the provider's replay instead of the exception. Returns a :class:PixRefund.
  • Without it — the form this method had before the refund contract existed, kept unchanged: a fresh key per call (retries of that one call are still safe, a second call is a second refund), no balance check, and a :class:PixCharge back.

Mercado Pago's refund entries carry no reference of the caller's, so the refund this call made is read as the last entry of the action's answer — in the sandbox fixtures the answer lists every refund of the order, oldest first (pix_refund_rest.json). That a replayed answer is byte-for-byte the first one was measured on the create (vendor/mercadopago-evidence.md section 9.6), not on the refund route.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required
amount_cents int | None

How much to refund; None refunds what is left.

None
refund_reference str | None

The refund's idempotency key.

None

Returns:

Type Description
PixCharge | PixRefund

PixCharge | PixRefund: A :class:PixRefund when

PixCharge | PixRefund

refund_reference is given; otherwise the order after the

PixCharge | PixRefund

refund, as before. Observed on 2026-10-10: PAID with

PixCharge | PixRefund

provider_status processed and the refund under

PixCharge | PixRefund

raw["transactions"]["refunds"] after a partial one,

PixCharge | PixRefund

REFUNDED after the rest.

Raises:

Type Description
PixRefundExceedsBalanceException

With a reference, when the order has less left than asked and Mercado Pago refuses.

PixRefundReferenceConflictException

With a reference, when Mercado Pago answers 409 idempotency_key_already_used — the reference went out before with another amount.

HTTPStatusError

For any other non-2xx answer — 409 cannot_refund_order for an unpaid order, which is cancelled, not refunded.

ValueError

If amount_cents is not positive, or a partial refund is asked of an order with no payment to address.

get_refunded_cents async

get_refunded_cents(charge_id: str) -> int

Sum the refunds the order lists, failed ones left out.

Reads transactions.refunds of GET /v1/orders/{id}. A refund in a state :data:REFUND_STATUS_MAP does not name counts.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
int int

Cents refunded or in flight; 0 with no refund.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer.

parse_webhook

parse_webhook(event: object) -> PixPaymentEvent

Turn a verified, re-read delivery into a canonical Pix event.

Parameters:

Name Type Description Default
event object

A :class:MercadoPagoOrderDelivery.

required

Returns:

Name Type Description
PixPaymentEvent PixPaymentEvent

The event, its type read off the re-read order

PixPaymentEvent

(:data:STATUS_EVENT_MAP). provider_event_name and raw

PixPaymentEvent

come from the unsigned body: log them, do not decide on them.

Raises:

Type Description
TypeError

If handed anything else — in particular the bare :class:MercadoPagoWebhookEvent, which carries no state and could only become UNKNOWN, leaving a service that settles on CHARGE_PAID silently stuck.

MercadoPagoCardProvider

MercadoPagoCardProvider(
    http: HTTPClient,
    *,
    idempotency_key: Callable[[str], str] | None = None,
    action_retry_delays: Sequence[float] = DEFAULT_ACTION_RETRY_DELAYS,
)

Bases: _OrdersClient

Mercado Pago cards as a :class:~...payment.base.CardProvider, over Orders.

Attributes:

Name Type Description
provider_name str

Always "mercado_pago".

create_card_charge async

create_card_charge(request: CardChargeRequest) -> CardCharge

Charge, or only authorize, a tokenized card.

capture=False sends capture_mode: manual; the order comes back action_required / waiting_capture (:attr:PaymentStatusEnum.AUTHORIZED). Otherwise the provider's default applies, observed as automatic_async.

With installments, amount_cents goes out as both total_amount and the payment amount, and the provider adds the interest: observed on a 3x Amex order of R$ 1.000,00 (2026-10-30), 201 processed / accredited, installment_amount 370.77, paid_amount 1112.31. A full refund of that order returned 1000.00 — the price, not what the payer paid.

Parameters:

Name Type Description Default
request CardChargeRequest

What to charge.

required

Returns:

Name Type Description
CardCharge CardCharge

PAID, AUTHORIZED, or FAILED with the

CardCharge

reason in status_detail — a decline answers HTTP 402 and is

CardCharge

returned, not raised.

Raises:

Type Description
HTTPStatusError

For a non-2xx answer other than a decline — 400 invalid_transaction_amount for an installment count the card does not offer at this amount, among others.

ValueError

If the answer is not an order.

get_card_charge async

get_card_charge(charge_id: str) -> CardCharge

Read a card order back.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge as Mercado Pago reports it now.

capture_card_charge async

capture_card_charge(charge_id: str) -> CardCharge

Capture an authorization, then read the order back.

POST /v1/orders/{id}/capture answers only the order's id, status, status detail and transactions — measured, no total_amount — so the order is read again to return a whole charge. The capture has already happened when that read runs.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The order after capture, PAID.

cancel_card_charge async

cancel_card_charge(charge_id: str) -> CardCharge

Release an authorization (POST /v1/orders/{id}/cancel).

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The order after cancellation, CANCELLED.

refund_card_charge async

refund_card_charge(charge_id: str, amount_cents: int | None = None) -> CardCharge

Refund a card order in full or in part, then read it back.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required
amount_cents int | None

How much to refund; None refunds what is left.

None

Returns:

Name Type Description
CardCharge CardCharge

The order after the refund. Observed: PAID with

CardCharge

status_detail partially_refunded after a partial one,

CardCharge

REFUNDED after the rest.

Raises:

Type Description
HTTPStatusError

For any non-2xx answer.

ValueError

If a partial refund is asked of an order with no payment to address.

charge_from_delivery staticmethod

charge_from_delivery(delivery: MercadoPagoOrderDelivery) -> CardCharge | None

Read the card charge a re-read delivery carries, if any.

Parameters:

Name Type Description Default
delivery MercadoPagoOrderDelivery

From :func:make_mercado_pago_webhook_delivery_dependency.

required

Returns:

Type Description
CardCharge | None

CardCharge | None: The charge when the re-read order is a card

CardCharge | None

order, else None.

MercadoPagoOrderDelivery dataclass

MercadoPagoOrderDelivery(
    notification: MercadoPagoWebhookEvent, order: dict[str, Any] | None = None
)

A verified notification, plus the order re-read because of it.

Built by :func:make_mercado_pago_webhook_delivery_dependency.

Attributes:

Name Type Description
notification MercadoPagoWebhookEvent

The verified notification.

order dict[str, Any] | None

The order the notification points at, as the API answered on the re-read. None when the delivery is not about an order, its data.id is not an order id, or the API answered 404 — the dashboard's "simulate notification" signs a made-up id, and raising there would make the provider retry forever.

make_mercado_pago_webhook_delivery_dependency

make_mercado_pago_webhook_delivery_dependency(
    secret: str,
    client: MercadoPagoPixProvider | MercadoPagoCardProvider,
    *,
    tolerance_seconds: float | None = DEFAULT_TOLERANCE_SECONDS,
    versions: Sequence[str] = DEFAULT_SIGNATURE_VERSIONS,
) -> Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]

Build a FastAPI dependency yielding a verified, re-read delivery.

Parameters:

Name Type Description Default
secret str

The webhook secret from the Mercado Pago dashboard. An empty secret rejects every delivery.

required
client MercadoPagoPixProvider | MercadoPagoCardProvider

Either adapter; used to re-read the order.

required
tolerance_seconds float | None

Maximum drift between the signature's ts and the clock. Defaults to :data:DEFAULT_TOLERANCE_SECONDS; None skips the check.

DEFAULT_TOLERANCE_SECONDS
versions Sequence[str]

Hash versions to accept, in preference order.

DEFAULT_SIGNATURE_VERSIONS

Returns:

Type Description
Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]

Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]: The

Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]

dependency. It refuses an unsigned or badly signed delivery with 401

Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]

before the route runs, and re-reads the order by the signed

Callable[..., Coroutine[Any, Any, MercadoPagoOrderDelivery]]

data.id.

make_mercado_pago_router

make_mercado_pago_router(
    provider: MercadoPagoPixProvider | MercadoPagoCardProvider,
    *,
    on_delivery: MercadoPagoDeliveryHandler,
    secret: str | None = None,
    settings: MercadoPagoSettings | None = None,
    simulate: bool = False,
    simulation_api: FakeMercadoPagoOrdersAPI | None = None,
    simulation_url: str | None = None,
    simulation_client: AsyncClient | None = None,
    withdraw: MercadoPagoWithdrawConfig | None = None,
    webhook_path: str = DEFAULT_WEBHOOK_PATH,
    simulation_prefix: str = DEFAULT_SIMULATION_PREFIX,
    tags: list[str] | None = None,
    include_in_schema: bool = True,
    tolerance_seconds: float | None = DEFAULT_TOLERANCE_SECONDS,
    docs_locale: str | None = None,
) -> APIRouter

Build the Mercado Pago routes of a service.

Parameters:

Name Type Description Default
provider MercadoPagoPixProvider | MercadoPagoCardProvider

The adapter the service charges with; re-reads each delivery's order.

required
on_delivery MercadoPagoDeliveryHandler

Awaited with each verified, re-read delivery. Raise to answer 500 (Mercado Pago retries).

required
secret str | None

The webhook secret. None reads settings.MERCADOPAGO_WEBHOOK_SECRET (or the environment and .env when settings is None).

None
settings MercadoPagoSettings | None

The service's settings, for the secret and for ENV.

None
simulate bool

Mount the simulation routes. Refused unless ENV is development or test (see :func:ensure_simulation_allowed).

False
simulation_api FakeMercadoPagoOrdersAPI | None

The simulator provider runs over. None takes the one :func:mercado_pago_provider_for registered for provider.

None
simulation_url str | None

Base URL of a running tempest mercado-pago fake-api (e.g. "http://mp-fake:8090"). The simulation routes then move orders on it, through :class:RemoteMercadoPagoSimulation, so a worker in another process — its provider pointed at the same fake-api by MERCADOPAGO_BASE_URL — reads what they moved. Needs simulate=True; excludes simulation_api.

None
simulation_client AsyncClient | None

The client the remote simulation sends with; its lifecycle stays with the caller. None opens a short-lived client per call. Needs simulation_url.

None
withdraw MercadoPagoWithdrawConfig | None

Mounts the withdrawal route. None mounts none.

None
webhook_path str

Path of the webhook route — the URL registered in the Mercado Pago dashboard.

DEFAULT_WEBHOOK_PATH
simulation_prefix str

Path prefix of the simulation routes.

DEFAULT_SIMULATION_PREFIX
tags list[str] | None

OpenAPI tags of the webhook and withdrawal routes. Defaults to ["mercado-pago"]; the simulation routes always carry "mercado-pago (dev)".

None
include_in_schema bool

Whether the routes appear in OpenAPI.

True
tolerance_seconds float | None

Signature clock drift allowed.

DEFAULT_TOLERANCE_SECONDS
docs_locale str | None

Language of the OpenAPI text — "en-US" or "pt-BR"; None reads API_DOCS_LOCALE.

None

Returns:

Name Type Description
APIRouter APIRouter

Ready for app.include_router.

Raises:

Type Description
RuntimeError

If simulate is True outside development and test.

ValueError

If simulate is True and no simulator is found for provider, no webhook secret is configured, simulation_url comes without simulate=True or together with simulation_api, or simulation_client comes without simulation_url.

MercadoPagoWithdrawConfig dataclass

MercadoPagoWithdrawConfig(
    service_factory: Callable[[AsyncSession], WalletService],
    session_factory: Callable[..., AsyncIterator[AsyncSession]],
    current_user_id: Callable[..., Any],
    pix_destination: Callable[..., Any],
    payout: PayoutProvider | None = None,
    mailer: AdminMailer | None = None,
    admin_emails: Sequence[str] = (),
    record_model: type[BaseManualPayoutModel] | None = None,
    record_url: str | None = None,
    hooks: ManualPayoutHooks | None = None,
    path: str = DEFAULT_WITHDRAW_PATH,
)

How the withdrawal route resolves the wallet, the user and the payout.

Same dependencies as :func:~tempest_fastapi_sdk.wallet.make_wallet_router: the user and the Pix key come from the service, never from the request.

Attributes:

Name Type Description
service_factory Callable[[AsyncSession], WalletService]

Builds the request-scoped wallet service from the session.

session_factory Callable[..., AsyncIterator[AsyncSession]]

Yields the request's session.

current_user_id Callable[..., Any]

Dependency resolving the authenticated user's :class:~uuid.UUID.

pix_destination Callable[..., Any]

Dependency resolving the user's :class:~tempest_fastapi_sdk.wallet.PixDestinationSchema from their profile; raise from it when there is none.

payout PayoutProvider | None

An automated provider. Leave None to build a :class:~tempest_fastapi_sdk.wallet.ManualPayoutProvider from mailer and admin_emails.

mailer AdminMailer | None

Sends the manual payout order.

admin_emails Sequence[str]

Who receives it.

record_model type[BaseManualPayoutModel] | None

The project's concrete manual payout table; each withdrawal writes a row the admin panel completes.

record_url str | None

Link to a row in the panel, {id} for the row id, written into the e-mail.

hooks ManualPayoutHooks | None

Transition callbacks handed to the :class:~tempest_fastapi_sdk.wallet.ManualPayoutProvider: on_requested runs in the transaction that writes the row (raising refuses the withdrawal and returns the debit), and on_canceled in the one that cancels it when the e-mail fails. Needs record_model — without a row there is no transaction for them to join. Pass the same instance to :class:~tempest_fastapi_sdk.wallet.ManualPayoutService for on_paid / on_rejected.

path str

The route's path.

provider

provider(session: AsyncSession) -> PayoutProvider

Build the payout provider for one request.

Parameters:

Name Type Description Default
session AsyncSession

The request's session — the one the wallet service debits on.

required

Returns:

Name Type Description
PayoutProvider PayoutProvider

payout, or a manual provider writing its row

PayoutProvider

on session.

MercadoPagoWebhookAckSchema

Bases: BaseSchema

What the webhook route answers once on_delivery returned.

Mercado Pago reads only the status; the body is for a log or a test.

Attributes:

Name Type Description
ok bool

Always True.

data_id str

The data.id the signature covered.

order_status str | None

The re-read order's status, or None when the delivery is not about a known order.

MercadoPagoDeliveryHandler module-attribute

MercadoPagoDeliveryHandler = Callable[[MercadoPagoOrderDelivery], Awaitable[None]]

An async callable receiving one verified, re-read delivery.

Raise to answer 500 and have Mercado Pago deliver again; return to answer 200.

DEFAULT_WEBHOOK_PATH module-attribute

DEFAULT_WEBHOOK_PATH: Final[str] = '/webhooks/mercado-pago'

Where the webhook route is mounted by default.

DEFAULT_WITHDRAW_PATH module-attribute

DEFAULT_WITHDRAW_PATH: Final[str] = '/api/mercado-pago/withdraw'

Where the withdrawal route is mounted by default.

mercado_pago_provider_for

mercado_pago_provider_for(
    settings: MercadoPagoSettings | None = None,
    *,
    simulate: bool = False,
    provider_class: type[MercadoPagoPixProvider] = MercadoPagoPixProvider,
    simulation_api: FakeMercadoPagoOrdersAPI | None = None,
) -> MercadoPagoPixProvider
mercado_pago_provider_for(
    settings: MercadoPagoSettings | None = None,
    *,
    simulate: bool = False,
    provider_class: type[MercadoPagoCardProvider],
    simulation_api: FakeMercadoPagoOrdersAPI | None = None,
) -> MercadoPagoCardProvider
mercado_pago_provider_for(
    settings: MercadoPagoSettings | None = None,
    *,
    simulate: bool = False,
    provider_class: type[MercadoPagoPixProvider]
    | type[MercadoPagoCardProvider] = MercadoPagoPixProvider,
    simulation_api: FakeMercadoPagoOrdersAPI | None = None,
) -> MercadoPagoPixProvider | MercadoPagoCardProvider

Build the Mercado Pago adapter a service charges with.

Parameters:

Name Type Description Default
settings MercadoPagoSettings | None

The service's settings. None reads MERCADOPAGO_* and ENV from the environment and .env.

None
simulate bool

True runs the adapter over a simulator in memory instead of the API host. Refused outside development and test.

False
provider_class type[MercadoPagoPixProvider] | type[MercadoPagoCardProvider]

:class:MercadoPagoPixProvider (default) or :class:MercadoPagoCardProvider.

MercadoPagoPixProvider
simulation_api FakeMercadoPagoOrdersAPI | None

The simulator to run over, to share one between a Pix and a card provider. None builds one signing with MERCADOPAGO_WEBHOOK_SECRET (or the simulator's default secret when that is empty). Ignored unless simulate is True.

None

Returns:

Type Description
MercadoPagoPixProvider | MercadoPagoCardProvider

MercadoPagoPixProvider | MercadoPagoCardProvider: The adapter, of

MercadoPagoPixProvider | MercadoPagoCardProvider

provider_class. In simulation,

MercadoPagoPixProvider | MercadoPagoCardProvider

func:simulation_api_for returns its simulator.

Raises:

Type Description
RuntimeError

If simulate is True outside development and test.

simulation_api_for

simulation_api_for(
    provider: MercadoPagoPixProvider | MercadoPagoCardProvider,
) -> FakeMercadoPagoOrdersAPI | None

Find the simulator a provider runs over.

Parameters:

Name Type Description Default
provider MercadoPagoPixProvider | MercadoPagoCardProvider

A provider.

required

Returns:

Name Type Description
FakeMercadoPagoOrdersAPI | None

FakeMercadoPagoOrdersAPI | None: The simulator, when the provider came

from FakeMercadoPagoOrdersAPI | None

func:mercado_pago_provider_for with simulate=True.

MercadoPagoSimulationResultSchema

Bases: BaseSchema

The answer of a simulation route.

Attributes:

Name Type Description
order dict[str, Any]

The order after the transition, as GET /v1/orders/{id} answers it.

delivery MercadoPagoSimulatedDeliverySchema

How the webhook went.

MercadoPagoSimulatedDeliverySchema

Bases: BaseSchema

What the service's webhook route answered to a simulated delivery.

Attributes:

Name Type Description
action str

The delivery's action.

status_code int

The webhook route's status — 200 when on_delivery returned, 401 for a signature mismatch, 500 when it raised.

body Any

The webhook route's body, decoded when it is JSON.

SIMULATION_TAG module-attribute

SIMULATION_TAG: Final[str] = 'mercado-pago (dev)'

OpenAPI tag of the simulation routes, so they stand apart in /docs.

RemoteMercadoPagoSimulation

RemoteMercadoPagoSimulation(
    base_url: str, *, client: AsyncClient | None = None, timeout: float = 10.0
)

Drive a tempest mercado-pago fake-api running in another process.

The in-memory simulator lives in one process, so a worker that re-reads an order (a sweep of pending charges, a refund cron) cannot see what the API process created. Run tempest mercado-pago fake-api once, point every process's MERCADOPAGO_BASE_URL at it, and give make_mercado_pago_router(simulate=True, simulation_url=...) the same URL: the simulation routes then move the order on the fake-api, through its control prefix (:data:~tempest_fastapi_sdk.testing.fakes.FAKE_CONTROL_PREFIX), and deliver the signed webhook to the service's own route, as the in-memory mode does.

Attributes:

Name Type Description
base_url str

The fake-api's base URL, without a trailing /.

timeout float

Seconds per request when no client is injected.

Point at a running fake-api.

Parameters:

Name Type Description Default
base_url str

Where the fake-api answers, e.g. "http://mp-fake:8090".

required
client AsyncClient | None

The client to send with; its lifecycle stays with the caller. None opens a short-lived client per call.

None
timeout float

Seconds per request when client is None.

10.0

list_orders async

list_orders() -> list[dict[str, Any]]

List every order on the fake-api, oldest first.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: The orders; one request per order after the

list[dict[str, Any]]

listing of ids.

Raises:

Type Description
HTTPError

When the fake-api cannot be reached, answers an unexpected status, or answers a body that is not its JSON (:class:httpx.DecodingError).

find_order async

find_order(reference: str) -> dict[str, Any]

Read one order by id or by external_reference.

Parameters:

Name Type Description Default
reference str

The order id or its external_reference.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The order.

Raises:

Type Description
KeyError

If no order matches.

HTTPError

When the fake-api cannot be reached, answers an unexpected status, or answers a body that is not its JSON (:class:httpx.DecodingError).

apply async

apply(
    reference: str, transition: str, /, amount_cents: int | None = None
) -> tuple[dict[str, Any], str]

Apply a transition on the fake-api.

Parameters:

Name Type Description Default
reference str

The order id or its external_reference.

required
transition str

The transition name.

required
amount_cents int | None

For refund: a partial amount.

None

Returns:

Type Description
tuple[dict[str, Any], str]

tuple[dict[str, Any], str]: The order and the delivery action.

Raises:

Type Description
KeyError

If no order matches.

ValueError

If the move does not apply to the order's state.

HTTPError

When the fake-api cannot be reached, answers an unexpected status, or answers a body that is not its JSON (:class:httpx.DecodingError).

MercadoPagoSimulationBackend

Bases: Protocol

Where the simulation routes read and move orders.

Two implementations ship: the in-memory :class:~tempest_fastapi_sdk.testing.fakes.FakeMercadoPagoOrdersAPI (wrapped by :class:MercadoPagoSimulator) and :class:RemoteMercadoPagoSimulation, which drives a tempest mercado-pago fake-api over HTTP so an API and a worker in separate processes see the same orders.

reference is an order id or the external_reference the service sent on create; when several orders share an external_reference the most recent one is meant.

list_orders async

list_orders() -> list[dict[str, Any]]

List every order, oldest first.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: The orders, as GET /v1/orders/{id}

list[dict[str, Any]]

answers each.

find_order async

find_order(reference: str) -> dict[str, Any]

Read one order by id or by external_reference.

Parameters:

Name Type Description Default
reference str

The order id or its external_reference.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The order.

Raises:

Type Description
KeyError

If no order matches.

apply async

apply(
    reference: str, transition: str, /, amount_cents: int | None = None
) -> tuple[dict[str, Any], str]

Apply a transition to an order.

Parameters:

Name Type Description Default
reference str

The order id or its external_reference.

required
transition str

pay, expire, fail, cancel, capture or refund.

required
amount_cents int | None

For refund: a partial amount.

None

Returns:

Type Description
dict[str, Any]

tuple[dict[str, Any], str]: The order after the move and the

str

delivery action announcing it.

Raises:

Type Description
KeyError

If no order matches.

ValueError

If the move does not apply to the order's state.

DEFAULT_SIMULATION_PREFIX module-attribute

DEFAULT_SIMULATION_PREFIX: Final[str] = '/dev/mercado-pago'

Path prefix of the simulation routes.

MercadoPagoTransition module-attribute

MercadoPagoTransition = Literal['pay', 'expire', 'fail', 'cancel', 'capture', 'refund']

The moves a simulation route applies — the simulator's TRANSITIONS.

ensure_simulation_allowed

ensure_simulation_allowed(settings: MercadoPagoSettings | None, what: str) -> None

Refuse a simulation outside development and test.

The environment is settings.ENV when the settings carry one (a Settings composing EnvironmentSettings, or the ambient read of :func:ambient_settings), else the ENV environment variable. Unset counts as production: a host that forgot ENV must not expose routes that mark orders paid.

Parameters:

Name Type Description Default
settings MercadoPagoSettings | None

The service's settings.

required
what str

What is being built, for the message ("make_mercado_pago_router with simulate=True").

required

Raises:

Type Description
RuntimeError

When the environment is not development or test.

MercadoPagoSimulator

MercadoPagoSimulator(
    backend: FakeMercadoPagoOrdersAPI | MercadoPagoSimulationBackend,
    *,
    secret: str | None = None,
    settings: MercadoPagoSettings | None = None,
    app: ASGIApp | None = None,
    webhook_url: str | None = None,
    client: AsyncClient | None = None,
    timeout: float = 10.0,
)

Move an order and deliver the signed webhook announcing it.

Where the delivery goes:

  • app and webhook_url — in process, through the whole application (middleware, the signature check, the service's handler) over httpx.ASGITransport. webhook_url is a path ("/api/webhook/mercadopago", sent to http://localhost) or an absolute URL whose host the app accepts.
  • webhook_url alone — over the network, to a running service ("http://api:8000/api/webhook/mercadopago"), with client or a short-lived client per call.
  • neither — only :meth:apply_to delivers; the development routes use it with the request's own application.

Attributes:

Name Type Description
backend MercadoPagoSimulationBackend

Where orders are moved.

secret str

The secret the service's webhook route verifies with.

webhook_url str | None

Where :meth:apply delivers.

app ASGIApp | None

The application that receives an in-process delivery.

timeout float

Seconds per delivery when no client is injected.

Build the simulator.

Parameters:

Name Type Description Default
backend FakeMercadoPagoOrdersAPI | MercadoPagoSimulationBackend

The in-memory simulator the provider runs over, or a backend such as :class:~tempest_fastapi_sdk.integrations.payment.adapters.RemoteMercadoPagoSimulation.

required
secret str | None

The secret the service verifies deliveries with. None reads MERCADOPAGO_WEBHOOK_SECRET from settings (or the environment), then falls back to the in-memory simulator's secret.

None
settings MercadoPagoSettings | None

The service's settings, for the secret and for ENV.

None
app ASGIApp | None

Deliver in process to this application. Needs webhook_url; excludes client.

None
webhook_url str | None

The service's webhook route.

None
client AsyncClient | None

The client a network delivery is sent with; its lifecycle stays with the caller.

None
timeout float

Seconds per delivery when client is None.

10.0

Raises:

Type Description
RuntimeError

Outside ENV=development and ENV=test.

ValueError

When no webhook secret is found, app comes without webhook_url, app comes with client, or a network webhook_url is not absolute.

apply async

apply(
    reference: str,
    transition: MercadoPagoTransition | str,
    *,
    amount_cents: int | None = None,
) -> MercadoPagoSimulationResultSchema

Move an order and deliver the webhook to webhook_url.

Parameters:

Name Type Description Default
reference str

The order id or the external_reference the service sent on create (the most recent order wins when several share it).

required
transition MercadoPagoTransition | str

pay, expire, fail, cancel, capture or refund.

required
amount_cents int | None

For refund: a partial amount.

None

Returns:

Name Type Description
MercadoPagoSimulationResultSchema MercadoPagoSimulationResultSchema

The order after the move and

MercadoPagoSimulationResultSchema

what the webhook route answered. A route that refused the

MercadoPagoSimulationResultSchema

delivery (401) or raised (500) is reported here, not

MercadoPagoSimulationResultSchema

raised.

Raises:

Type Description
RuntimeError

When the simulator was built without webhook_url.

KeyError

If no order matches reference.

ValueError

If the move does not apply to the order's state.

HTTPError

When a remote backend cannot be reached, or a network delivery cannot reach the service.

apply_to async

apply_to(
    reference: str,
    transition: MercadoPagoTransition | str,
    *,
    client: AsyncClient,
    endpoint: str,
    amount_cents: int | None = None,
) -> MercadoPagoSimulationResultSchema

Move an order and deliver the webhook with the given client.

Parameters:

Name Type Description Default
reference str

The order id or its external_reference.

required
transition MercadoPagoTransition | str

The move.

required
client AsyncClient

The client the delivery is posted with — one over httpx.ASGITransport reaches an app in process.

required
endpoint str

The webhook route, relative to the client's base URL or absolute.

required
amount_cents int | None

For refund: a partial amount.

None

Returns:

Name Type Description
MercadoPagoSimulationResultSchema MercadoPagoSimulationResultSchema

The order and the delivery.

Raises:

Type Description
KeyError

If no order matches reference.

ValueError

If the move does not apply to the order's state.

HTTPError

When a remote backend cannot be reached, or the delivery cannot reach the service.

make_mercado_pago_simulation_router

make_mercado_pago_simulation_router(
    *,
    webhook_route: str,
    simulation_url: str | None = None,
    simulation_api: FakeMercadoPagoOrdersAPI | None = None,
    simulation_client: AsyncClient | None = None,
    secret: str | None = None,
    settings: MercadoPagoSettings | None = None,
    prefix: str = DEFAULT_SIMULATION_PREFIX,
    include_in_schema: bool = True,
    docs_locale: str | None = None,
) -> APIRouter

Build only the development routes, delivering to the service's webhook.

For a service that wrote its own webhook route (its own controller, BackgroundTasks, a worker): the simulation then exercises the same path production does. Mount the router on the same application as that route — the delivery goes through it in process.

Parameters:

Name Type Description Default
webhook_route str

The service's webhook route: its name (@router.post(..., name="mercado_pago_webhook")), or its path when it starts with / ("/api/webhook/mercadopago").

required
simulation_url str | None

Base URL of a running tempest mercado-pago fake-api, shared with the worker through MERCADOPAGO_BASE_URL. Excludes simulation_api.

None
simulation_api FakeMercadoPagoOrdersAPI | None

The in-memory simulator the provider runs over (see :func:~tempest_fastapi_sdk.integrations.payment.adapters.simulation_api_for).

None
simulation_client AsyncClient | None

The client the remote simulation sends with; its lifecycle stays with the caller. Needs simulation_url.

None
secret str | None

The secret the service's webhook route verifies with. None reads MERCADOPAGO_WEBHOOK_SECRET.

None
settings MercadoPagoSettings | None

The service's settings, for the secret and for ENV.

None
prefix str

Path prefix of the routes.

DEFAULT_SIMULATION_PREFIX
include_in_schema bool

Whether the routes appear in OpenAPI.

True
docs_locale str | None

Language of the OpenAPI text — "en-US" or "pt-BR"; None reads API_DOCS_LOCALE.

None

Returns:

Name Type Description
APIRouter APIRouter

Ready for app.include_router.

Raises:

Type Description
RuntimeError

Outside ENV=development and ENV=test.

ValueError

When neither or both of simulation_url and simulation_api are given, simulation_client comes without simulation_url, or no webhook secret is found.