Skip to main content

No project description provided

Project description

django-whatsapp-api-wrapper

Um wrapper simples para enviar mensagens via WhatsApp Cloud API e expor um endpoint de webhook, pronto para integrar em qualquer projeto Django.

Instalação

python -m pip install django-whatsapp-api-wrapper

Configuração (Django)

  1. Adicione o app em INSTALLED_APPS:
INSTALLED_APPS = [
    # ...
    "django_whatsapp_api_wrapper",
]
  1. Inclua as URLs no urls.py principal:
from django.urls import path, include

urlpatterns = [
    # ...
    path("whatsapp-api-wrapper/", include("django_whatsapp_api_wrapper.urls")),
]
  1. Defina as variáveis de ambiente (ou no seu .env):
WHATSAPP_CLOUD_API_TOKEN=
WHATSAPP_CLOUD_API_PACKAGE_VERSION=0.1.1
WHATSAPP_CLOUD_API_VERSION=v23.0
WHATSAPP_CLOUD_API_PHONE_NUMBER_ID=
WHATSAPP_CLOUD_API_WABA_ID=
WHATSAPP_CLOUD_API_VERIFY_TOKEN=
  1. Configure a autenticação para as rotas de templates (opcional, mas recomendado):
# settings.py

# Opção 1: Usar Token Authentication do DRF (padrão)
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'rest_framework.authentication.TokenAuthentication',
]

# Opção 2: Usar JWT (se você já tem configurado)
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'rest_framework_simplejwt.authentication.JWTAuthentication',
]

# Opção 3: Usar API Key simples
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'django_whatsapp_api_wrapper.authentication.APIKeyAuthentication',
]
WHATSAPP_API_KEY = "sua_api_key_secreta_aqui"

# Permissões (padrão: IsAuthenticated)
WHATSAPP_API_PERMISSION_CLASSES = [
    'rest_framework.permissions.IsAuthenticated',
]

Importante: Se não configurar a autenticação, as rotas de templates usarão TokenAuthentication por padrão.

O endpoint de webhook ficará disponível em:

  • GET/POST: /whatsapp-api-wrapper/webhook/
  • Verificação (GET): /whatsapp-api-wrapper/webhook/?hub.mode=subscribe&hub.verify_token=<TOKEN>&hub.challenge=123

Extensibilidade do Webhook

Você pode customizar o processamento do webhook no projeto hospedeiro de duas formas:

  • Via setting com handler plugável:
# settings.py
WHATSAPP_WEBHOOK_HANDLER = "meuapp.whatsapp.handle_webhook"
# meuapp/whatsapp.py
from django.http import JsonResponse

def handle_webhook(request, payload):
    # sua lógica aqui (salvar eventos, acionar tasks, etc)
    return JsonResponse({"ok": True})
  • Via signal webhook_event_received:
from django.dispatch import receiver
from django_whatsapp_api_wrapper.signals import webhook_event_received

@receiver(webhook_event_received)
def on_whatsapp_event(sender, payload, request, **kwargs):
    # sua lógica aqui
    pass

Mensagens

Envio e recebimento de mensagens via Cloud API.

Envio (Python)

from django_whatsapp_api_wrapper import WhatsApp

wp = WhatsApp()

# Template
language = {"code": "pt_BR"}
template = {"name": "opa", "language": language}
m = wp.build_message(to="551199999999", type="template", data=template)
m.send()

# Texto
data = {"preview_url": False, "body": "olá do wrapper"}
m2 = wp.build_message(to="551199999999", type="text", data=data)
m2.send()

Webhook

  • Recebe eventos (mensagens/atualizações de status) em GET/POST /whatsapp-api-wrapper/webhook/.
  • Verificação (GET): /whatsapp-api-wrapper/webhook/?hub.mode=subscribe&hub.verify_token=<TOKEN>&hub.challenge=123.
  • Personalize via setting WHATSAPP_WEBHOOK_HANDLER ou escute o signal webhook_event_received (veja seção Extensibilidade do Webhook acima).

Autenticação

Proteção das Rotas de Templates

Por padrão, todas as rotas de templates (/templates/) são protegidas e requerem autenticação. O webhook permanece público (necessário para o WhatsApp).

Opções de Autenticação

1. Token Authentication (Padrão)

# settings.py
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'rest_framework.authentication.TokenAuthentication',
]

Uso:

curl -H "Authorization: Token seu_token_aqui" \
     "$BASE/whatsapp-api-wrapper/templates/"

2. JWT Authentication

# settings.py
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'rest_framework_simplejwt.authentication.JWTAuthentication',
]

Uso:

curl -H "Authorization: Bearer seu_jwt_token" \
     "$BASE/whatsapp-api-wrapper/templates/"

3. API Key Authentication

# settings.py
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'django_whatsapp_api_wrapper.authentication.APIKeyAuthentication',
]
WHATSAPP_API_KEY = "sua_api_key_secreta"

Uso:

curl -H "X-WhatsApp-API-Key: sua_api_key_secreta" \
     "$BASE/whatsapp-api-wrapper/templates/"

4. Múltiplas Autenticações

# settings.py
WHATSAPP_API_AUTHENTICATION_CLASSES = [
    'rest_framework.authentication.TokenAuthentication',
    'django_whatsapp_api_wrapper.authentication.APIKeyAuthentication',
]

Permissões Customizadas

# settings.py
WHATSAPP_API_PERMISSION_CLASSES = [
    'rest_framework.permissions.IsAuthenticated',
    # ou 'rest_framework.permissions.IsAdminUser',
    # ou 'myapp.permissions.CustomPermission',
]

Templates

Endpoints REST (DRF) para gerenciar Message Templates do WhatsApp (proxy para Graph API). Todos os endpoints abaixo partem do prefixo que você incluir no projeto, por exemplo: .../whatsapp-api-wrapper/.

⚠️ Importante: Todos os endpoints de templates requerem autenticação (veja seção Autenticação acima).

Requisitos de ambiente: WHATSAPP_CLOUD_API_TOKEN, WHATSAPP_CLOUD_API_VERSION, WHATSAPP_CLOUD_API_WABA_ID.

Aqui a documentação OFICIAL:

https://www.postman.com/meta/whatsapp-business-platform/folder/2ksdd2s/whatsapp-cloud-api

Listar e criar

  • GET GET /templates/?limit=&after=&before=
  • POST POST /templates/ com payload conforme a Graph API.

Exemplo de criação:

curl -X POST \
  "$BASE/whatsapp-api-wrapper/templates/" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "authentication_code_copy_code_button",
    "language": "en_US",
    "category": "AUTHENTICATION",
    "components": [
      {"type": "BODY", "add_security_recommendation": true},
      {"type": "FOOTER", "code_expiration_minutes": 10},
      {"type": "BUTTONS", "buttons": [{"type": "OTP", "otp_type": "COPY_CODE", "text": "Copy Code"}]}
    ]
  }'

Buscar por ID e editar

  • GET GET /templates/<template_id>/
  • POST POST /templates/<template_id>/ para editar (mesmo formato do corpo de criação).

Buscar e excluir por nome

  • GET GET /templates/by-name/?name=<TEMPLATE_NAME>
  • DELETE DELETE /templates/by-name/?name=<TEMPLATE_NAME>

Excluir por ID (hsm_id) e nome

  • DELETE DELETE /templates/delete-by-id/?hsm_id=<HSM_ID>&name=<NAME>

Obter namespace

  • GET GET /templates/namespace/

Notas:

  • Os payloads aceitos seguem a documentação oficial de Message Templates da Meta (Graph API). Este wrapper só valida campos básicos e encaminha a requisição.
  • As respostas retornadas são as mesmas da Graph API (status code e corpo JSON), para facilitar troubleshooting.

Notas

  • Nome do pacote no PyPI: django-whatsapp-api-wrapper
  • Nome do módulo/import: django_whatsapp_api_wrapper

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

django_whatsapp_api_wrapper-0.3.0.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

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

django_whatsapp_api_wrapper-0.3.0-py3-none-any.whl (15.6 kB view details)

Uploaded Python 3

File details

Details for the file django_whatsapp_api_wrapper-0.3.0.tar.gz.

File metadata

File hashes

Hashes for django_whatsapp_api_wrapper-0.3.0.tar.gz
Algorithm Hash digest
SHA256 0feb0f8526d901ca19a237718f642943b546f34c9d1a670d138e9b1ee72eaace
MD5 03e8bac431564399b33f593afaf8e3e8
BLAKE2b-256 0836799576edde86b4043ffafeaeacb2d15824a24d6a99c6d29feb8732a15e36

See more details on using hashes here.

File details

Details for the file django_whatsapp_api_wrapper-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_whatsapp_api_wrapper-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 68225da0dda6a93008c85d20ab3f09e17a9970816bdea71a1a6984bec21a88dd
MD5 f984824f9973806a00e3e3a3b6124b89
BLAKE2b-256 8bda2c9ce84bb86b51a94b4bfea0cda92dbad8e2758ef97f052ad7775bb2aa1a

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