新增资质
增加签名
增加模版
Access Key
建议创建子用户,方便权限控制
这里说了如何创建用户以及分配权限:
https://zhengxingtao.com/archives/a-li-yun-ossdui-xiang-cun-chu
Python调用
import random
class AliSmsParams:
"""
阿里云 SMS API 参数
https://dysms.console.aliyun.com/domestic/text
"""
# 使用RAM账号
# 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html
ACCESS_KEY_ID = "your_access_key_id"
ACCESS_KEY_SECRET = "your_access_key_secret"
# 区域ID 和 服务地址:https://api.aliyun.com/product/Dysmsapi
REGION_ID = "cn-hangzhou"
ENDPOINT = "dysmsapi.aliyuncs.com"
# 签名名称
SIGN_NAME = "your_sign_name"
# 模板CODE
TEMPLATE_CODE = "your_template_code"
# 测试号码:https://dysms.console.aliyun.com/quickstart
PHONE_NUMBERS = "your_test_phone_number"
# TEMPLATE_PARAM = '{"code":"1234", "time":"3"}'
class SendSMS:
"""
使用阿里云 SMS API 发送短信
https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?RegionId=cn-hangzhou
"""
def __init__(self):
pass
@staticmethod
def create_client() -> Client:
"""
使用AccessKey初始化账号Client
@return: Client
@throws Exception
"""
config = openapi_models.Config(
access_key_id=AliSmsParams.ACCESS_KEY_ID,
access_key_secret=AliSmsParams.ACCESS_KEY_SECRET,
)
config.endpoint = AliSmsParams.ENDPOINT
return Client(config)
@staticmethod
def main(args: List[str], code: str, time: str) -> None:
client = SendSMS.create_client()
send_sms_request = models.SendSmsRequest(
sign_name=AliSmsParams.SIGN_NAME,
template_code=AliSmsParams.TEMPLATE_CODE,
phone_numbers=AliSmsParams.PHONE_NUMBERS,
template_param=f'{{"code":"{code}", "time":"{time}"}}',
)
runtime = util_models.RuntimeOptions()
try:
response = client.send_sms_with_options(send_sms_request, runtime)
# pprint(response.__dict__)
# pprint(response.body.__dict__)
if response.body.message != "OK":
print("短信发送失败")
except Exception as error:
print(error.message)
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
async def main_async(args: List[str], code: str, time: str) -> None:
client = SendSMS.create_client()
send_sms_request = models.SendSmsRequest(
sign_name=AliSmsParams.SIGN_NAME,
template_code=AliSmsParams.TEMPLATE_CODE,
phone_numbers=AliSmsParams.PHONE_NUMBERS,
template_param=f'{{"code":"{code}", "time":"{time}"}}',
)
runtime = util_models.RuntimeOptions()
try:
await client.send_sms_with_options_async(send_sms_request, runtime)
except Exception as error:
print(error.message)
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
if __name__ == "__main__":
code = str(random.randint(100000, 999999))
time = "3"
SendSMS.main(sys.argv[1:], code, time)
评论区