smswhatsappservice/whatsapp_api/views.py
vickytechkey 8f31f80e99
All checks were successful
Deploy Beta (NATIVE) / deploy (push) Successful in 32s
feat: format mobile number with country code prefix in WhatsApp payload
2026-09-21 22:29:39 +05:30

121 lines
4.7 KiB
Python

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"):
template_path = os.path.join(settings.BASE_DIR, 'template jsons', f"{template_name}.json")
if not os.path.exists(template_path):
logger.error(f"Template {template_name} not found")
return {"status": "error", "message": f"Template {template_name} not found"}
with open(template_path, 'r') as f:
payload_dict = json.load(f)
clean_digits = ''.join(c for c in str(mobile_number) if c.isdigit())
if len(clean_digits) == 10:
target_number = f"91{clean_digits}"
else:
target_number = clean_digits
# Populate the dynamic values
try:
to_and_components = payload_dict["payload"]["template"]["to_and_components"][0]
to_and_components["to"] = [target_number]
if "components" in to_and_components:
if "body_1" in to_and_components["components"]:
to_and_components["components"]["body_1"]["value"] = otp_code
if "button_1" in to_and_components["components"]:
to_and_components["components"]["button_1"]["value"] = otp_code
except (KeyError, IndexError) as e:
logger.error(f"Error parsing template JSON structure: {e}")
return {"status": "error", "message": f"Invalid template JSON structure"}
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')
templates_dir = os.path.join(settings.BASE_DIR, 'template jsons')
templates = []
if os.path.exists(templates_dir):
for f in os.listdir(templates_dir):
if f.endswith('.json'):
templates.append(f.replace('.json', ''))
logs = WhatsAppMessageLog.objects.all().order_by('-created_at')[:10]
return render(request, 'whatsapp_api/index.html', {'logs': logs, 'templates': templates})