Ir para o conteúdo

tempest_fastapi_sdk.integrations.payment.base

O contrato canônico de pagamento em que todo provedor embutido é mapeado.

« Integrações e pagamentos


PixProvider

Bases: Protocol

The contract every Pix integration implements.

A Protocol rather than a base class, matching how the SDK models every other provider seam (RateLimitStore, QuotaStore, ModerationBackend, PushDispatcher, TextBackend). An adapter satisfies it by shape; nothing has to be inherited.

Deliberately not runtime_checkable: isinstance against a runtime-checkable protocol only checks that the attribute names exist, so an adapter whose create_pix_charge takes the wrong arguments would pass. tests/integrations/payment/test_contract.py compares inspect.signature instead, which is the check worth having.

Attributes:

Name Type Description
provider_name str

The provider's identifier, copied into :attr:PixCharge.provider.

create_pix_charge async

create_pix_charge(request: PixChargeRequest) -> PixCharge

Create a charge.

Parameters:

Name Type Description Default
request PixChargeRequest

What to charge, and for whom.

required

Returns:

Name Type Description
PixCharge PixCharge

The created charge, with the payable code filled in.

get_pix_charge async

get_pix_charge(charge_id: str) -> PixCharge

Read a charge back from the provider.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge as the provider currently reports it.

cancel_pix_charge async

cancel_pix_charge(charge_id: str) -> PixCharge

Withdraw a charge that has not been paid.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge after cancellation. Providers differ in

PixCharge

how much they return here, so fields the provider does not

PixCharge

report on this call come back None rather than being

PixCharge

refetched behind the caller's back.

parse_webhook

parse_webhook(event: object) -> PixPaymentEvent

Turn a verified provider delivery into a canonical event.

Parameters:

Name Type Description Default
event object

Whatever the provider's own verifier produces — an OpenPixWebhookEvent, a MercadoPagoOrderDelivery, and so on. Typed object because the input type is the one part of this contract that is genuinely per-provider; each adapter narrows and validates with isinstance.

required

Returns:

Name Type Description
PixPaymentEvent PixPaymentEvent

The canonical event.

PixChargeRequest

Bases: BaseSchema

What a service asks for when it wants to charge over Pix.

Attributes:

Name Type Description
amount_cents int

The amount in cents. An int, never a float: both bundled providers type money as number in their specification, and a value that has been through a float is a value that can be wrong. The adapter converts to whatever unit its provider states.

reference str

The identifier the service owns. It becomes OpenPix's correlationID and Mercado Pago's external_reference, and it is what lets a webhook that arrives before the HTTP response still be reconciled. It is also the create's idempotency key: repeating a create with the same reference answers the charge that already exists.

description str | None

Free text shown to the payer where the provider supports it.

expires_in timedelta | None

How long the charge stays payable. None leaves the provider's default in place.

payer PixPayer | None

Who is paying, when known.

PixCharge

Bases: _EnumSafeSchema

A Pix charge, in the shape every provider is mapped into.

Attributes:

Name Type Description
provider str

The provider that owns this charge, matching :attr:PixProvider.provider_name.

provider_charge_id str

The charge's identifier at the provider, which is what a later read or cancellation is addressed to.

reference str

The identifier the service sent in :attr:PixChargeRequest.reference.

amount_cents int

The amount in cents.

currency str

ISO 4217 code. Pix is BRL-only, and the field exists so the contract does not have to change the day a provider settles in another currency.

status PaymentStatusEnum

The canonical state.

provider_status str

The provider's own string, kept verbatim for logs and support — the canonical mapping loses detail on purpose, and this is where the detail stays.

br_code str | None

The EMV copy-and-paste string.

qr_code_base64 str | None

The QR code as a Base64 image, for providers that return the image inline.

qr_code_image_url str | None

The QR code as a URL, for providers that return a link instead. Both fields exist because the two bundled providers disagree: OpenPix returns a URL, Mercado Pago returns Base64. Filling the wrong one would make the contract lie about what the caller can render.

end_to_end_id str | None

The Pix end-to-end identifier, when the provider reports it. Deliberately not filled with a provider's internal transaction id: a txid is not an E2E id, and a plausible wrong value is worse than a missing one.

expires_at datetime | None

When the charge stops being payable.

paid_at datetime | None

When settlement happened.

raw dict[str, Any]

The provider's payload as decoded. Present because BaseSchema is extra="ignore": without it, everything a provider sends beyond this contract would be dropped in validation, with no error. Keys are spelled the way the provider spells them on the wire, whichever path produced the charge — an adapter that reads a response through a generated model dumps it by_alias, so an API read and a webhook delivery answer to the same key.

PixPayer

Bases: BaseSchema

Who is paying, to the extent a provider accepts being told.

Every field is optional because a Pix charge is valid without any of them; providers use what they get to prefill their screens and to bind the charge to a tax ID when asked to.

Attributes:

Name Type Description
name str | None

The payer's full name.

tax_id str | None

CPF or CNPJ, digits or formatted — the adapter sends it in whatever shape its provider expects.

email str | None

The payer's e-mail.

phone str | None

The payer's phone number.

PixPaymentEvent

Bases: _EnumSafeSchema

A webhook delivery, after the provider's verifier accepted it.

Verification stays with the provider — RSA-1024 at OpenPix, HMAC at Stripe — because signing is the one thing that cannot be unified. What is unified is what comes out of it.

Attributes:

Name Type Description
provider str

The provider that delivered the event.

type PixEventTypeEnum

The canonical meaning.

provider_event_name str

The provider's own event name, kept even when it maps to :attr:PixEventTypeEnum.UNKNOWN.

charge PixCharge | None

The charge the event is about, when the payload carried enough to build one.

raw dict[str, Any]

The decoded delivery body.

PaymentStatusEnum

Bases: BaseStrEnum

The state of a charge, in the vocabulary the SDK guarantees.

A provider's own string is never discarded — it travels alongside in :attr:PixCharge.provider_status. This enum is what a service branches on.

:attr:UNKNOWN exists for the same reason :attr:PixEventTypeEnum.UNKNOWN does: a provider can report a state this SDK version has never seen, and the two ways of hiding that are both worse than saying so. Falling through to :attr:PENDING reports a charge as awaiting payment when the provider just said it is not; refusing to read the charge at all turns a state the SDK does not recognize into a failed request, with the real state nowhere the caller can see it.

Attributes:

Name Type Description
PENDING str

Created and waiting for the payer.

AUTHORIZED str

Approved by the card issuer and held, not captured. The money has not moved: capture settles it, cancelling releases the hold. Distinct from :attr:PENDING, which waits on the payer, and from :attr:PAID, which is settled.

PAID str

Settled. The money is with the receiver.

EXPIRED str

The window closed before payment.

CANCELLED str

Withdrawn by the merchant or the provider.

REFUNDED str

Paid and then returned to the payer.

CHARGED_BACK str

Reversed by the payer's institution after settlement, which is not the same event as a refund and is not initiated by us.

IN_ANALYSIS str

Held by the provider for review — neither settled nor refused yet.

FAILED str

Refused. A terminal state distinct from :attr:EXPIRED, which is about time rather than refusal.

UNKNOWN str

A state this SDK version does not classify. The provider's own string stays in :attr:PixCharge.provider_status, so an unmapped state is visible rather than reported as something it is not.

PixEventTypeEnum

Bases: BaseStrEnum

What a webhook delivery means, once the provider name is dropped.

Attributes:

Name Type Description
CHARGE_CREATED str

A charge came into existence.

CHARGE_PAID str

A charge settled.

CHARGE_EXPIRED str

A charge reached its deadline unpaid.

CHARGE_CANCELLED str

A charge was withdrawn.

CHARGE_REFUNDED str

Money went back to the payer.

UNKNOWN str

A delivery this SDK version does not classify. The provider's own name stays in :attr:PixPaymentEvent.provider_event_name, so an unmapped event is visible rather than swallowed.

PixRefundProvider

Bases: PixProvider, Protocol

A :class:PixProvider that can also give money back, idempotently.

Separate from :class:PixProvider so a provider without a refund still satisfies the base contract; a service that refunds depends on this one instead.

The contract is what makes a retried refund safe without a lease of the service's own:

  • refund_reference is the refund's idempotency key. Repeating a refund with the same reference answers the refund that already exists instead of giving the money back twice — including when the first call's answer was lost to a timeout after the provider applied it.
  • Repeating it with the same reference and another amount raises :class:~tempest_fastapi_sdk.exceptions.PixRefundReferenceConflictException.
  • Asking for more than is left raises :class:~tempest_fastapi_sdk.exceptions.PixRefundExceedsBalanceException — a full refund (amount_cents=None) of a charge with nothing left included.
  • :meth:get_refunded_cents answers the total the provider lists, so a service can reconcile what it recorded against what really happened.

Use one reference per refund, unique across the account: OpenPix keys the refund by it as a correlationID.

Attributes:

Name Type Description
provider_name str

Copied into :attr:PixRefund.provider.

refund_pix_charge async

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

Give a paid charge's money back, in full or in part.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required
amount_cents int | None

How much to refund. None refunds whatever is left.

None
refund_reference str

The service's identifier for this refund, and its idempotency key.

required

Returns:

Name Type Description
PixRefund PixRefund

The refund — the existing one when the reference was

PixRefund

already used on this charge.

get_refunded_cents async

get_refunded_cents(charge_id: str) -> int

Answer how much of a charge has been refunded, in cents.

Parameters:

Name Type Description Default
charge_id str

:attr:PixCharge.provider_charge_id.

required

Returns:

Name Type Description
int int

The sum of every refund the provider lists for the charge

int

except the ones in :attr:PixRefundStatusEnum.FAILED. A refund

int

still in flight counts: treating it as money owed is what lets a

int

second refund go out while the first settles. 0 when there

int

is none.

PixRefund

Bases: _EnumSafeSchema

One refund of a Pix charge, in the shape every provider is mapped into.

Attributes:

Name Type Description
provider str

The provider that owns the charge.

provider_charge_id str

The charge the refund belongs to, as :attr:PixCharge.provider_charge_id names it.

refund_reference str

The identifier the service sent — the refund's idempotency key.

provider_refund_id str | None

The refund's identifier at the provider, when it reports one.

amount_cents int

How much this refund gives back, in cents.

refunded_cents int

How much of the charge has been refunded in total once this refund is counted, with the same rule as :meth:PixRefundProvider.get_refunded_cents.

status PixRefundStatusEnum

The canonical state of this refund.

provider_status str

The provider's own string for it.

end_to_end_id str | None

The refund's Pix end-to-end identifier, when the provider reports one.

raw dict[str, Any]

The provider's record of the refund, as decoded.

PixRefundStatusEnum

Bases: BaseStrEnum

Where one refund stands, in the vocabulary the SDK guarantees.

The provider's own string travels alongside in :attr:PixRefund.provider_status.

Attributes:

Name Type Description
PENDING str

Accepted by the provider and not settled yet — OpenPix's IN_PROCESSING.

COMPLETED str

The money went back to the payer — OpenPix's CONFIRMED, Mercado Pago's processed.

FAILED str

Refused after it was accepted — OpenPix's REJECTED. The only state :meth:PixRefundProvider.get_refunded_cents leaves out of the total.

UNKNOWN str

A state this SDK version does not classify. Counted as refunded by get_refunded_cents: reading an unrecognized refund as money still owed is what lets a retry refund twice.

CardProvider

Bases: Protocol

The contract a card integration implements.

Separate from :class:PixProvider because a card charge has a lifecycle Pix does not: it can be authorized and captured later, refunded in part, and declined with a reason. Structural, like every provider seam here.

A decline is a result, not an exception: create_card_charge returns a :class:CardCharge with :attr:PaymentStatusEnum.FAILED and the reason in :attr:CardCharge.status_detail. Exceptions are for the call itself failing — transport, an invalid request — where whether a charge exists is the open question.

Attributes:

Name Type Description
provider_name str

Copied into :attr:CardCharge.provider.

create_card_charge async

create_card_charge(request: CardChargeRequest) -> CardCharge

Charge, or only authorize, a tokenized card.

Parameters:

Name Type Description Default
request CardChargeRequest

What to charge, and how.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge — :attr:PaymentStatusEnum.PAID,

CardCharge

attr:PaymentStatusEnum.AUTHORIZED or :attr:PaymentStatusEnum.FAILED.

get_card_charge async

get_card_charge(charge_id: str) -> CardCharge

Read a charge back from the provider.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge as the provider reports it now.

capture_card_charge async

capture_card_charge(charge_id: str) -> CardCharge

Settle an authorized charge.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge after capture.

cancel_card_charge async

cancel_card_charge(charge_id: str) -> CardCharge

Release an authorization that was not captured.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge after cancellation.

refund_card_charge async

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

Give money back to the payer, in full or in part.

Parameters:

Name Type Description Default
charge_id str

:attr:CardCharge.provider_charge_id.

required
amount_cents int | None

How much to refund. None refunds whatever is left.

None

Returns:

Name Type Description
CardCharge CardCharge

The charge after the refund, with

CardCharge

attr:CardCharge.refunded_cents updated.

CardChargeRequest

Bases: BaseSchema

What a service asks for when it charges a card.

The card itself never reaches the service: it is tokenized in the browser or app with the provider's public key, and what arrives here is the token. Handling the card number on a server puts that server in PCI DSS scope.

Attributes:

Name Type Description
amount_cents int

The price, in cents. With installments it is still the price, not the total the installment options quote: the provider adds the interest on top and reports what the payer owes in :attr:CardCharge.payer_total_cents.

reference str

The identifier the service owns, as in :attr:PixChargeRequest.reference.

card_token str

The single-use token the client-side tokenizer produced.

payment_method_id str

The card brand as the provider names it (visa, master, ...), which the tokenizer reports.

installments int

How many installments the payer chose, from the options the provider offered for this card and amount.

capture bool

True charges at once. False only authorizes: the charge comes back :attr:PaymentStatusEnum.AUTHORIZED and waits for :meth:CardProvider.capture_card_charge or :meth:CardProvider.cancel_card_charge.

description str | None

Free text, where the provider supports it.

payer PixPayer | None

Who is paying. The name is historical — the same payer block serves card and Pix.

CardCharge

Bases: _EnumSafeSchema

A card charge, in the shape every provider is mapped into.

Attributes:

Name Type Description
provider str

The provider that owns this charge.

provider_charge_id str

The charge's identifier at the provider — what capture, cancel and refund are addressed to.

reference str

The identifier the service sent.

amount_cents int

The amount charged, in cents.

refunded_cents int

How much of it went back to the payer. A partial refund leaves :attr:status at :attr:PaymentStatusEnum.PAID and shows here.

currency str

ISO 4217 code.

status PaymentStatusEnum

The canonical state. A declined card is :attr:PaymentStatusEnum.FAILED, returned, not raised: the charge exists at the provider, and the reason is in :attr:status_detail.

provider_status str

The provider's own status string.

status_detail str | None

The provider's reason — rejected_by_issuer, waiting_capture, accredited. What a service shows the payer on a decline comes from here.

payment_method_id str | None

The card brand.

installments int | None

How many installments were charged.

installment_amount_cents int | None

Each installment, in cents, interest included, as the provider reports it.

payer_total_cents int | None

What the payer owes, in cents: :attr:amount_cents plus installment interest. Equal to :attr:amount_cents for a single installment. It is the amount the charge was submitted for, not proof of payment — read :attr:status for that. None when the provider does not report it.

raw dict[str, Any]

The provider's payload as decoded.

PayoutProvider

Bases: Protocol

The contract a provider that can send Pix out of the platform implements.

Error contract, which the wallet's withdrawal depends on:

  • raise :class:~tempest_fastapi_sdk.exceptions.PayoutRejectedException only when the provider definitively refused — the money did not leave, so the debit is given back;
  • let anything else propagate (timeout, connection error, unreadable answer): the outcome is unknown and the debit must be kept.

Attributes:

Name Type Description
provider_name str

Copied into :attr:PayoutResult.provider.

transfer_to_pix_key async

transfer_to_pix_key(request: PayoutRequest) -> PayoutResult

Send request.amount_cents to request.pix_key.

Parameters:

Name Type Description Default
request PayoutRequest

The transfer.

required

Returns:

Name Type Description
PayoutResult PayoutResult

The accepted transfer.

PayoutRequest

Bases: BaseSchema

A transfer from the platform account to someone's Pix key.

Attributes:

Name Type Description
amount_cents int

The amount, in cents.

pix_key str

The destination key, read from the payee's profile and never from the request that asked for the payout.

pix_key_type PixKeyType

The kind of key — the SDK's :class:~tempest_fastapi_sdk.PixKeyType, which :func:~tempest_fastapi_sdk.detect_pix_key_type can infer from the key itself.

correlation_id str

The service's id for this payout. Providers use it to make a retried request idempotent.

comment str | None

Text that travels with the transfer.

payee_id str | None

The service's id of whoever is paid — the wallet owner on a withdrawal. Automated providers ignore it; :class:~tempest_fastapi_sdk.wallet.ManualPayoutProvider puts it in the e-mail, so the administrator knows whose withdrawal it is.

PayoutResult

Bases: _EnumSafeSchema

What the provider answered when it accepted a payout.

Attributes:

Name Type Description
correlation_id str

Echo of :attr:PayoutRequest.correlation_id.

status PayoutStatusEnum

Confirmed or still pending.

provider str

Which provider handled it.

provider_status str | None

The provider's own status string, kept so a value the mapping did not anticipate is still visible.

PayoutStatusEnum

Bases: BaseStrEnum

Where a payout stands right after the provider accepted it.

A refusal is not a status here: it is :class:~tempest_fastapi_sdk.exceptions.PayoutRejectedException, raised, because the caller has to act on it (give the money back).

Attributes:

Name Type Description
CONFIRMED

The provider reports the transfer done.

PENDING

Accepted, not settled yet. Settlement or failure arrives later (for OpenPix, the MOVEMENT_* webhooks).