commit 590f9c1999aa236a6b4a2adca7b9dde97f88a687 Author: vickytechkey Date: Sun Sep 20 18:57:37 2026 +0530 Initial commit diff --git a/.forgejo/workflows/deploy-beta.yml b/.forgejo/workflows/deploy-beta.yml new file mode 100644 index 0000000..1d38242 --- /dev/null +++ b/.forgejo/workflows/deploy-beta.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9419a82 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CERD.TXT b/CERD.TXT new file mode 100644 index 0000000..8db9771 --- /dev/null +++ b/CERD.TXT @@ -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}" +}' \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..b13bc8b --- /dev/null +++ b/manage.py @@ -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() diff --git a/msg91_otp_docs.md b/msg91_otp_docs.md new file mode 100644 index 0000000..55cf75b --- /dev/null +++ b/msg91_otp_docs.md @@ -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`). diff --git a/msg91_whatsapp_bulk_docs.md b/msg91_whatsapp_bulk_docs.md new file mode 100644 index 0000000..7ff5b34 --- /dev/null +++ b/msg91_whatsapp_bulk_docs.md @@ -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: ` + +## 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": [ + "" + ], + "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": [ + "" + ], + "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": [ + "" + ], + "components": { + "header_1": { + "type": "image", + "value": "" + } + } + } + ] + } + } +} +``` + +### 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": [ + "" + ], + "components": { + "header_1": { + "type": "video", + "value": "" + } + } + } + ] + } + } +} +``` + +### 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": [ + "" + ], + "components": { + "header_1": { + "filename": "", + "type": "document", + "value": "" + } + } + } + ] + } + } +} +``` + +### 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": [ + "" + ], + "components": { + "header_1_latitude": { + "type": "location", + "value": "" + }, + "header_1_longitude": { + "type": "location", + "value": "" + }, + "header_1_name": { + "type": "location", + "value": "" + }, + "header_1_address": { + "type": "location", + "value": "
" + }, + "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": [ + "" + ], + "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. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bcb0ace --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +django>=4.0 +djangorestframework +psycopg2-binary +requests +gunicorn diff --git a/send_otp.py b/send_otp.py new file mode 100644 index 0000000..f4a3c18 --- /dev/null +++ b/send_otp.py @@ -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) diff --git a/send_whatsapp_bulk.py b/send_whatsapp_bulk.py new file mode 100644 index 0000000..d3a8911 --- /dev/null +++ b/send_whatsapp_bulk.py @@ -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")) \ No newline at end of file diff --git a/success.json b/success.json new file mode 100644 index 0000000..28e6f2d --- /dev/null +++ b/success.json @@ -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" + } + } + } + ] + } + } +} \ No newline at end of file diff --git a/template jsons/mobile_number_verification.json b/template jsons/mobile_number_verification.json new file mode 100644 index 0000000..7a08a2c --- /dev/null +++ b/template jsons/mobile_number_verification.json @@ -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": "" + } + } + } + ] + } + } +} diff --git a/whatsapp-service.service b/whatsapp-service.service new file mode 100644 index 0000000..ad67ece --- /dev/null +++ b/whatsapp-service.service @@ -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 diff --git a/whatsapp_api/__init__.py b/whatsapp_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/whatsapp_api/admin.py b/whatsapp_api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/whatsapp_api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/whatsapp_api/apps.py b/whatsapp_api/apps.py new file mode 100644 index 0000000..79e8583 --- /dev/null +++ b/whatsapp_api/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class WhatsappApiConfig(AppConfig): + name = 'whatsapp_api' diff --git a/whatsapp_api/migrations/0001_initial.py b/whatsapp_api/migrations/0001_initial.py new file mode 100644 index 0000000..efff0dd --- /dev/null +++ b/whatsapp_api/migrations/0001_initial.py @@ -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)), + ], + ), + ] diff --git a/whatsapp_api/migrations/__init__.py b/whatsapp_api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/whatsapp_api/models.py b/whatsapp_api/models.py new file mode 100644 index 0000000..06b0987 --- /dev/null +++ b/whatsapp_api/models.py @@ -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}" diff --git a/whatsapp_api/serializers.py b/whatsapp_api/serializers.py new file mode 100644 index 0000000..ca97f5a --- /dev/null +++ b/whatsapp_api/serializers.py @@ -0,0 +1,7 @@ +from rest_framework import serializers +from .models import WhatsAppMessageLog + +class WhatsAppMessageLogSerializer(serializers.ModelSerializer): + class Meta: + model = WhatsAppMessageLog + fields = '__all__' diff --git a/whatsapp_api/templates/whatsapp_api/index.html b/whatsapp_api/templates/whatsapp_api/index.html new file mode 100644 index 0000000..b044fca --- /dev/null +++ b/whatsapp_api/templates/whatsapp_api/index.html @@ -0,0 +1,97 @@ + + + + + + WhatsApp SMS Service + + + +
+

WhatsApp SMS Service Dashboard

+ +
+
+
+
+
Send Message
+
+
+
+ {% csrf_token %} +
+ + +
+
+ + +
+
+ + +
+ +
+
+
+ +
+
+
API Usage (cURL)
+
+
+
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"
+}'
+
+
+
+ +
+
+
+
Recent Message Logs
+
+
+ + + + + + + + + + + {% for log in logs %} + + + + + + + {% empty %} + + + + {% endfor %} + +
TimeMobile NumberTemplateStatus
{{ log.created_at|date:"M d, H:i:s" }}{{ log.mobile_number }}{{ log.template_name }} + {% if log.status == 'success' %} + Success + {% else %} + {{ log.status }} + {% endif %} +
No messages sent yet.
+
+
+
+
+
+ + diff --git a/whatsapp_api/tests.py b/whatsapp_api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/whatsapp_api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/whatsapp_api/urls.py b/whatsapp_api/urls.py new file mode 100644 index 0000000..303dee6 --- /dev/null +++ b/whatsapp_api/urls.py @@ -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'), +] diff --git a/whatsapp_api/views.py b/whatsapp_api/views.py new file mode 100644 index 0000000..7f32164 --- /dev/null +++ b/whatsapp_api/views.py @@ -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}) diff --git a/whatsapp_service_project/__init__.py b/whatsapp_service_project/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/whatsapp_service_project/asgi.py b/whatsapp_service_project/asgi.py new file mode 100644 index 0000000..4324cc6 --- /dev/null +++ b/whatsapp_service_project/asgi.py @@ -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() diff --git a/whatsapp_service_project/settings.py b/whatsapp_service_project/settings.py new file mode 100644 index 0000000..6ddc5c2 --- /dev/null +++ b/whatsapp_service_project/settings.py @@ -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, + }, + }, +} diff --git a/whatsapp_service_project/urls.py b/whatsapp_service_project/urls.py new file mode 100644 index 0000000..ec9a0b5 --- /dev/null +++ b/whatsapp_service_project/urls.py @@ -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')), +] diff --git a/whatsapp_service_project/wsgi.py b/whatsapp_service_project/wsgi.py new file mode 100644 index 0000000..5d685c5 --- /dev/null +++ b/whatsapp_service_project/wsgi.py @@ -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()