Pular para o conteúdo

Integração

API HTTP

Base, autenticação, envelopes e as rotas — pra quem não usa o SDK.

Atualizado em

O SDK é um cliente fino sobre uma API REST. Se você não está em Node — ou está depurando com curl — é isto que você precisa.

Base

AmbienteAPICheckout hospedado
Sandbox (sk_test_)https://api-sandbox.beinfi.comhttps://app-sandbox.beinfi.com
Produção (sk_live_)https://api.beinfi.comhttps://app.beinfi.com

O prefixo da chave decide o ambiente. Uma sk_test_ enviada pra produção não falha com "chave errada" — o recurso simplesmente não existe lá (404).

Autenticação

curl https://api-sandbox.beinfi.com/metering/products \
  -H "Authorization: Bearer sk_test_…"

Só Authorization: Bearer. Não existe X-Api-Key.

As rotas públicas de checkout (/public/v1/* e /pay/{slug}/*) não levam chave: são abertas por definição, porque rodam no navegador do pagador.

Cadastro pelo agente

Use POST /public/v1/agent-signups com Idempotency-Key, email e accountName para pedir um código. Confirme em POST /public/v1/agent-signups/{challengeId}/verify. Só a confirmação cria a conta com dono e retorna as chaves de teste. Veja cadastro pelo agente para corpos das chamadas, limites e retomada. Contas existentes usam login normal. A criação anônima por claim foi encerrada e retorna 410 signup_required.

Idempotency-Key

Mutações autenticadas e o pedido público de OTP exigem o header. A confirmação de OTP consome o desafio uma vez e não repete chaves:

-H "Idempotency-Key: $(uuidgen)"

Sem ele: 400 idempotency_key_required. Reusar a mesma chave com corpo diferente: 409 idempotency_key_reused.

Envelopes de resposta

Algumas rotas devolvem o recurso embrulhado. Criar produto devolve dois:

{ "product": { "id": "0d83d66e-…", "key": "x1", … },
  "version": { "id": "…", "version": 1, "status": "draft" } }

Listagens vêm sob a chave do plural ({"products":[…]}, {"links":[…]}). Confira o corpo antes de assumir que o objeto está na raiz — é o erro mais comum de quem sai do SDK.

Envelopes de erro

São dois, e a diferença importa se você faz parsing:

// handlers — a maioria esmagadora
{ "message": "…", "error_code": "validation_failed", "tracer_id": "befee651…",
  "errors": [ { "field": "eventId", "description": "is required" } ] }
 
// middleware (idempotência, rate limit)
{ "error": { "code": "rate_limited", "message": "…", "request_id": "e0484f60…" } }

errors[] é onde mora o motivo de um 422 — é o campo que diz o que corrigir. Guarde o tracer_id/request_id: é o que o suporte procura.

Rotas

{id} são UUIDs, exceto onde indicado. Esta seção é gerada do contrato OpenAPI, então acompanha a API.

Catálogo e clientes

MétodoRota
GET · POST/metering/customersList tenant customers
GET/metering/customers/{customerID}Get tenant customer detail or legacy enrollment by ID
GET · POST/metering/customers/{customerID}/rate-cardsList a customer's rate cards
DELETE/metering/customers/{customerID}/rate-cards/{rateCardID}Delete a rate card
GET/metering/customers/{customerID}/stateSingle-read customer state (enrollment, credit, subscriptions, usage)
GET/metering/customers/{customerID}/walletGet meter wallet balances for an enrollment
POST/metering/customers/{customerID}/wallet/creditCredit a meter balance
POST/metering/customers/{customerID}/wallet/debitDebit a meter balance
POST/metering/eventsIngest a single usage event
POST/metering/events/batchIngest a batch of usage events (all-or-nothing)
GET/metering/overviewTenant KPI summary for the dashboard overview
GET · POST/metering/productsList products
GET · PATCH/metering/products/{productID}Get a product
GET · POST/metering/products/{productID}/customersList product enrollments
GET/metering/products/{productID}/customers/{enrollmentID}Get a product enrollment by enrollment ID
GET · PUT · DELETE/metering/products/{productID}/deliverableGet a product's deliverable metadata
POST/metering/products/{productID}/deliverable/presignPresign an R2 upload URL for a file deliverable
GET · POST/metering/products/{productID}/metersList meters of a product
PATCH/metering/products/{productID}/meters/{meterID}Update a meter's display name / unit / aggregation
GET · POST/metering/products/{productID}/payment-linksList a product's payment links
DELETE/metering/products/{productID}/payment-links/{linkID}Revoke a payment link
GET · POST/metering/products/{productID}/versionsList versions of a product
PUT/metering/products/{productID}/versions/{versionID}/commitmentSet a committed minimum on a version
GET · POST/metering/products/{productID}/versions/{versionID}/pricesList prices on a version
POST/metering/products/{productID}/versions/{versionID}/publishPublish a draft version (makes pricing immutable)
GET/metering/usageGet usage totals for a customer

Cobrança

MétodoRota
GET · POST/billing/couponsList the tenant's coupons
GET · PATCH · DELETE/billing/coupons/{couponID}Get a coupon
GET/billing/customers/{customerID}/invoicesList a customer's invoices
GET/billing/customers/{customerID}/payment-methodsList a payer's stored payment methods
DELETE/billing/customers/{customerID}/payment-methods/{instrumentID}Remove a stored payment method
POST/billing/customers/{customerID}/payment-methods/{instrumentID}/defaultMake a stored payment method the payer's default
GET/billing/customers/{customerID}/subscriptionsList a customer's subscriptions
GET · POST/billing/invoicesList all invoices for the tenant
GET/billing/invoices/{invoiceID}Get an invoice
POST/billing/invoices/{invoiceID}/chargeCharge an open invoice via the PSP
GET/billing/invoices/{invoiceID}/paymentsList payments against an invoice
GET/billing/invoices/{invoiceID}/deliverableList the buyer download grants an invoice's payments produced
POST/billing/invoices/{invoiceID}/sendFinalize and send an invoice
POST/billing/invoices/{invoiceID}/uncollectibleMark an invoice uncollectible
POST/billing/invoices/{invoiceID}/voidVoid an invoice
POST/billing/invoices/from-usageGenerate an invoice from an enrollment's accrued usage (on demand)
GET/billing/paymentsList all payments for the tenant
GET/billing/payments/{paymentID}Get one payment
POST/billing/payments/{paymentID}/refundRefund a payment (full or partial) — o que acontece com o acesso
GET/billing/payments/{paymentID}/refundsList the refunds recorded against a payment
POST/billing/products/{productID}/invoicesPurchase a product — enroll the customer and open a finalized invoice
POST/billing/products/{productID}/subscriptionsCreate a subscription for a customer
GET · PUT/billing/settingsGet the tenant's collection settings
GET/billing/subscriptionsList all subscriptions for the tenant
GET · PATCH/billing/subscriptions/{subscriptionID}Get a subscription
GET · POST/billing/subscriptions/{subscriptionID}/alertsList usage alerts on a subscription
DELETE/billing/subscriptions/{subscriptionID}/alerts/{alertID}Delete a usage alert
POST/billing/subscriptions/{subscriptionID}/invoicesGenerate an invoice for the subscription's current ended period
GET/billing/subscriptions/{subscriptionID}/periodsList billing periods of a subscription

Conta

MétodoRota
GET · POST/account/api-keysList API keys
DELETE/account/api-keys/{keyID}Revoke an API key
GET · POST/account/notification-subscriptionsList notification subscriptions
PATCH · DELETE/account/notification-subscriptions/{subscriptionID}Activate or deactivate a notification subscription
GET/account/notifications/deliveriesList notification delivery audit records
GET · PATCH/account/tenantGet the authenticated tenant
GET · POST/account/webhooksList webhook endpoints
GET · PATCH · DELETE/account/webhooks/{endpointID}Get a webhook endpoint
POST/account/webhooks/{endpointID}/rotate-secretRotate a webhook endpoint's signing secret
GET/account/webhooks/deliveriesList webhook delivery audit records

Público — sem chave

MétodoRota
GET/pay/{slug}/download/{token}Redeem a tokenized digital-product download (unauthenticated)
GET/pay/{slug}/invoices/{invoiceID}Public hosted-checkout invoice read (unauthenticated)
POST/pay/{slug}/invoices/{invoiceID}/chargeInitiate payment on a public checkout invoice (unauthenticated)
POST/pay/{slug}/invoices/{invoiceID}/couponApply a coupon to a public checkout invoice (unauthenticated)
GET/pay/{slug}/links/{token}Resolve a payment link for display (unauthenticated)
POST/pay/{slug}/links/{token}/checkoutMaterialize an invoice from a payment link (unauthenticated, legacy)
POST/pay/{slug}/links/{token}/sessionsOpen (or reuse) a checkout session for a payment link (unauthenticated)
GET/pay/{slug}/links/{token}/sessions/{sessionID}Read a checkout session (unauthenticated)
POST/pay/{slug}/links/{token}/sessions/{sessionID}/chargeMaterialize the invoice and charge a checkout session (unauthenticated)
POST/public/v1/agent-signupsPede um OTP por e-mail sem criar conta
POST/public/v1/agent-signups/{challengeId}/verifyConfirma o código e cria a conta sandbox com dono
POST/public/v1/claimablesRetired; returns 410 signup_required
GET/public/v1/claimables/{claimableID}Public claimable-tenant status (no secrets)

Operação — sessão e webhooks de entrada

MétodoRota
POST/auth/claimables/{claimableID}/claimClaim a provisional tenant to the signed-in user
POST/auth/cli/tokenExchange dashboard session for CLI API key
POST/auth/session/bootstrapProvision tenant on first dashboard signup
POST/auth/session/onboarding/completeMark tenant onboarding complete
POST/auth/session/syncSync dashboard session with backend membership

Uma venda inteira, só com curl

API=https://api-sandbox.beinfi.com
# Obtenha K e SLUG no cadastro por OTP antes de continuar.
K="$INFI_SECRET_KEY"; SLUG="$INFI_TENANT_SLUG"
IDEM() { echo "Idempotency-Key: $(uuidgen)"; }
 
# o cadastro: sem ele a loja não cobra. Em sandbox o envio aprova na hora.
M=$(curl -s -X PUT $API/account/mor/registration -H "Authorization: Bearer $K" \
  -H 'Content-Type: application/json' -H "$(IDEM)" \
  -d '{"country":"GB","entityType":"company","legalName":"Acme Ltd","document":"GB123456789",
       "address":{"line1":"1 High Street","city":"London","postalCode":"EC1A 1BB"}}')
curl -s -X POST $API/account/mor/agreements/$(echo $M | jq -r .agreement.id)/accept \
  -H "Authorization: Bearer $K" -H "$(IDEM)"
curl -s -X PUT $API/account/mor/eligibility -H "Authorization: Bearer $K" \
  -H 'Content-Type: application/json' -H "$(IDEM)" \
  -d '{"sells":["digital_downloads"],"country":"GB","entityType":"company","currency":"BRL"}'
curl -s -X POST $API/account/mor/policy/$(echo $M | jq -r .policy.version)/accept \
  -H "Authorization: Bearer $K" -H "$(IDEM)"
curl -s -X POST $API/account/mor/application/submit -H "Authorization: Bearer $K" -H "$(IDEM)" \
  | jq .admission.status   # "approved"
 
P=$(curl -s -X POST $API/metering/products -H "Authorization: Bearer $K" \
  -H 'Content-Type: application/json' -H "$(IDEM)" \
  -d '{"key":"guia","name":"Guia","type":"item","pricingModel":"one_time",
       "currency":"BRL","basePrice":"49.90"}')
PID=$(echo $P | jq -r .product.id); VID=$(echo $P | jq -r .version.id)
 
curl -s -X POST $API/metering/products/$PID/versions/$VID/publish \
  -H "Authorization: Bearer $K" -H "$(IDEM)"
 
INV=$(curl -s -X POST $API/billing/products/$PID/invoices \
  -H "Authorization: Bearer $K" -H 'Content-Type: application/json' -H "$(IDEM)" \
  -d '{"customer":{"externalId":"u1","email":"[email protected]"}}' | jq -r .id)
 
# o comprador declara o país; a resposta traz o orçamento que o clique confirma
Q=$(curl -s -X POST $API/pay/$SLUG/invoices/$INV/country \
  -H 'Content-Type: application/json' -d '{"buyerCountry":"BR","revision":0}' | jq .purchase)
 
curl -s -X POST $API/pay/$SLUG/invoices/$INV/charge -H 'Content-Type: application/json' \
  -d "$(jq -n --argjson q "$Q" '{method:"card", withdrawalWaiver:true,
        revision:$q.revision, quoteId:$q.quoteId, consentDigest:$q.consentDigest}')" \
  | jq .checkoutAction
# -> { "kind": "stripe_checkout_elements", "clientSecret": "cs_test_…", "publishableKey": "pk_test_…" }

O checkoutAction é o que o Payment Element da Stripe monta no navegador. Se você não vai montar o formulário, pare na fatura e mande o comprador para a página da Infi (url do checkout() ou link de pagamento). A loja precisa do cadastro enviado antes — em sandbox ele aprova na hora, veja testar no sandbox.

O `slug` vem do provisionamento

tenantSlug, no mesmo JSON que devolveu a chave.