# 阿里云短信服务 Python SDK 调用指南 ## 前置准备 | 步骤 | 说明 | 参考链接 | |------|------|----------| | 1. 查看 API 文档 | 了解 SendSms 接口参数 | [API 文档](https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/?tab=DOC) | | 2. 创建 RAM 用户 | 建议使用 RAM 用户而非主账号 | [RAM 用户概览](https://help.aliyun.com/zh/ram/user-guide/overview-of-ram-users) | | 3. 创建 AccessKey | 获取 AccessKey ID 和 Secret | [创建访问密钥](https://help.aliyun.com/zh/ram/user-guide/create-an-accesskey-pair) | ## 环境配置 ### Python 版本要求 - Python >= 3.7 ### 安装 SDK ```bash pip install alibabacloud_dysmsapi20170525==4.3.0 ``` > 最新版本:https://pypi.org/project/alibabacloud_dysmsapi20170525/ ### 环境变量配置 | 环境变量名 | 说明 | 示例值 | |-----------|------|--------| | `ALIBABA_CLOUD_ACCESS_KEY_ID` | AccessKey ID | `LTAI5t...` | | `ALIBABA_CLOUD_ACCESS_KEY_SECRET` | AccessKey Secret | `xxx...` | > 推荐使用无 AK 方式(凭据配置),详见:[凭据配置文档](https://help.aliyun.com/document_detail/378659.html) ## 代码示例 ### 同步调用示例 ```python # -*- coding: utf-8 -*- import os import sys from typing import List from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client from alibabacloud_credentials.client import Client as CredentialClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models from alibabacloud_tea_util import models as util_models from alibabacloud_tea_util.client import Client as UtilClient class Sample: @staticmethod def create_client() -> Dysmsapi20170525Client: """ 使用凭据初始化账号 Client @return: Client """ # 使用凭据客户端(推荐方式,支持无 AK) credential = CredentialClient() config = open_api_models.Config( credential=credential ) # 配置 Endpoint config.endpoint = 'dysmsapi.aliyuncs.com' return Dysmsapi20170525Client(config) @staticmethod def main(args: List[str]) -> None: # 初始化客户端 client = Sample.create_client() # 构造请求对象 send_sms_request = dysmsapi_20170525_models.SendSmsRequest( phone_numbers='1390000****', # 接收短信的手机号 sign_name='阿里云', # 短信签名 template_code='SMS_15305****', # 短信模板代码 template_param='{"name":"张三","number":"1390000****"}' # 模板参数(JSON 字符串) ) try: # 发送短信 response = client.send_sms_with_options( send_sms_request, util_models.RuntimeOptions() ) # 打印响应 print(response) except Exception as error: # 错误处理 print(f"错误信息: {error.message}") if hasattr(error, 'data') and error.data: print(f"诊断地址: {error.data.get('Recommend')}") UtilClient.assert_as_string(error.message) if __name__ == '__main__': Sample.main(sys.argv[1:]) ``` ### 异步调用示例 ```python import asyncio from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models from alibabacloud_tea_util import models as util_models class Sample: @staticmethod async def main_async(args: List[str]) -> None: client = Sample.create_client() send_sms_request = dysmsapi_20170525_models.SendSmsRequest( phone_numbers='1390000****', sign_name='阿里云', template_code='SMS_15305****', template_param='{"name":"张三"}' ) try: # 异步调用 response = await client.send_sms_with_options_async( send_sms_request, util_models.RuntimeOptions() ) print(response) except Exception as error: print(f"错误信息: {error.message}") # 运行异步示例 if __name__ == '__main__': asyncio.run(Sample.main_async(sys.argv[1:])) ``` ### 使用环境变量直接配置(传统方式) ```python import os from alibabacloud_tea_openapi import models as open_api_models # 直接使用 AccessKey(不推荐,建议使用凭据客户端) config = open_api_models.Config( access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] ) config.endpoint = 'dysmsapi.aliyuncs.com' ``` ## 请求参数说明 | 参数 | 类型 | 必填 | 说明 | |------|------|------|------| | `phone_numbers` | String | 是 | 接收短信的手机号,多个号码用逗号分隔 | | `sign_name` | String | 是 | 短信签名,需在控制台审核通过 | | `template_code` | String | 是 | 短信模板代码,需在控制台审核通过 | | `template_param` | String | 否 | 模板参数,JSON 格式字符串 | ## 响应格式 ```python # 响应对象结构 response.body.request_id # 请求 ID response.body.biz_id # 业务流水号 response.body.code # 状态码(OK 表示成功) response.body.message # 状态描述 ``` ### 响应字段说明 | 字段 | 类型 | 说明 | |------|------|------| | `biz_id` | String | 业务流水号,用于查询发送状态 | | `code` | String | 状态码,`OK` 表示成功 | | `message` | String | 状态描述 | | `request_id` | String | 请求 ID,用于问题排查 | ## 异常处理 ```python from Tea.exceptions import UnretryableException, TeaException try: response = client.send_sms_with_options(request, util_models.RuntimeOptions()) except UnretryableException as e: # 网络异常 print(f"网络异常: {e}") except TeaException as e: # 业务异常 print(f"业务异常: {e.message}") if e.data: print(f"诊断地址: {e.data.get('Recommend')}") except Exception as e: # 其他异常 print(f"其他异常: {e}") ``` ## 注意事项 1. **凭据配置**:推荐使用 `CredentialClient` 进行无 AK 配置,更安全 2. **环境变量**:如使用传统方式,确保设置 `ALIBABA_CLOUD_ACCESS_KEY_ID` 和 `ALIBABA_CLOUD_ACCESS_KEY_SECRET` 3. **签名和模板**:需在阿里云控制台提前申请并审核通过 4. **模板参数**:必须是有效的 JSON 字符串,参数名需与模板中的变量名一致 5. **异步调用**:使用 `send_sms_with_options_async` 进行异步调用,需要配合 `asyncio` ## 相关链接 - [SDK 源码仓库](https://github.com/aliyun/alibabacloud-python-sdk/tree/master/dysmsapi-20170525) - [SDK 示例代码](https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/?tab=DEMO&lang=PYTHON&sdkStyle=dara) - [API 文档](https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/?tab=DOC) - [凭据配置文档](https://help.aliyun.com/document_detail/378659.html)