How to receive webhooks events in django?
I have a webhook registered and have a php file that receives the message and dump it under text file. I want to achieve the same in django but the function never gets called when the event is triggerd
the php code ''
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
file_put_contents('messages_log.txt', print_r($data, true), FILE_APPEND);
$formatted_output = '';
$timestamp = date('d-M-Y-H:i');
if (isset($data['data']['message']['body_message']['content']) && !empty($data['data']['message']['body_message']['content'])) {
$content = $data['data']['message']['body_message']['content'];
$from_contact = isset($data['data']['message']['from_contact']) ? $data['data']['message']['from_contact'] : 'Unknown';
$formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content);
} else {
$messages = isset($data['data']['data']['messages'][0]) ? $data['data']['data']['messages'][0] : null;
if ($messages) {
$message = isset($messages['message']) ? $messages['message'] : [];
$content = isset($message['conversation']) ? $message['conversation'] : '';
$from_contact = isset($messages['verifiedBizName']) ? $messages['verifiedBizName'] : '';
if (!empty($content) && !empty($from_contact)) {
$formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content);
}
}
}
if (!empty($formatted_output)) {
file_put_contents('formatted
_messages_log.txt', $formatted_output . PHP_EOL, FILE_APPEND);
}
http_response_code(200);
echo json_encode(['status' => 'received']);
} else {
http_response_code(405);
echo json_encode(['status' => 'Method Not Allowed']);
}
?>
'''
So whenever I receive or send a message from whatsapp it gets dumped here with "messages_log.txt"
Python django code (views.py)
import os
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
@csrf_exempt # Exempt from CSRF checks as it's a webhook
def home(request):
with open('jimmy', 'w') as file:
file.write(f"acid\n")
if request.method == 'POST':
raw_data = request.body.decode('utf-8')
try:
data = json.loads(raw_data)
except json.JSONDecodeError:
return JsonResponse({'status': 'Invalid JSON'}, status=400)
file_path = os.path.join(os.getcwd(), 'messages_log.txt')
with open(file_path, 'a') as file:
file.write(f"{json.dumps(data, indent=4)}\n")
return JsonResponse({'status': 'received'}, status=200)
# Respond with a 405 Method Not Allowed for non-POST requests
return JsonResponse({'status': 'Method Not Allowed'}, status=405)
It never received any whatsapp event. I tried sending stuff manually to url. like this
import requests
import json
url = 'test' # Replace with your actual URL
# Sample JSON payload to simulate the webhook event
payload = {
"data": {
"message": {
"body_message": {
"content": "This is a test message"
},
"from_contact": "Test Contact"
},
"data": {
"messages": [
{
"message": {
"conversation": "Fallback message content"
},
"verifiedBizName": "Test Business"
}
]
}
}
}
json_payload = json.dumps(payload)
response = requests.post(url, headers={'Content-Type': 'application/json'}, data=json_payload)
print(f"Status Code: {response.status_code}")
try:
response_json = response.json()
print(f"Response JSON: {response_json}")
except requests.exceptions.JSONDecodeError:
print("Response content is not JSON:")
print(response.text)
It gets recieved but the acutal whatsapp event never gets received. Php receives the message and received message looks like this
Array
(
[instance_id] => XXXXXXXXXXXXX
[data] => Array
(
[event] => contacts.update
[data] => Array
(
[0] => Array
(
[id] => 123123123@s.whatsapp.net
[imgUrl] => changed
)
)
)
No idea why I am unable to receive the whatsapp even on python
It was pretty strange experience
For webhook registration the company requires to register URL in this manner
So for PHP website I replace this part "https%3A%2F%2Fwebhook.site%2F" with my php website and it worked.
I contacted support and they said for django you need to create a url of your website having this slug too "1b25464d6833784f96eef4xxxxxxxxxx" like mywebiste.com/webhook/1b25464d6833784f96eef4xxxxxxxxxx in order for it to work whereas in php it was just mywebsite.com/webhook.php