initial commit
This commit is contained in:
63
apps/users/tasks.py
Normal file
63
apps/users/tasks.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import logging
|
||||
|
||||
import requests
|
||||
from celery import shared_task
|
||||
from django.conf import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SMS_APIKEY = settings.SMS_APIKEY
|
||||
|
||||
|
||||
def _send_sms(receptor, pattern_code, variables: list = None):
|
||||
"""
|
||||
Send OTP SMS using SMS.ir pattern-based API
|
||||
"""
|
||||
SMS_ENDPOINT = "https://api.sms.ir/v1/send/verify"
|
||||
|
||||
variables = variables or []
|
||||
headers = {"Content-Type": "application/json", "Accept": "text/plain", "x-api-key": SMS_APIKEY}
|
||||
payload = {
|
||||
"mobile": receptor,
|
||||
"templateId": str(pattern_code),
|
||||
"parameters": variables,
|
||||
}
|
||||
|
||||
logger.info(f"Sending SMS to {receptor} with payload: {payload}")
|
||||
|
||||
try:
|
||||
response = requests.post(SMS_ENDPOINT, data=payload, headers=headers, timeout=10)
|
||||
|
||||
logger.info(f"Response status: {response.status_code}")
|
||||
logger.info(f"Response text: {response.text}")
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
|
||||
if str(result.get("status", "")) == "1":
|
||||
logger.info(f"SMS sent successfully to {receptor}")
|
||||
else:
|
||||
logger.error(f"SMS.ir API error: {result}")
|
||||
else:
|
||||
logger.error(f"HTTP error sending SMS: {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:
|
||||
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
|
||||
Reference in New Issue
Block a user