77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
import logging
|
|
|
|
import requests
|
|
from celery import shared_task
|
|
from django.conf import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _send_sms(receptor, pattern_code, variables: list = None):
|
|
"""
|
|
Send OTP SMS using SMS.ir verify API
|
|
"""
|
|
SMS_ENDPOINT = "https://api.sms.ir/v1/send/verify"
|
|
|
|
variables = variables or []
|
|
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json",
|
|
"x-api-key": settings.SMS_APIKEY,
|
|
}
|
|
|
|
payload = {
|
|
"mobile": receptor,
|
|
"templateId": int(pattern_code),
|
|
"parameters": variables,
|
|
}
|
|
|
|
logger.info("Sending SMS to %s with payload: %s", receptor, payload)
|
|
|
|
try:
|
|
response = requests.post(
|
|
SMS_ENDPOINT,
|
|
json=payload,
|
|
headers=headers,
|
|
timeout=10,
|
|
)
|
|
|
|
logger.info("Response status: %s", response.status_code)
|
|
logger.info("Response text: %s", response.text)
|
|
|
|
if response.status_code == 200:
|
|
result = response.json()
|
|
|
|
if str(result.get("status", "")) == "1":
|
|
logger.info("SMS sent successfully to %s", receptor)
|
|
else:
|
|
logger.error("SMS.ir API error: %s", result)
|
|
else:
|
|
logger.error("HTTP error sending SMS: %s - %s", response.status_code, response.text)
|
|
|
|
return response
|
|
|
|
except requests.exceptions.RequestException:
|
|
logger.error("Network error in send_sms", exc_info=True)
|
|
return None
|
|
|
|
|
|
@shared_task
|
|
def send_verification_sms(mobile, code):
|
|
logger.info(f"Starting to send SMS to {mobile} with code {code}")
|
|
try:
|
|
if not settings.SMS_APIKEY:
|
|
logger.info("SMS_APIKEY is not configured. Skipping real SMS delivery for %s with code %s", mobile, code)
|
|
return {"mobile": mobile, "code": str(code), "sent": False}
|
|
|
|
variables = [{"name": "OTP", "value": str(code)}]
|
|
response = _send_sms(mobile, 570574, variables=variables)
|
|
if response and response.status_code == 200:
|
|
logger.info(f"Verification SMS sent to {mobile}")
|
|
else:
|
|
raise Exception("Failed to send SMS")
|
|
except Exception as e:
|
|
logger.error(f"Error in send_verification_sms: {e}", exc_info=True)
|
|
raise # For Celery retry
|