Skip to main content

SDK oficial Python para a API da Vitrin Digital

Project description

vitrin (Python)

SDK oficial Python para a API da Vitrin Digital.

pip install vitrin

Python 3.10+ requerido. Única dependência runtime: requests.

Setup

import os
from vitrin import Vitrin

vitrin = Vitrin(
    api_key=os.environ["VITRIN_API_KEY"],
    # opcionais:
    # base_url="https://api.vitrin.digital/api/v1",
    # timeout=30.0,
    # max_retries=3,
)

Use vd_test_* em desenvolvimento, vd_live_* em produção.

Organizações LLC (US)

Se a org é uma US LLC (entity_type == "llc"), os valores são em USD (campo currency nas transações); os métodos default são cartão e Pix cross-border (o cliente paga em BRL, a LLC recebe em USD). A liquidação é automática: os endpoints de saldo/recebíveis/transferências retornam { "auto_payout": true } em vez de saldo retido (não há saque/antecipação manual; o cronograma "PIX D+1 / Boleto D+2 / Cartão Nx D+30" abaixo é só para CNPJ). O onboarding inclui verificação de identidade (KYC). Veja docs/api/onboarding-llc.md e docs/api/differences-cnpj-llc.md.

Recursos

Clientes

customer = vitrin.customers.create(
    name="Maria Silva",
    email="maria@example.com",
    cpf_cnpj="12345678901",
)

vitrin.customers.list(page=1)
vitrin.customers.update(customer["id"], phone="11987654321")
vitrin.customers.delete(customer["id"])

Cobranças

charge = vitrin.charges.create(
    customer_id=customer["id"],
    amount=99.90,
    billing_type="PIX",
    description="Mensalidade abril",
    idempotency_key=f"mensalidade-{customer['id']}-2026-04",  # evita duplo-débito em retry
)

print(charge["pix_qr_code"])
print(charge["pix_copy_paste"])

# Reembolso parcial
vitrin.charges.refund(charge["id"], amount=50.0, pin="123456")

Planos & Assinaturas

plan = vitrin.plans.create(name="Pro Mensal", price=99.0, billing_cycle="monthly")

sub = vitrin.subscriptions.create(
    customer_id=customer["id"],
    plan_id=plan["id"],
    billing_type="CREDIT_CARD",
    credit_card_token="tok_xxx",
)

vitrin.subscriptions.cancel(sub["id"], pin="123456")

Saldo & Recebíveis

vitrin.balance.retrieve()
# → { "available": ..., "total": ..., "pending": ..., "withdrawal_fees": {...} }

vitrin.balance.scheduled(90)
# → cronograma 90d: PIX D+1, Boleto D+2, Cartão Nx D+30·n

Webhooks

from flask import Flask, request, abort
from vitrin import webhooks, VitrinError
import os

app = Flask(__name__)

@app.post("/webhooks/vitrin")
def handle_webhook():
    try:
        event = webhooks.construct_event(
            payload=request.get_data(),                          # body cru, NÃO parsed
            signature=request.headers.get("X-Vitrin-Signature"),
            timestamp=request.headers.get("X-Vitrin-Timestamp"),
            event_type=request.headers.get("X-Vitrin-Event"),
            event_id=request.headers.get("X-Vitrin-Event-Id"),
            secret=os.environ["VITRIN_WEBHOOK_SECRET"],
        )
        print(event.type, event.id, event.data)
        return "", 200
    except VitrinError as e:
        return str(e), 400

Tratamento de erros

from vitrin import (
    VitrinError, VitrinAuthError, VitrinValidationError,
    VitrinRateLimitError, VitrinNotFoundError, VitrinServerError,
)

try:
    vitrin.charges.create(...)
except VitrinValidationError as e:
    print("Campos inválidos:", e.field_errors)
except VitrinAuthError:
    print("Chave inválida ou sem permissão")
except VitrinRateLimitError:
    print("Aguarde antes de tentar de novo")
except VitrinError as e:
    print(f"Erro Vitrin: {e.status_code} {e.request_id} {e.message}")

Retry automático em 429 e 5xx com backoff exponencial (default: 3 tentativas). 4xx (exceto 429) não são retentados.

Idempotência

Inclua idempotency_key em POSTs sensíveis. Se o request chegar duas vezes (retry de rede, deploy etc), a Vitrin reconhece pela chave e devolve a mesma resposta — sem cobrar duas vezes.

vitrin.charges.create(
    customer_id="cus_1",
    amount=100,
    billing_type="PIX",
    idempotency_key=f"pedido-{order_id}",  # único por pedido
)

Acesso bruto

data = vitrin.request("/some/path/", method="POST", body={"foo": "bar"})

Licença

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

vitrin-0.2.1.tar.gz (10.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

vitrin-0.2.1-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

Details for the file vitrin-0.2.1.tar.gz.

File metadata

  • Download URL: vitrin-0.2.1.tar.gz
  • Upload date:
  • Size: 10.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for vitrin-0.2.1.tar.gz
Algorithm Hash digest
SHA256 437cd168c27534c2a7bc16bc49a237c5ad62574c55f66a1f10996d38f2a815bb
MD5 20083e9c9e7020a81621770ff62d15a4
BLAKE2b-256 ef30ed23edceb8baebb0cb202d8e06d69f76c776f398950cb36b949c7cf8b526

See more details on using hashes here.

File details

Details for the file vitrin-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: vitrin-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 12.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for vitrin-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a61c7f228050f7f037f460d7564ad385ab7e420969dab6894b4c0ed29f09eeed
MD5 3d1da405c9c2c708cac759ce93df921c
BLAKE2b-256 a79ef21adcdc015f723bf95807cbc92292cfd964a8dce48bb81d004102674350

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page