OTP kann nicht über Twilio in Django gesendet werdenPython

Python-Programme
Guest
 OTP kann nicht über Twilio in Django gesendet werden

Post by Guest »

Ich arbeite an der Implementierung eines OTP-Systems in meinem Django-Projekt mit Twilio. Ich habe erfolgreich eine Twilio-Telefonnummer erhalten, aber die OTP-Nachricht wird nicht an die Mobiltelefonnummer des Benutzers gesendet. Unten sind die Details meines Setups:
Code-Implementierung

Code: Select all

def send_otp_view(request):
if request.method == "POST":
data = json.loads(request.body)
phone_number = data.get('phone_number')

# Generate a random 6-digit OTP
otp = random.randint(100000, 999999)

# Send OTP via Twilio (or any other SMS provider)
try:
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
message = client.messages.create(
body=f"Your OTP is {otp}. Please use this to verify your number.",
from_=settings.TWILIO_PHONE_NUMBER,
to=phone_number
)

# Optionally, store the OTP in a session or database
request.session['otp'] = otp
request.session['phone_number'] = phone_number

return JsonResponse({'status': 'success', 'otp': otp})  # Return OTP for validation
except Exception as e:
return JsonResponse({'status': 'error', 'message': str(e)})

return JsonResponse({'status': 'error', 'message': 'Invalid request'})

def address_view(request):
if request.user.is_authenticated:
user_addresses = Address.objects.filter(user=request.user)

if request.method == "POST":
# Get the OTP from the form
entered_otp = request.POST.get("otp")

# Check if the OTP matches
if entered_otp == str(request.session.get('otp')):
# Proceed with saving the address if OTP is correct
mobile = request.POST.get("mobile")
email = request.POST.get("email")
pin = request.POST.get("pin")
region = request.POST.get("region")
address = request.POST.get("address")
landmark = request.POST.get("landmark")
name = request.POST.get("name")

new_address = Address.objects.create(
user=request.user,
mobile=mobile,
email=email,
pin=pin,
region=region,
address=address,
landmark=landmark,
name=name,
)
messages.success(request, "Address Added Successfully.")
return redirect("core:address")
else:
messages.error(request, "Invalid OTP. Please try again.")
return redirect("core:address")

context = {
"user_addresses": user_addresses,
}
return render(request, 'others/address-book.html', context)
else:
print("User is not authenticated")
return redirect("core:login")
2. HTML-Formular:

Code: Select all


PHONE *

Send OTP

ENTER OTP *



STREET ADDRESS *



3. Twilio-Einstellungen (

Code: Select all

settings.py
):[/b]

Code: Select all

TWILIO_ACCOUNT_SID = 'YOUR_ACCOUNT_SID'
TWILIO_AUTH_TOKEN = 'YOUR_AUTH_TOKEN'
TWILIO_PHONE_NUMBER = '+1234567890'  # Twilio number with country code
4. Frontend-Validierung (JavaScript):

Code: Select all

console.log("OTP");

let sentOTP = null; // Store the sent OTP

function validatePhoneNumber() {
const phoneInput = document.getElementById('address-phone');
const otpBox = document.getElementById('otp-box');
const sendOtpBtn = document.getElementById('send-otp-btn');

// Check if the phone number is 10 digits long
if (phoneInput.value.length === 10) {
otpBox.style.display = 'block'; // Show OTP box
sendOtpBtn.style.display = 'inline-block'; // Show OTP button
} else {
otpBox.style.display = 'none'; // Hide OTP box
sendOtpBtn.style.display = 'none'; // Hide OTP button
}
}

function sendOTP() {
const phoneNumber = document.getElementById('address-phone').value;

// Send an AJAX request to the Django view to generate and send OTP
fetch('/send-otp/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken') // Handle CSRF token for security
},
body: JSON.stringify({ phone_number: phoneNumber })
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
sentOTP = data.otp; // Save the OTP for later validation
console.log("OTP sent successfully");
} else {
alert("Error sending OTP");
}
})
.catch(error => {
console.error('Error:', error);
alert('Failed to send OTP');
});
}

function validateOTP() {
const otpInput = document.getElementById('otp-input');
const feedback = document.getElementById('otp-feedback');

// Compare entered OTP with the sent OTP
if (otpInput.value === sentOTP) {
feedback.style.display = 'block';
feedback.style.color = 'green';
feedback.textContent = 'OTP is correct!';
} else if (otpInput.value.length === sentOTP.length) {
feedback.style.display = 'block';
feedback.style.color = 'red';
feedback.textContent = 'Incorrect OTP, please try again.';
} else {
feedback.style.display = 'none';  // Hide feedback when incomplete
}
}

// Utility to get the CSRF token from cookies
function getCookie(name) {
const cookieValue = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
return cookieValue ? cookieValue.pop() : '';
}
Problem:
  • Das Formular sendet die richtige Mobiltelefonnummer und die POST-Anfrage erreicht die Django-Ansicht.
  • Die Methoden „Client“ und „messages.create“ von Twilio werden aufgerufen, aber es wird keine SMS gesendet.
  • Ich sehe den folgenden Fehler in meinen Django-Protokollen:

Code: Select all

Error sending OTP: TwilioRestException: [Error message here]
Was ich versucht habe:
  • Überprüft, ob die Twilio-Anmeldeinformationen (Konto-SID , Authentifizierungstoken und Telefonnummer) sind korrekt.
  • Es wurde sichergestellt, dass die Telefonnummer im E.164-Format mit der richtigen Landesvorwahl vorliegt.
  • Bestätigt dass das Twilio-Testkonto das Telefon des Empfängers verifiziert hat Nummer.
  • Twilio-Nachrichtenprotokolle überprüft, aber für die fehlgeschlagene Nachricht werden keine Einträge angezeigt.
  • Die Twilio-Funktionalität wurde mit einem eigenständigen Skript getestet, das funktioniert:

Code: Select all

from twilio.rest import Client

client = Client('YOUR_ACCOUNT_SID', 'YOUR_AUTH_TOKEN')
message = client.messages.create(
body="Test message",
from_='+1234567890',
to='+9876543210'
)
print(message.sid)
Erwartetes Verhalten:
Die OTP-Nachricht sollte an die eingegebene Mobiltelefonnummer gesendet werden.
Frage:
Was könnte das Problem verursachen und wie kann ich es beheben? Könnte es mit der Einrichtung meines Twilio-Kontos oder meiner Django-Konfiguration zusammenhängen? Für jede Hilfe oder jeden Einblick wäre ich dankbar!
Zusätzliche Anmerkungen:
  • Ich bin mit einem Twilio-Testkonto.
  • Die Telefonnummer des Empfängers wird im Twilio-Dashboard überprüft.
    In meinem Setup gibt es keine Netzwerk- oder Firewall-Einschränkungen.< /li>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post