Реализация кода
- :
Код: Выделить всё
views.py
Код: Выделить всё
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")
Код: Выделить всё
PHONE *
Send OTP
ENTER OTP *
STREET ADDRESS *
Код: Выделить всё
settings.pyКод: Выделить всё
TWILIO_ACCOUNT_SID = 'YOUR_ACCOUNT_SID'
TWILIO_AUTH_TOKEN = 'YOUR_AUTH_TOKEN'
TWILIO_PHONE_NUMBER = '+1234567890' # Twilio number with country code
Код: Выделить всё
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() : '';
}
- В форме передается правильный номер мобильного телефона и запрос POST. достигает представления Django.
- Методы Twilio Client и messages.create вызываются, но SMS не отправляется.
- Я вижу следующую ошибку в журналах Django:
Код: Выделить всё
Error sending OTP: TwilioRestException: [Error message here]
- Проверил, что учетные данные Twilio (SID учетной записи , токен аутентификации и номер телефона).
- Убедитесь, что номер телефона имеет формат E.164 с правильным кодом страны.
- Подтверждено что пробная учетная запись Twilio подтвердила телефон получателя номер.
- Проверил журналы сообщений Twilio, но записи о неудачном сообщении не появились.
- Протестировал функциональность Twilio с помощью автономного сценария, который работает:
Код: Выделить всё
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)
OTP-сообщение должно быть отправлено на введенный номер мобильного телефона.
Вопрос:
Что может быть причиной проблемы и как ее решить? Может ли это быть связано с настройкой моей учетной записи Twilio или конфигурацией Django? Будем признательны за любую помощь или информацию!
Дополнительные примечания:
[*]Я с использованием пробной учетной записи Twilio.
[*]Номер телефона получателя подтверждается на панели управления Twilio.
В моей настройке нет ограничений сети или брандмауэра.< /li>
Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-django
Мобильная версия