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.

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.0.tar.gz (10.3 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.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: vitrin-0.2.0.tar.gz
  • Upload date:
  • Size: 10.3 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.0.tar.gz
Algorithm Hash digest
SHA256 2a2ecac1e8a621c3e141b5644259b2edfc72857089e67e9f8098ddef58175c92
MD5 17b24716f0cb3f2939192c6f0c0cd7c0
BLAKE2b-256 661e496777680d94c5a4b1ac701b1abdf6f5e3e9ff461ed4dc1b8694c204f3f6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: vitrin-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 12.4 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b65b3e1b7198b0f75592e5af2fc0b6dfee975bb946d982befb7bd0b47f92bf95
MD5 abefb3e2118a0fd75eb9cfe0ccade136
BLAKE2b-256 772110284c1ee3ce29016377942df6bb863609aa19588514ef14fd6a7f6be12d

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