60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
PerToolBox Server - 阿里云短信服务
|
|
Copyright (C) 2024 Sea Network Technology Studio
|
|
Author: Canglan <admin@sea-studio.top>
|
|
License: AGPL v3
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
from typing import Optional
|
|
from ..config import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def send_sms(phone: str, code: str) -> bool:
|
|
"""发送短信验证码(阿里云)"""
|
|
if not all([
|
|
settings.ALIYUN_SMS_ACCESS_KEY_ID,
|
|
settings.ALIYUN_SMS_ACCESS_KEY_SECRET,
|
|
settings.ALIYUN_SMS_SIGN_NAME,
|
|
settings.ALIYUN_SMS_TEMPLATE_CODE
|
|
]):
|
|
logger.warning("阿里云短信未配置,使用模拟验证码")
|
|
return True
|
|
|
|
try:
|
|
from aliyunsdkcore.client import AcsClient
|
|
from aliyunsdkcore.request import CommonRequest
|
|
|
|
client = AcsClient(
|
|
settings.ALIYUN_SMS_ACCESS_KEY_ID,
|
|
settings.ALIYUN_SMS_ACCESS_KEY_SECRET,
|
|
'cn-hangzhou'
|
|
)
|
|
|
|
request = CommonRequest()
|
|
request.set_domain('dysmsapi.aliyuncs.com')
|
|
request.set_version('2017-05-25')
|
|
request.set_action_name('SendSms')
|
|
|
|
request.add_query_param('PhoneNumbers', phone)
|
|
request.add_query_param('SignName', settings.ALIYUN_SMS_SIGN_NAME)
|
|
request.add_query_param('TemplateCode', settings.ALIYUN_SMS_TEMPLATE_CODE)
|
|
request.add_query_param('TemplateParam', json.dumps({'code': code}))
|
|
|
|
response = client.do_action_with_exception(request)
|
|
result = json.loads(response)
|
|
|
|
if result.get('Code') == 'OK':
|
|
logger.info(f"短信发送成功: {phone}")
|
|
return True
|
|
else:
|
|
logger.error(f"短信发送失败: {result}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
logger.error(f"短信发送异常: {e}")
|
|
return False |