Skip to main content

Biblioteca Python para integração com a API Nhonga.net

Project description

Nhonga API - Python Library

Biblioteca Python para integração com a API de pagamentos da Nhonga.net.

Instalação

pip install nhonga-api

Configuração

from nhonga_api import NhongaAPI

nhonga = NhongaAPI({
    "api_key": "SUA_CHAVE_API",
    "secret_key": "SUA_CHAVE_SECRETA",  # Opcional, necessária para webhooks
    "base_url": "https://nhonga.net/api/"  # Opcional, padrão já configurado
})

Uso

Criar Pagamento

from nhonga_api import NhongaAPI, NhongaError, Currency, Environment

try:
    payment = nhonga.create_payment({
        "amount": 1500,
        "context": "Pagamento do curso de programação",
        "callbackUrl": "https://seusite.com/webhook",
        "returnUrl": "https://seusite.com/obrigado",
        "currency": Currency.MZN,
        "enviroment": Environment.PRODUCTION
    })

    if payment["success"]:
        print("URL de redirecionamento:", payment["redirectUrl"])
        print("ID da transação:", payment["id"])
    else:
        print("Erro:", payment["error"])
        
except NhongaError as e:
    print("Erro da API Nhonga:", e)

Verificar Status do Pagamento

try:
    status = nhonga.get_payment_status({
        "id": "txn_123456789"
    })

    print("Status:", status["status"])
    print("Valor:", status["amount"])
    print("Método:", status["method"])
    print("Taxa:", status["tax"])
    
except NhongaError as e:
    print("Erro ao verificar status:", e)

Pagamento Direto Mobile

from nhonga_api import PaymentMethod

try:
    mobile_payment = nhonga.create_mobile_payment({
        "method": PaymentMethod.MPESA,
        "amount": 2500,
        "context": "Recarga de saldo",
        "useremail": "cliente@exemplo.com",
        "userwhatsApp": "841234567",
        "phone": "841416077"
    })

    if mobile_payment["success"]:
        print("ID da transação:", mobile_payment["id"])
    else:
        print("Erro:", mobile_payment["error"])
        
except NhongaError as e:
    print("Erro no pagamento mobile:", e)

Processamento de Webhooks

Com Flask

from flask import Flask, request, jsonify
from nhonga_api import NhongaAPI, NhongaError

app = Flask(__name__)
nhonga = NhongaAPI({"api_key": "SUA_CHAVE_API", "secret_key": "SUA_CHAVE_SECRETA"})

@app.route('/webhook', methods=['POST'])
def webhook():
    try:
        secret_key = request.headers.get('secretkey')
        payload = request.get_json()

        def processar_pagamento(webhook_data):
            print("Pagamento confirmado:", webhook_data["id"])
            print("Valor pago:", webhook_data["paid"])
            print("Valor recebido:", webhook_data["received"])
            print("Taxa:", webhook_data["fee"])
            
            # Processar o pagamento confirmado
            # Atualizar banco de dados, enviar email, etc.

        nhonga.process_webhook(payload, secret_key, processar_pagamento)
        return jsonify({"status": "success"}), 200
        
    except NhongaError as e:
        print("Webhook inválido:", e)
        return jsonify({"error": "Invalid webhook"}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)

Com FastAPI

from fastapi import FastAPI, Request, HTTPException, Header
from nhonga_api import NhongaAPI, NhongaError
from typing import Optional

app = FastAPI()
nhonga = NhongaAPI({"api_key": "SUA_CHAVE_API", "secret_key": "SUA_CHAVE_SECRETA"})

@app.post("/webhook")
async def webhook(request: Request, secretkey: Optional[str] = Header(None)):
    try:
        if not secretkey:
            raise HTTPException(status_code=400, detail="Missing secret key")
        
        payload = await request.json()

        def processar_pagamento(webhook_data):
            print("Pagamento confirmado:", webhook_data["id"])
            # Processar pagamento...

        nhonga.process_webhook(payload, secretkey, processar_pagamento)
        return {"status": "success"}
        
    except NhongaError as e:
        raise HTTPException(status_code=400, detail="Invalid webhook")

# Para executar: uvicorn main:app --host 0.0.0.0 --port 3000

Tipos e Enums

A biblioteca inclui tipos e enums para melhor experiência de desenvolvimento:

from nhonga_api import (
    PaymentStatus,
    PaymentMethod, 
    Currency,
    Environment,
    CreatePaymentRequest,
    PaymentStatusResponse,
    MobilePaymentRequest,
    WebhookPayload
)

# Enums disponíveis
PaymentStatus.PENDING     # "pending"
PaymentStatus.COMPLETED   # "completed"
PaymentStatus.CANCELLED   # "cancelled"

PaymentMethod.MPESA       # "mpesa"
PaymentMethod.EMOLA       # "emola"

Currency.MZN              # "MZN"
Currency.USD              # "USD"

Environment.PRODUCTION    # "prod"
Environment.DEVELOPMENT   # "dev"

Context Manager

Use context manager para gerenciamento automático de recursos:

with NhongaAPI({"api_key": "SUA_CHAVE_API"}) as nhonga:
    payment = nhonga.create_payment({
        "amount": 1000,
        "context": "Teste de pagamento",
        "enviroment": Environment.DEVELOPMENT
    })
    print("Pagamento criado:", payment["id"])

Tratamento de Erros

A biblioteca usa a classe NhongaError para erros específicos da API:

from nhonga_api import NhongaError

try:
    payment = nhonga.create_payment(payment_data)
except NhongaError as e:
    print("Erro da API Nhonga:", e.message)
    print("Código de status:", e.status_code)
except Exception as e:
    print("Erro inesperado:", e)

Ambiente de Desenvolvimento

Para testes, use Environment.DEVELOPMENT nas requisições de pagamento:

from nhonga_api import Environment

payment = nhonga.create_payment({
    "amount": 1000,
    "context": "Teste de pagamento",
    "enviroment": Environment.DEVELOPMENT  # Não gera cobrança real
})

Exemplos Completos

Veja o arquivo examples.py para exemplos completos de uso com Flask, FastAPI e outras funcionalidades.

Requisitos

  • Python 3.7+
  • requests >= 2.25.0
  • typing-extensions >= 4.0.0

Desenvolvimento

Para contribuir com o desenvolvimento:

# Clonar repositório
git clone https://github.com/nhonga/nhonga-python
cd nhonga-python

# Instalar dependências de desenvolvimento
pip install -e ".[dev]"

# Executar testes
pytest

# Verificar tipos
mypy nhonga_api

# Formatar código
black nhonga_api

Suporte

Para suporte técnico, entre em contato:

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

nhonga_api-1.0.0.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

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

nhonga_api-1.0.0-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: nhonga_api-1.0.0.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for nhonga_api-1.0.0.tar.gz
Algorithm Hash digest
SHA256 9d9067b4fcba9bc064cfcf09ab7cb7a5f56e0162459eccf9ee41a79f32cc021b
MD5 d296b16ffb0c6d5c644e2051bffd52d5
BLAKE2b-256 3dc218e41e2ddb160420f5bedbf2f6675d1129431d33a5770b0e877a0c667625

See more details on using hashes here.

File details

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

File metadata

  • Download URL: nhonga_api-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for nhonga_api-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0a69dde7c34349c65549f57b3bf7b2f32afb8f906abe67766088e9feb33853cf
MD5 1e26b461cf3262fa7ca18ecac77708f6
BLAKE2b-256 4bf40b4d23c248b36be76dc309f6d11370e13127570cf6f85ad1be20185291c7

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