Initial commit
Some checks failed
Deploy Beta (NATIVE) / deploy (push) Failing after 37s

This commit is contained in:
vickytechkey 2026-09-20 18:57:37 +05:30
commit 590f9c1999
28 changed files with 1205 additions and 0 deletions

View file

@ -0,0 +1,137 @@
name: Deploy Beta (NATIVE)
on:
push:
branches:
- beta
jobs:
deploy:
runs-on: ubuntu-latest
container:
image: node:22-alpine
steps:
- name: Install git
run: apk add --no-cache git
- name: Checkout Code
uses: https://github.com/actions/checkout@v4
- name: Generate CloudWatch and Nginx Configs Locally
run: |
mkdir -p tmp
cat << 'EOF' > tmp/amazon-cloudwatch-agent.json
{
"agent": { "metrics_collection_interval": 60, "run_as_user": "root" },
"metrics": {
"metrics_collected": {
"disk": { "measurement": ["used_percent"], "metrics_collection_interval": 60, "resources": ["/"] },
"mem": { "measurement": ["mem_used_percent"], "metrics_collection_interval": 60 }
}
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{ "file_path": "/home/ubuntu/smswhatsappservice/whatsapp_service.log", "log_group_name": "/smswhatsappservice/app", "log_stream_name": "{instance_id}", "retention_in_days": 30 },
{ "file_path": "/home/ubuntu/smswhatsappservice/logs/gunicorn-access.log", "log_group_name": "/smswhatsappservice/gunicorn-access", "log_stream_name": "{instance_id}", "retention_in_days": 30 },
{ "file_path": "/home/ubuntu/smswhatsappservice/logs/gunicorn-error.log", "log_group_name": "/smswhatsappservice/gunicorn-error", "log_stream_name": "{instance_id}", "retention_in_days": 30 }
]
}
}
}
}
EOF
cat << 'EOF' > tmp/nginx-proxy.conf
server {
server_name whatsapp.tradhox.com whatsapp.tipro.in;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/whatsapp.tradhox.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/whatsapp.tradhox.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
listen 80;
server_name whatsapp.tradhox.com whatsapp.tipro.in;
return 301 https://$host$request_uri;
}
EOF
- name: Package Application
run: |
tar -czf app.tar.gz --exclude=.git --exclude=venv --exclude=__pycache__ --exclude=db.sqlite3 --exclude=tmp .
- name: Deploy to Beta EC2
run: |
apk add --no-cache openssh-client aws-cli
mkdir -p ~/.ssh
echo "${{ secrets.BETA_EC2_SSH_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
# Copy app archive and configuration files
scp -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa app.tar.gz tmp/amazon-cloudwatch-agent.json tmp/nginx-proxy.conf whatsapp-service.service ${{ secrets.BETA_EC2_USERNAME }}@${{ secrets.BETA_EC2_HOST }}:/tmp/
# Execute deployment commands on remote server
ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa ${{ secrets.BETA_EC2_USERNAME }}@${{ secrets.BETA_EC2_HOST }} << 'EOF'
set -e
# ── 1. Install Host Dependencies ──────────────────────────────
sudo apt-get update
sudo apt-get install -y python3-pip python3-venv python3-dev default-libmysqlclient-dev pkg-config libpq-dev build-essential nginx
# ── 2. Extract codebase to target directory ───────────────────
sudo mkdir -p /home/ubuntu/smswhatsappservice
sudo chown -R ubuntu:ubuntu /home/ubuntu/smswhatsappservice
tar -xzf /tmp/app.tar.gz -C /home/ubuntu/smswhatsappservice
# ── 3. Set up python virtual environment & dependencies ────────
cd /home/ubuntu/smswhatsappservice
mkdir -p logs
python3 -m venv venv
./venv/bin/pip install --upgrade pip
./venv/bin/pip install -r requirements.txt
# ── 4. Configure environment variables ─────────────────────────
# Using the hardcoded DB parameters for now as in the project setup
echo "DEBUG=0" > .env
echo "ENVIRONMENT=beta" >> .env
echo "DB_USER=postgres" >> .env
echo "DB_PASSWORD=password" >> .env
echo "DB_HOST=16.113.106.152" >> .env
echo "DB_PORT=5432" >> .env
# ── 5. Run Database Migrations ─────────────────────────────────
./venv/bin/python manage.py migrate --noinput
# ── 6. Configure and restart Systemd service ───────────────────
sudo mv /tmp/whatsapp-service.service /etc/systemd/system/whatsapp-service.service
sudo systemctl daemon-reload
sudo systemctl enable whatsapp-service
sudo systemctl restart whatsapp-service
# ── 7. Configure CloudWatch Agent ──────────────────────────────
sudo mv /tmp/amazon-cloudwatch-agent.json /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config -m ec2 -s \
-c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
# ── 8. Configure Nginx Reverse Proxy ───────────────────────────
sudo mv /tmp/nginx-proxy.conf /etc/nginx/sites-available/smswhatsappservice
sudo ln -sf /etc/nginx/sites-available/smswhatsappservice /etc/nginx/sites-enabled/smswhatsappservice
sudo rm -f /etc/nginx/sites-enabled/default
sudo systemctl restart nginx
# ── 9. Cleanup tmp files ───────────────────────────────────────
rm -f /tmp/app.tar.gz
EOF

21
.gitignore vendored Normal file
View file

@ -0,0 +1,21 @@
# Environments
venv/
env/
ENV/
.env
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
# Django
db.sqlite3
whatsapp_service.log
*.log
# IDEs
.idea/
.vscode/
*.swp

11
CERD.TXT Normal file
View file

@ -0,0 +1,11 @@
widgetId: "36696e6d5046343033343830",
tokenAuth: "563180T1AlanJm6aa942b9P1",
curl --location --request POST
'https://control.msg91.com/api/v5/widget/verifyAccessToken'
--header 'Content-Type: application/json'
--data-raw '{
"authkey": "{Your MSG91 AuthKey}",
"access-token": "{jwt_token_from_otp_widget}"
}'

22
manage.py Executable file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'whatsapp_service_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

67
msg91_otp_docs.md Normal file
View file

@ -0,0 +1,67 @@
# MSG91 Send OTP API Documentation Summary
## Overview
MSG91 provides an OTP service that allows sending One-Time Passwords (OTPs) via SMS, WhatsApp, and Voice calls. Channel selection and fallback behavior are configured inside the OTP Template created in the MSG91 control panel.
---
## 1. Send OTP Endpoint
- **URL**: `https://control.msg91.com/api/v5/otp`
- **HTTP Method**: `POST`
---
## 2. Headers
| Header Name | Type | Required | Description |
|---|---|---|---|
| `authkey` | String | Yes | User authentication key (unique for every MSG91 user account). Can also be passed as query parameter. |
| `content-type` | String | Yes | `application/json` (when passing JSON payload for template parameters). |
---
## 3. Query Parameters
### Required Parameters
| Parameter | Type | Description |
|---|---|---|
| `template_id` | String | OTP Template ID generated in the MSG91 Dashboard (OTP section). Configures the message template and delivery channels (SMS, WhatsApp, Voice). |
| `mobile` | String | Recipient mobile number in international format with country code (e.g. `919876543210`). |
| `authkey` | String | User authentication key. |
### Optional Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| `otp` | String / Integer | Auto-generated | Custom OTP value to send. If omitted, MSG91 generates the OTP automatically. |
| `unicode` | Integer | `0` | Pass `1` for non-English SMS content, `0` for English. |
| `invisible` | Integer | `0` | Mobile App verification (1 = ON, 0 = OFF). Auto-verifies if mobile network is ON. |
| `otp_expiry` | Integer | `15` | OTP expiry in minutes (Min: 1 min, Max: 10080 mins / 7 days). |
| `otp_length` | Integer | `4` | Number of digits in generated OTP (Min: 4, Max: 9). |
| `realTimeResponse` | Integer | - | Pass `1` to receive real-time API response handling error codes via caching. |
---
## 4. Request Body Parameters (JSON)
- **Content-Type**: `application/json`
- Pass dynamic variables defined in your MSG91 OTP template as JSON key-value pairs.
- Variable names are **case-sensitive**.
**Example JSON Payload**:
```json
{
"Param1": "Value1",
"Param2": "Value2",
"company_name": "MyCompany"
}
```
---
## 5. WhatsApp & Multi-Channel OTP Setup
- **Template-Based Routing**: Delivery channels (SMS vs WhatsApp) are configured within the MSG91 Dashboard under the OTP Template (`template_id`).
- When creating or editing an OTP template in MSG91, you can set WhatsApp as the primary or secondary fallback channel.
- **Resend OTP API**:
- **Endpoint**: `GET https://control.msg91.com/api/v5/otp/retry`
- **Query Parameters**:
- `mobile`: Mobile number in international format.
- `authkey`: User authentication key.
- `retrytype`: Delivery type for resending OTP (`text` for SMS/WhatsApp text, `voice` for voice call; Default: `voice`).

264
msg91_whatsapp_bulk_docs.md Normal file
View file

@ -0,0 +1,264 @@
# MSG91 WhatsApp API Bulk Payloads
Common endpoint and header for all the payloads
* **API URL**: `https://api.msg91.com/api/v5/whatsapp/whatsapp-outbound-message/bulk/`
* **Method**: `POST`
* **Headers**:
* `Content-Type: application/json`
* `authkey: <authkey>`
## 1. Header Configurations
### Header with None
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "WhatsApp Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers>"
],
"components": {}
}
]
}
}
}
```
### Header with Text
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "WhatsApp Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers with country code>"
],
"components": {}
}
]
}
}
}
```
### Header with Image
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "WhatsApp Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers with country code>"
],
"components": {
"header_1": {
"type": "image",
"value": "<url of media>"
}
}
}
]
}
}
}
```
### Header with Video
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "WhatsApp Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers with country code>"
],
"components": {
"header_1": {
"type": "video",
"value": "<url of media>"
}
}
}
]
}
}
}
```
### Header with Document
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers with country code>"
],
"components": {
"header_1": {
"filename": "<filename>",
"type": "document",
"value": "<url of media>"
}
}
}
]
}
}
}
```
### Header with Location
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "Template Name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers>"
],
"components": {
"header_1_latitude": {
"type": "location",
"value": "<latitude>"
},
"header_1_longitude": {
"type": "location",
"value": "<longitude>"
},
"header_1_name": {
"type": "location",
"value": "<name>"
},
"header_1_address": {
"type": "location",
"value": "<address>"
},
"body_1": {
"type": "text",
"value": "value1"
}
}
}
]
}
}
}
```
## 2. Button Configurations
### Header with Button
1) Header (Text) - Variable
Body (Text) - Variable
CTA button (Visit Website) - Variable or click count enabled
```json
{
"integrated_number": "Your integrated Number",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "Your template name",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"<list_of_phone_numbers>"
],
"components": {
"header_1": {
"type": "text",
"value": "<{{1}}>"
},
"body_1": {
"type": "text",
"value": "value1"
},
"button_1": {
"subtype": "url",
"type": "text",
"value": "<{{url text variable}}>"
}
}
}
]
}
}
}
```
> **Note**: This file contains a partial representation of the MSG91 payloads for reference. Refer to the original documentation for Carousels, Catalogues, and Authentication templates.

5
requirements.txt Normal file
View file

@ -0,0 +1,5 @@
django>=4.0
djangorestframework
psycopg2-binary
requests
gunicorn

26
send_otp.py Normal file
View file

@ -0,0 +1,26 @@
import requests
import json
# Your credentials and details
authkey = "563180T1AlanJm6aa942b9P1" # Extracted from tokenAuth in CERD.TXT
mobile = "919600494039" # Mobile number with country code (assuming India 91)
template_id = "YOUR_TEMPLATE_ID" # You must replace this with your actual Template ID from MSG91 dashboard
url = f"https://control.msg91.com/api/v5/otp?template_id={template_id}&mobile={mobile}&authkey={authkey}"
payload = json.dumps({
# Add any custom variables defined in your template here
# "Param1": "value1",
# "company_name": "MyCompany"
})
headers = {
'Content-Type': 'application/json'
}
print(f"Sending OTP to {mobile}...")
response = requests.request("POST", url, headers=headers, data=payload)
print("Status Code:", response.status_code)
print("Response Body:", response.text)

59
send_whatsapp_bulk.py Normal file
View file

@ -0,0 +1,59 @@
import http.client
import os
import json
import sys
# Get mobile number from user input or command line argument
if len(sys.argv) > 1:
mobile_number = sys.argv[1]
else:
mobile_number = input("Enter the mobile number with country code (e.g., 919600494039): ").strip()
if not mobile_number:
print("Error: Mobile number is required!")
sys.exit(1)
# Get OTP code from user input or command line argument
if len(sys.argv) > 2:
otp_code = sys.argv[2]
else:
otp_code = input("Enter the OTP code (e.g., 123456): ").strip()
if not otp_code:
print("Error: OTP code is required!")
sys.exit(1)
conn = http.client.HTTPSConnection("control.msg91.com")
# Read the JSON payload from the template file
template_path = os.path.join(os.path.dirname(__file__), "template jsons", "mobile_number_verification.json")
with open(template_path, "r") as f:
payload_dict = json.load(f)
# Update the target mobile number dynamically
payload_dict["payload"]["template"]["to_and_components"][0]["to"] = [mobile_number]
# Update the OTP values dynamically
components = payload_dict["payload"]["template"]["to_and_components"][0]["components"]
if "body_1" in components:
components["body_1"]["value"] = otp_code
if "button_1" in components:
components["button_1"]["value"] = otp_code
# Convert the dictionary back to a JSON string
payload = json.dumps(payload_dict)
headers = {
'accept': "application/json",
'authkey': "563180AluxJHIeTGn6aaf97aeP1",
'content-type': "application/json"
}
print(f"Sending OTP {otp_code} to {mobile_number}...")
conn.request("POST", "/api/v5/whatsapp/whatsapp-outbound-message/bulk/", payload, headers)
res = conn.getresponse()
data = res.read()
print("Response:", data.decode("utf-8"))

33
success.json Normal file
View file

@ -0,0 +1,33 @@
{
"integrated_number": "918610694498",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "accountcreation",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
"919600494039"
],
"components": {
"body_1": {
"type": "text",
"value": "vignesh"
},
"body_2": {
"type": "text",
"value": "2268"
}
}
}
]
}
}
}

View file

@ -0,0 +1,34 @@
{
"integrated_number": "918610694498",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": "mobile_number_verification",
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": null,
"to_and_components": [
{
"to": [
""
],
"components": {
"body_1": {
"type": "text",
"value": ""
},
"button_1": {
"subtype": "url",
"type": "text",
"value": ""
}
}
}
]
}
}
}

17
whatsapp-service.service Normal file
View file

@ -0,0 +1,17 @@
[Unit]
Description=WhatsApp SMS Service Gunicorn Daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/smswhatsappservice
ExecStart=/home/ubuntu/smswhatsappservice/venv/bin/gunicorn \
--access-logfile /home/ubuntu/smswhatsappservice/logs/gunicorn-access.log \
--error-logfile /home/ubuntu/smswhatsappservice/logs/gunicorn-error.log \
--workers 3 \
--bind 127.0.0.1:8080 \
whatsapp_service_project.wsgi:application
[Install]
WantedBy=multi-user.target

0
whatsapp_api/__init__.py Normal file
View file

3
whatsapp_api/admin.py Normal file
View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
whatsapp_api/apps.py Normal file
View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class WhatsappApiConfig(AppConfig):
name = 'whatsapp_api'

View file

@ -0,0 +1,26 @@
# Generated by Django 6.1.1 on 2026-09-20 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='WhatsAppMessageLog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mobile_number', models.CharField(max_length=20)),
('template_name', models.CharField(max_length=255)),
('payload_sent', models.JSONField()),
('status', models.CharField(max_length=50)),
('api_response', models.JSONField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
]

View file

12
whatsapp_api/models.py Normal file
View file

@ -0,0 +1,12 @@
from django.db import models
class WhatsAppMessageLog(models.Model):
mobile_number = models.CharField(max_length=20)
template_name = models.CharField(max_length=255)
payload_sent = models.JSONField()
status = models.CharField(max_length=50)
api_response = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.mobile_number} - {self.template_name} - {self.status}"

View file

@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import WhatsAppMessageLog
class WhatsAppMessageLogSerializer(serializers.ModelSerializer):
class Meta:
model = WhatsAppMessageLog
fields = '__all__'

View file

@ -0,0 +1,97 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WhatsApp SMS Service</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<h2 class="text-center mb-4">WhatsApp SMS Service Dashboard</h2>
<div class="row">
<div class="col-md-5">
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary text-white">
<h5 class="mb-0">Send Message</h5>
</div>
<div class="card-body">
<form method="POST">
{% csrf_token %}
<div class="mb-3">
<label class="form-label">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" placeholder="e.g. 919600494039" required>
</div>
<div class="mb-3">
<label class="form-label">Template Name</label>
<input type="text" name="template_name" class="form-control" value="mobile_number_verification" required>
</div>
<div class="mb-3">
<label class="form-label">OTP / Variable Value</label>
<input type="text" name="otp_code" class="form-control" placeholder="123456" required>
</div>
<button type="submit" class="btn btn-primary w-100">Send WhatsApp Message</button>
</form>
</div>
</div>
<div class="card shadow-sm">
<div class="card-header bg-secondary text-white">
<h5 class="mb-0">API Usage (cURL)</h5>
</div>
<div class="card-body bg-dark text-white rounded-bottom">
<pre class="mb-0"><code>curl -X POST http://127.0.0.1:8000/api/send/ \
-H "Content-Type: application/json" \
-d '{
"mobile_number": "919600494039",
"otp_code": "123456",
"template_name": "mobile_number_verification"
}'</code></pre>
</div>
</div>
</div>
<div class="col-md-7">
<div class="card shadow-sm">
<div class="card-header bg-success text-white">
<h5 class="mb-0">Recent Message Logs</h5>
</div>
<div class="card-body p-0">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Time</th>
<th>Mobile Number</th>
<th>Template</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for log in logs %}
<tr>
<td>{{ log.created_at|date:"M d, H:i:s" }}</td>
<td>{{ log.mobile_number }}</td>
<td>{{ log.template_name }}</td>
<td>
{% if log.status == 'success' %}
<span class="badge bg-success">Success</span>
{% else %}
<span class="badge bg-danger">{{ log.status }}</span>
{% endif %}
</td>
</tr>
{% empty %}
<tr>
<td colspan="4" class="text-center py-4 text-muted">No messages sent yet.</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

3
whatsapp_api/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

7
whatsapp_api/urls.py Normal file
View file

@ -0,0 +1,7 @@
from django.urls import path
from .views import SendMessageAPI, home_view
urlpatterns = [
path('', home_view, name='home'),
path('api/send/', SendMessageAPI.as_view(), name='api-send'),
]

120
whatsapp_api/views.py Normal file
View file

@ -0,0 +1,120 @@
import http.client
import json
import os
import logging
from django.shortcuts import render, redirect
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import WhatsAppMessageLog
logger = logging.getLogger('whatsapp_api')
MSG91_AUTHKEY = "563180AluxJHIeTGn6aaf97aeP1"
MSG91_HOST = "control.msg91.com"
def send_msg91_whatsapp(mobile_number, otp_code, template_name="mobile_number_verification"):
# Build payload structure (using the known working mobile_number_verification template)
payload_dict = {
"integrated_number": "918610694498",
"content_type": "template",
"payload": {
"messaging_product": "whatsapp",
"type": "template",
"template": {
"name": template_name,
"language": {
"code": "en",
"policy": "deterministic"
},
"namespace": None,
"to_and_components": [
{
"to": [mobile_number],
"components": {
"body_1": {
"type": "text",
"value": otp_code
},
"button_1": {
"subtype": "url",
"type": "text",
"value": otp_code
}
}
}
]
}
}
}
payload = json.dumps(payload_dict)
headers = {
'accept': "application/json",
'authkey': MSG91_AUTHKEY,
'content-type': "application/json"
}
try:
logger.info(f"Sending WhatsApp message to {mobile_number} using template '{template_name}'")
conn = http.client.HTTPSConnection(MSG91_HOST)
conn.request("POST", "/api/v5/whatsapp/whatsapp-outbound-message/bulk/", payload, headers)
res = conn.getresponse()
data = res.read()
response_json = json.loads(data.decode("utf-8"))
logger.info(f"MSG91 Response for {mobile_number}: {response_json}")
# Log to DB
WhatsAppMessageLog.objects.create(
mobile_number=mobile_number,
template_name=template_name,
payload_sent=payload_dict,
status=response_json.get('status', 'unknown'),
api_response=response_json
)
return response_json
except Exception as e:
logger.error(f"Error sending WhatsApp message to {mobile_number}: {e}", exc_info=True)
WhatsAppMessageLog.objects.create(
mobile_number=mobile_number,
template_name=template_name,
payload_sent=payload_dict,
status="error",
api_response={"error": str(e)}
)
return {"status": "error", "message": str(e)}
class SendMessageAPI(APIView):
authentication_classes = []
permission_classes = []
def post(self, request):
mobile_number = request.data.get('mobile_number')
otp_code = request.data.get('otp_code')
template_name = request.data.get('template_name', 'mobile_number_verification')
if not mobile_number or not otp_code:
return Response({"error": "mobile_number and otp_code are required"}, status=status.HTTP_400_BAD_REQUEST)
result = send_msg91_whatsapp(mobile_number, otp_code, template_name)
if result.get('status') == 'success':
return Response(result, status=status.HTTP_200_OK)
return Response(result, status=status.HTTP_400_BAD_REQUEST)
def home_view(request):
if request.method == "POST":
mobile_number = request.POST.get('mobile_number')
otp_code = request.POST.get('otp_code')
template_name = request.POST.get('template_name', 'mobile_number_verification')
if mobile_number and otp_code:
send_msg91_whatsapp(mobile_number, otp_code, template_name)
return redirect('home')
logs = WhatsAppMessageLog.objects.all().order_by('-created_at')[:10]
return render(request, 'whatsapp_api/index.html', {'logs': logs})

View file

View file

@ -0,0 +1,16 @@
"""
ASGI config for whatsapp_service_project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'whatsapp_service_project.settings')
application = get_asgi_application()

View file

@ -0,0 +1,174 @@
"""
Django settings for whatsapp_service_project project.
Generated by 'django-admin startproject' using Django 6.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-t90ex8^f#*1t!g!8tiqt&q#_l!%37^mjq7az^q3*$l3%iudanp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'whatsapp_api',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'whatsapp_service_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'whatsapp_service_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'whatsmsservice',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': '16.113.106.152',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/6.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.1/howto/static-files/
STATIC_URL = 'static/'
# Email
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration
MAILERS = {
'default': {
'BACKEND': 'django.core.mail.backends.console.EmailBackend',
},
}
import os
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'whatsapp_service.log'),
'formatter': 'verbose',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'loggers': {
'django': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': True,
},
'whatsapp_api': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': True,
},
},
}

View file

@ -0,0 +1,23 @@
"""
URL configuration for whatsapp_service_project project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/6.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('whatsapp_api.urls')),
]

View file

@ -0,0 +1,16 @@
"""
WSGI config for whatsapp_service_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'whatsapp_service_project.settings')
application = get_wsgi_application()