Skip to main content

SDK oficial da NXGATE para integração com a API PIX

Project description

NXGATE PIX SDK para Python

SDK oficial da NXGATE para integração com a API PIX. Permite gerar cobranças (cash-in), realizar saques (cash-out), consultar saldo e transações, tudo com tipagem completa e zero dependências externas.

Requisitos

  • Python 3.10 ou superior
  • Sem dependências externas (usa apenas a biblioteca padrão)

Instalação

pip install nxgate

Ou instale diretamente do repositório:

pip install git+https://github.com/nxgate/sdk-python.git

Início Rápido

from nxgate import NXGate, NXGateWebhook

nx = NXGate(
    client_id="nxgate_xxx",
    client_secret="secret",
    hmac_secret="opcional",  # opcional - quando informado, todas as requisições são assinadas com HMAC-SHA256
)

Funcionalidades

Gerar cobrança PIX (Cash-in)

Gera uma cobrança PIX e retorna o QR Code para pagamento.

charge = nx.pix_generate(
    valor=100.00,
    nome_pagador="João da Silva",
    documento_pagador="12345678901",
    webhook="https://meusite.com/webhook",
    descricao="Pedido #1234",
    email_pagador="joao@email.com",
    celular="11999999999",
)

print(charge.status)            # "ACTIVE"
print(charge.paymentCode)       # código copia-e-cola
print(charge.idTransaction)     # ID da transação
print(charge.paymentCodeBase64) # QR Code em base64

Cobrança com split de pagamento

charge = nx.pix_generate(
    valor=200.00,
    nome_pagador="Maria Souza",
    documento_pagador="98765432100",
    split_users=[
        {"username": "loja_a", "percentage": 70.0},
        {"username": "loja_b", "percentage": 30.0},
    ],
)

Saque PIX (Cash-out)

Realiza uma transferência PIX para uma chave destino.

withdrawal = nx.pix_withdraw(
    valor=50.00,
    chave_pix="joao@email.com",
    tipo_chave="EMAIL",  # CPF | CNPJ | PHONE | EMAIL | RANDOM
    webhook="https://meusite.com/webhook",
)

print(withdrawal.status)            # "PROCESSING"
print(withdrawal.internalreference) # referência interna

Consultar saldo

balance = nx.get_balance()

print(balance.balance)   # saldo total
print(balance.blocked)   # saldo bloqueado
print(balance.available) # saldo disponível

Consultar transação

tx = nx.get_transaction(type="cash-in", txid="px_xxx")

print(tx.idTransaction) # ID da transação
print(tx.status)        # status atual
print(tx.amount)        # valor
print(tx.paidAt)        # data do pagamento
print(tx.endToEnd)      # identificador end-to-end

Webhooks

O SDK fornece um parser para eventos recebidos via webhook.

Recebendo eventos (exemplo com Flask)

from flask import Flask, request, jsonify
from nxgate import NXGateWebhook, NXGateError
from nxgate.types import CashInEvent, CashOutEvent

app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def webhook():
    try:
        event = NXGateWebhook.parse(request.json)
    except NXGateError as e:
        return jsonify({"error": str(e)}), 400

    if isinstance(event, CashInEvent):
        print(f"Cash-in: {event.type}")
        print(f"  Valor: R$ {event.data.amount:.2f}")
        print(f"  Pagador: {event.data.debtor_name}")
        print(f"  TX ID: {event.data.tx_id}")
        print(f"  Status: {event.data.status}")

    elif isinstance(event, CashOutEvent):
        print(f"Cash-out: {event.type}")
        print(f"  Valor: R$ {event.amount:.2f}")
        print(f"  Chave: {event.key}")
        if event.error:
            print(f"  Erro: {event.error}")

    return jsonify({"ok": True})

Tipos de evento

Cash-in:

  • QR_CODE_COPY_AND_PASTE_PAID - pagamento confirmado
  • QR_CODE_COPY_AND_PASTE_REFUNDED - pagamento devolvido

Cash-out:

  • PIX_CASHOUT_SUCCESS - saque realizado com sucesso
  • PIX_CASHOUT_ERROR - erro no saque
  • PIX_CASHOUT_REFUNDED - saque devolvido

Assinatura HMAC

Quando o parâmetro hmac_secret é informado na inicialização do cliente, todas as requisições são automaticamente assinadas com HMAC-SHA256. Os seguintes headers são adicionados:

Header Descrição
X-Client-ID Seu client_id
X-HMAC-Signature Assinatura HMAC-SHA256 em base64
X-HMAC-Timestamp Timestamp ISO 8601
X-HMAC-Nonce Valor único por requisição

A assinatura é gerada sobre a string canônica:

METHOD\nPATH\nTIMESTAMP\nNONCE\nBODY

Gerenciamento de Token

O SDK gerencia automaticamente o token OAuth2:

  • O token é obtido na primeira requisição
  • É mantido em cache enquanto válido
  • É renovado automaticamente 60 segundos antes de expirar
  • Em caso de falha na autenticação, NXGateAuthError é lançado

Tratamento de Erros

from nxgate import NXGate, NXGateError
from nxgate.errors import NXGateAuthError, NXGateTimeoutError, NXGateRetryError

nx = NXGate(client_id="xxx", client_secret="yyy")

try:
    charge = nx.pix_generate(
        valor=100.00,
        nome_pagador="Teste",
        documento_pagador="00000000000",
    )
except NXGateAuthError as e:
    print(f"Erro de autenticação: {e}")
    print(f"Status HTTP: {e.status_code}")
except NXGateTimeoutError as e:
    print(f"Timeout: {e}")
except NXGateRetryError as e:
    print(f"Todas as tentativas falharam: {e}")
except NXGateError as e:
    print(f"Erro da API: {e}")
    print(f"Título: {e.title}")
    print(f"Código: {e.code}")
    print(f"Descrição: {e.description}")
    print(f"Status HTTP: {e.status_code}")

Hierarquia de exceções

Exception
└── NXGateError
    ├── NXGateAuthError      # falha na autenticação
    ├── NXGateTimeoutError   # timeout na requisição
    └── NXGateRetryError     # tentativas esgotadas (503)

Retry Automático

Requisições que retornam HTTP 503 são automaticamente retentadas com backoff exponencial:

  • Máximo de 2 retentativas (3 tentativas no total)
  • Delay entre tentativas: 1s, 2s
  • Se todas as tentativas falharem, NXGateRetryError é lançado

Referência da API

NXGate(client_id, client_secret, hmac_secret=None, *, base_url, timeout)

Parâmetro Tipo Obrigatório Descrição
client_id str Sim Seu client_id NXGATE
client_secret str Sim Seu client_secret NXGATE
hmac_secret str | None Não Secret para assinatura HMAC
base_url str Não URL base da API (padrão: https://api.nxgate.com.br)
timeout int Não Timeout em segundos (padrão: 30)

Métodos

Método Retorno Descrição
pix_generate(...) PixGenerateResponse Gera cobrança PIX
pix_withdraw(...) PixWithdrawResponse Realiza saque PIX
get_balance() BalanceResponse Consulta saldo
get_transaction(type, txid) TransactionResponse Consulta transação

Desenvolvimento

Executar testes

pip install pytest
pytest

Estrutura do projeto

nxgate/
├── __init__.py      # exports públicos
├── client.py        # classe NXGate
├── auth.py          # gerenciamento de token
├── hmac_signer.py   # assinatura HMAC
├── webhook.py       # parser de webhook
├── errors.py        # exceções
└── types.py         # dataclasses tipadas

Licença

MIT - veja o arquivo LICENSE para detalhes.

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

nxgate_sdk_python-1.0.0.tar.gz (19.0 kB view details)

Uploaded Source

Built Distribution

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

nxgate_sdk_python-1.0.0-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file nxgate_sdk_python-1.0.0.tar.gz.

File metadata

  • Download URL: nxgate_sdk_python-1.0.0.tar.gz
  • Upload date:
  • Size: 19.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for nxgate_sdk_python-1.0.0.tar.gz
Algorithm Hash digest
SHA256 c57154d3769eb3308b6e99512ab50a47a6d1734e0092668cadf103643f945274
MD5 e6699a6e6d32d32f14be390170f94a65
BLAKE2b-256 cd0c18cefc2896d07654bc5657ca830a36640e751254eb72b11f5fd4d2bb5c04

See more details on using hashes here.

Provenance

The following attestation bundles were made for nxgate_sdk_python-1.0.0.tar.gz:

Publisher: publish.yml on nxgate/nxgate-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file nxgate_sdk_python-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for nxgate_sdk_python-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9562eebc92328fb3b7ae804581baedd3f7a622ba4908a0dc61d561c54bc7fd8c
MD5 40b33d7a92992b6bc3bb29feefd78465
BLAKE2b-256 c807656ba893880f51b9396771a63b079c39a2b3f18afed6ae3e220026f2054d

See more details on using hashes here.

Provenance

The following attestation bundles were made for nxgate_sdk_python-1.0.0-py3-none-any.whl:

Publisher: publish.yml on nxgate/nxgate-sdk-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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