feat: 完善代理重试机制,添加数据验证告警,新增README文档

This commit is contained in:
shengyudong@yunqueai.net
2026-01-16 18:36:52 +08:00
parent 322ac74336
commit b518e6aacf
55 changed files with 13202 additions and 34781 deletions

View File

@@ -0,0 +1,6 @@
# Alibaba Cloud Access Credentials
# 请在阿里云控制台获取您的 AccessKey ID 和 AccessKey Secret
# https://ram.console.aliyun.com/manage/ak
ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id_here
ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret_here

5
ai_sms/ai_sms/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
runtime/
.idea/
.vscode/
__pycache__/
.pytest_cache/

57
ai_sms/ai_sms/README.md Normal file
View File

@@ -0,0 +1,57 @@
# 发送短信验证码完整工程示例
该项目为SendSmsVerifyCode的完整工程示例。
**工程代码建议使用更安全的无AK方式凭据配置方式请参阅[管理访问凭据](https://help.aliyun.com/zh/sdk/developer-reference/v2-manage-python-access-credentials)。**
## 运行条件
- 下载并解压需要语言的代码;
- *要求 Python >= 3.7*
## 执行步骤
完成凭据配置后,可以在**解压代码所在目录下**按如下的步骤执行:
- **创建并激活虚拟环境:**
```sh
python -m venv venv && source venv/bin/activate
```
- **安装依赖:**
```sh
pip install -r requirements.txt
```
- **运行代码**
```sh
python ./alibabacloud_sample/sample.py
```
## 使用的 API
- SendSmsVerifyCode发送短信验证码。 更多信息可参考:[文档](https://next.api.aliyun.com/document/Dypnsapi/2017-05-25/SendSmsVerifyCode)
## API 返回示例
*下列输出值仅作为参考,实际输出结构可能稍有不同,以实际调用为准。*
- JSON 格式
```js
{
"AccessDeniedDetail": "无",
"Message": "成功 ",
"RequestId": "CC3BB6D2-2FDF-4321-9DCE-B38165CE4C47",
"Model": {
"VerifyCode": "4232",
"RequestId": "a3671ccf-0102-4c8e-8797-a3678e091d09",
"OutId": "1231231313",
"BizId": "112231421412414124123^4"
},
"Code": "OK",
"Success": true
}
```

View File

@@ -0,0 +1,94 @@
# 阿里云短信验证码 API 运行说明
## 项目配置完成情况
✅ 依赖已安装: `alibabacloud_dypnsapi20170525==2.0.0`
✅ 代码已配置: 手机号码 `13621242430`,验证码长度 4 位
✅ Conda 环境: `douyin`
## 运行步骤
### 1. 配置阿里云访问凭据
您需要先获取阿里云的 AccessKey ID 和 AccessKey Secret:
- 访问: https://ram.console.aliyun.com/manage/ak
- 创建或查看您的 AccessKey
### 2. 设置环境变量 (PowerShell)
在运行程序前,需要设置环境变量:
```powershell
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="your_access_key_id"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_access_key_secret"
```
### 3. 运行程序
```powershell
python ./alibabacloud_sample/sample.py
```
## 完整运行示例 (PowerShell)
```powershell
# 激活 conda 环境
conda activate douyin
# 设置凭据
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="your_access_key_id"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_access_key_secret"
# 运行程序
python ./alibabacloud_sample/sample.py
```
## 代码说明
### 当前配置参数
`sample.py` 已配置以下参数:
```python
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest(
phone_number='13621242430', # 接收短信的手机号码
code_length=4, # 验证码长度 (1314 是 4 位)
code_type=1 # 验证码类型: 1=数字
)
```
### API 返回示例
成功时返回:
```json
{
"Code": "OK",
"Success": true,
"Message": "成功",
"Model": {
"VerifyCode": "1234",
"BizId": "...",
"RequestId": "..."
}
}
```
## 注意事项
1. **安全性**: 不要将 AccessKey 硬编码在代码中或提交到版本控制系统
2. **权限**: 确保您的 AccessKey 有发送短信的权限
3. **费用**: 发送短信会产生费用,请注意阿里云账户余额
4. **签名和模板**: 某些地区可能需要配置短信签名和模板
## 故障排查
如果遇到错误:
- 检查 AccessKey 是否正确
- 检查账户余额是否充足
- 检查手机号码格式是否正确
- 查看错误信息中的诊断地址 (Recommend)
## API 文档
- SendSmsVerifyCode API: https://next.api.aliyun.com/document/Dypnsapi/2017-05-25/SendSmsVerifyCode
- 凭据管理: https://help.aliyun.com/zh/sdk/developer-reference/v2-manage-python-access-credentials

View File

@@ -0,0 +1,79 @@
# 开始使用 - 3步运行
## ⚠️ 您的错误原因
**环境变量未设置!** 错误信息显示:
```
Environment variable accessKeyId cannot be empty
```
## ✅ 解决方案(选一个)
### 方案 1: 最简单 - 使用测试脚本
```powershell
# 第1步: 测试凭据配置
python test_credentials.py
# 第2步: 如果提示未设置,在 PowerShell 中运行:
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="您的AccessKey_ID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="您的AccessKey_Secret"
# 第3步: 再次测试
python test_credentials.py
# 第4步: 测试通过后运行
python ./alibabacloud_sample/sample.py
```
### 方案 2: 一键运行(交互式)
```powershell
python run_with_credentials.py
# 脚本会提示您输入 AccessKey然后自动运行
```
### 方案 3: 手动设置后运行
```powershell
# 设置环境变量
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="LTAI5t..."
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_secret_here"
# 直接运行
python ./alibabacloud_sample/sample.py
```
## 🔑 获取 AccessKey
https://ram.console.aliyun.com/manage/ak
## 🔧 已修复的问题
1. ✅ 代理超时问题(已禁用 ECS 元数据代理)
2. ✅ 错误处理问题(已修复 AttributeError
3. ✅ 手机号已配置: 13621242430
4. ✅ 验证码长度: 4位数字
## 📝 当前配置
- 手机号: `13621242430`
- 验证码: 4位数字API自动生成不能指定为1314
- 环境: conda douyin
- 依赖: 已安装
## ⚡ 快速测试流程
```powershell
# 1. 测试凭据
python test_credentials.py
# 2. 如果失败,设置环境变量
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="your_key"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_secret"
# 3. 运行程序
python ./alibabacloud_sample/sample.py
```
**现在就试试 `python test_credentials.py`**

View File

@@ -0,0 +1 @@
__version__ = "1.0.0"

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json
from typing import List
from alibabacloud_dypnsapi20170525.client import Client as Dypnsapi20170525Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dypnsapi20170525 import models as dypnsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Dypnsapi20170525Client:
"""
使用凭据初始化账号Client
@return: Client
@throws Exception
"""
# 工程代码建议使用更安全的无AK方式凭据配置方式请参见https://help.aliyun.com/document_detail/378659.html。
credential = CredentialClient()
config = open_api_models.Config(
credential=credential
)
# Endpoint 请参考 https://api.aliyun.com/product/Dypnsapi
config.endpoint = f'dypnsapi.aliyuncs.com'
return Dypnsapi20170525Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest()
runtime = util_models.RuntimeOptions()
try:
resp = client.send_sms_verify_code_with_options(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest()
runtime = util_models.RuntimeOptions()
try:
resp = await client.send_sms_verify_code_with_options_async(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
if __name__ == '__main__':
Sample.main(sys.argv[1:])

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json
from typing import List
from alibabacloud_dypnsapi20170525.client import Client as Dypnsapi20170525Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dypnsapi20170525 import models as dypnsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Dypnsapi20170525Client:
"""
使用凭据初始化账号Client
@return: Client
@throws Exception
"""
credential_config = CredentialConfig(
type='access_key',
access_key_id='LTAI5tSMvnCJdqkZtCVWgh8R',
access_key_secret='nyFzXyIi47peVLK4wR2qqbPezmU79W'
)
credential = CredentialClient(credential_config)
config = open_api_models.Config(
credential=credential
)
# Endpoint 请参考 https://api.aliyun.com/product/Dypnsapi
config.endpoint = f'dypnsapi.aliyuncs.com'
return Dypnsapi20170525Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest(
phone_number='13621242430',
sign_name='阿里云短信',
template_code='SMS_474580174',
template_param='{}',
code_length=4,
code_type=1
)
runtime = util_models.RuntimeOptions()
try:
resp = client.send_sms_verify_code_with_options(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(f"错误: {error}")
# 诊断地址
if hasattr(error, 'data') and error.data:
print(f"诊断地址: {error.data.get('Recommend')}")
raise
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest()
runtime = util_models.RuntimeOptions()
try:
resp = await client.send_sms_verify_code_with_options_async(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
if __name__ == '__main__':
Sample.main(sys.argv[1:])

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json
from typing import List
from alibabacloud_dypnsapi20170525.client import Client as Dypnsapi20170525Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dypnsapi20170525 import models as dypnsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Dypnsapi20170525Client:
"""
使用凭据初始化账号Client
@return: Client
@throws Exception
"""
credential_config = CredentialConfig(
type='access_key',
access_key_id='LTAI5tPnLdDkvSxrVJfRZMCn',
access_key_secret='AII2A8hgfxXWM1xYqeuNwnS61AErDz'
)
credential = CredentialClient(credential_config)
config = open_api_models.Config(
credential=credential
)
# Endpoint 请参考 https://api.aliyun.com/product/Dypnsapi
config.endpoint = f'dypnsapi.aliyuncs.com'
return Dypnsapi20170525Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest(
phone_number='13621242430',
sign_name='阿里云短信',
template_code='SMS_474580174',
template_param='{}',
code_length=4,
code_type=1
)
runtime = util_models.RuntimeOptions()
try:
resp = client.send_sms_verify_code_with_options(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(f"错误: {error}")
# 诊断地址
if hasattr(error, 'data') and error.data:
print(f"诊断地址: {error.data.get('Recommend')}")
raise
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest()
runtime = util_models.RuntimeOptions()
try:
resp = await client.send_sms_verify_code_with_options_async(send_sms_verify_code_request, runtime)
print(json.dumps(resp, default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
if __name__ == '__main__':
Sample.main(sys.argv[1:])

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json
from typing import List
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.models import Config as CredentialConfig
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:
def __init__(self):
pass
@staticmethod
def create_client() -> Dysmsapi20170525Client:
"""
使用凭据初始化账号Client
@return: Client
@throws Exception
"""
credential_config = CredentialConfig(
type='access_key',
access_key_id='LTAI5tSMvnCJdqkZtCVWgh8R',
access_key_secret='nyFzXyIi47peVLK4wR2qqbPezmU79W'
)
credential = CredentialClient(credential_config)
config = open_api_models.Config(
credential=credential
)
# Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = f'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='13621242430',
sign_name='北京乐航时代科技',
template_code='SMS_486210104',
template_param=json.dumps({"code": "1314"})
)
runtime = util_models.RuntimeOptions()
try:
resp = client.send_sms_with_options(send_sms_request, runtime)
print(json.dumps(resp.to_map(), default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(f"错误: {error}")
# 诊断地址
if hasattr(error, 'data') and error.data:
print(f"诊断地址: {error.data.get('Recommend')}")
raise
@staticmethod
async def main_async(
args: List[str],
) -> None:
client = Sample.create_client()
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
phone_numbers='13621242430',
sign_name='北京乐航时代科技',
template_code='SMS_486210104',
template_param=json.dumps({"code": "1314"})
)
runtime = util_models.RuntimeOptions()
try:
resp = await client.send_sms_with_options_async(send_sms_request, runtime)
print(json.dumps(resp.to_map(), default=str, indent=2))
except Exception as error:
# 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
# 错误 message
print(error.message)
# 诊断地址
print(error.data.get("Recommend"))
if __name__ == '__main__':
Sample.main(sys.argv[1:])

View File

@@ -0,0 +1 @@
alibabacloud_dypnsapi20170525==2.0.0

View File

@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
"""
快速运行脚本 - 设置凭据并运行 SMS 示例
使用方法: python run_with_credentials.py
"""
import os
import sys
import subprocess
def main():
print("=" * 60)
print("阿里云短信验证码 API - 快速运行")
print("=" * 60)
print()
# 检查环境变量
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID')
access_key_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
if not access_key_id or not access_key_secret:
print("⚠️ 未检测到环境变量,请输入您的阿里云凭据:")
print(" (获取地址: https://ram.console.aliyun.com/manage/ak)")
print()
access_key_id = input("AccessKey ID: ").strip()
access_key_secret = input("AccessKey Secret: ").strip()
if not access_key_id or not access_key_secret:
print()
print("❌ 错误: AccessKey 不能为空!")
sys.exit(1)
# 设置环境变量
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = access_key_id
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = access_key_secret
print()
print("✅ 凭据已设置")
else:
print(f"✅ 检测到环境变量:")
print(f" ALIBABA_CLOUD_ACCESS_KEY_ID: {access_key_id[:8]}...")
print(f" ALIBABA_CLOUD_ACCESS_KEY_SECRET: {'*' * 20}")
print()
print("=" * 60)
print("正在运行 SMS 示例...")
print("=" * 60)
print()
# 运行示例
try:
# 使用当前环境运行
result = subprocess.run(
[sys.executable, './alibabacloud_sample/sample.py'],
env=os.environ.copy(),
capture_output=False
)
sys.exit(result.returncode)
except Exception as e:
print(f"❌ 运行失败: {e}")
sys.exit(1)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,45 @@
# PowerShell 脚本:设置阿里云凭据环境变量
# 使用方法: .\set_credentials.ps1
Write-Host "=" -NoNewline -ForegroundColor Cyan
Write-Host ("=" * 59) -ForegroundColor Cyan
Write-Host "阿里云 SMS API 凭据配置" -ForegroundColor Yellow
Write-Host "=" -NoNewline -ForegroundColor Cyan
Write-Host ("=" * 59) -ForegroundColor Cyan
Write-Host ""
# 提示用户输入凭据
Write-Host "请输入您的阿里云访问凭据:" -ForegroundColor Green
Write-Host "(可以在 https://ram.console.aliyun.com/manage/ak 获取)" -ForegroundColor Gray
Write-Host ""
$accessKeyId = Read-Host "AccessKey ID"
$accessKeySecret = Read-Host "AccessKey Secret" -AsSecureString
$accessKeySecretPlain = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($accessKeySecret)
)
if ([string]::IsNullOrWhiteSpace($accessKeyId) -or [string]::IsNullOrWhiteSpace($accessKeySecretPlain)) {
Write-Host ""
Write-Host "错误: AccessKey ID 和 AccessKey Secret 不能为空!" -ForegroundColor Red
exit 1
}
# 设置环境变量
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = $accessKeyId
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = $accessKeySecretPlain
Write-Host ""
Write-Host "=" -NoNewline -ForegroundColor Cyan
Write-Host ("=" * 59) -ForegroundColor Cyan
Write-Host "凭据配置成功!" -ForegroundColor Green
Write-Host "=" -NoNewline -ForegroundColor Cyan
Write-Host ("=" * 59) -ForegroundColor Cyan
Write-Host ""
Write-Host "环境变量已设置 (当前 PowerShell 会话有效):" -ForegroundColor Yellow
Write-Host "ALIBABA_CLOUD_ACCESS_KEY_ID: $($accessKeyId.Substring(0, [Math]::Min(8, $accessKeyId.Length)))..." -ForegroundColor Gray
Write-Host "ALIBABA_CLOUD_ACCESS_KEY_SECRET: ********************" -ForegroundColor Gray
Write-Host ""
Write-Host "现在可以运行程序:" -ForegroundColor Green
Write-Host "python .\alibabacloud_sample\sample.py" -ForegroundColor Cyan
Write-Host ""

76
ai_sms/ai_sms/setup.py Normal file
View File

@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
import os
from setuptools import setup, find_packages
"""
setup module for alibabacloud_sample.
Created on 31/12/2025
@author:
"""
PACKAGE = "alibabacloud_sample"
NAME = "alibabacloud_sample" or "alibabacloud-package"
DESCRIPTION = "Alibaba Cloud SDK Code Sample Library for Python"
AUTHOR = ""
AUTHOR_EMAIL = ""
URL = "https://github.com/aliyun/alibabacloud-sdk"
VERSION = __import__(PACKAGE).__version__
REQUIRES = [
"alibabacloud_dypnsapi20170525>=2.0.0, <3.0.0",
]
LONG_DESCRIPTION = ''
if os.path.exists('./README.md'):
with open("README.md", encoding='utf-8') as fp:
LONG_DESCRIPTION = fp.read()
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="Apache License 2.0",
url=URL,
keywords=["alibabacloud","sample"],
packages=find_packages(exclude=["tests*"]),
include_package_data=True,
platforms="any",
install_requires=REQUIRES,
python_requires=">=3.6",
classifiers=(
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
"Topic :: Software Development"
)
)

View File

@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
import os
import sys
def setup_credentials():
"""
设置阿里云访问凭据的环境变量
"""
print("=" * 60)
print("阿里云 SMS API 凭据配置")
print("=" * 60)
print("\n请输入您的阿里云访问凭据:")
print("(可以在 https://ram.console.aliyun.com/manage/ak 获取)\n")
access_key_id = input("AccessKey ID: ").strip()
access_key_secret = input("AccessKey Secret: ").strip()
if not access_key_id or not access_key_secret:
print("\n错误: AccessKey ID 和 AccessKey Secret 不能为空!")
sys.exit(1)
# 设置环境变量
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = access_key_id
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = access_key_secret
print("\n" + "=" * 60)
print("凭据配置成功!")
print("=" * 60)
print("\n环境变量已设置:")
print(f"ALIBABA_CLOUD_ACCESS_KEY_ID: {access_key_id[:8]}...")
print(f"ALIBABA_CLOUD_ACCESS_KEY_SECRET: {'*' * 20}")
print("\n您可以使用以下命令设置环境变量 (PowerShell):")
print(f'$env:ALIBABA_CLOUD_ACCESS_KEY_ID="{access_key_id}"')
print(f'$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="{access_key_secret}"')
print("\n或者在当前 Python 会话中运行:")
print("python ./alibabacloud_sample/sample.py")
if __name__ == '__main__':
setup_credentials()

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
"""
测试凭据是否正确配置
使用方法: python test_credentials.py
"""
import os
import sys
os.environ['NO_PROXY'] = '100.100.100.200'
os.environ['no_proxy'] = '100.100.100.200'
from alibabacloud_credentials.client import Client as CredentialClient
def test_credentials():
print("=" * 60)
print("测试阿里云凭据配置")
print("=" * 60)
print()
# 检查环境变量
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID')
access_key_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
print("1. 检查环境变量:")
if access_key_id:
print(f" ✅ ALIBABA_CLOUD_ACCESS_KEY_ID: {access_key_id[:8]}...")
else:
print(f" ❌ ALIBABA_CLOUD_ACCESS_KEY_ID: 未设置")
if access_key_secret:
print(f" ✅ ALIBABA_CLOUD_ACCESS_KEY_SECRET: {'*' * 20}")
else:
print(f" ❌ ALIBABA_CLOUD_ACCESS_KEY_SECRET: 未设置")
print()
print("2. 测试凭据加载:")
try:
credential_client = CredentialClient()
credential = credential_client.get_credential()
loaded_ak_id = credential.get_access_key_id()
loaded_ak_secret = credential.get_access_key_secret()
if loaded_ak_id and loaded_ak_secret:
print(f" ✅ 凭据加载成功!")
print(f" AccessKey ID: {loaded_ak_id[:8]}...")
print(f" AccessKey Secret: {'*' * 20}")
print()
print("=" * 60)
print("✅ 凭据配置正确,可以运行程序了!")
print("=" * 60)
print()
print("运行命令:")
print(" python ./alibabacloud_sample/sample.py")
print()
print("或使用快速运行脚本:")
print(" python run_with_credentials.py")
return True
else:
print(" ❌ 凭据加载失败: AccessKey 为空")
return False
except Exception as e:
print(f" ❌ 凭据加载失败: {e}")
print()
print("=" * 60)
print("解决方案:")
print("=" * 60)
print()
print("请在 PowerShell 中设置环境变量:")
print()
print(' $env:ALIBABA_CLOUD_ACCESS_KEY_ID="您的AccessKey_ID"')
print(' $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="您的AccessKey_Secret"')
print()
print("然后重新运行此测试脚本")
print()
print("获取 AccessKey: https://ram.console.aliyun.com/manage/ak")
return False
if __name__ == '__main__':
success = test_credentials()
sys.exit(0 if success else 1)

View File

@@ -0,0 +1,100 @@
# 快速运行指南
## 问题原因
您遇到的错误是因为程序无法加载阿里云访问凭据。默认凭据链尝试了以下方式但都失败了:
1. ❌ 环境变量 `ALIBABA_CLOUD_ACCESS_KEY_ID``ALIBABA_CLOUD_ACCESS_KEY_SECRET`
2. ❌ CLI 配置文件 `C:\Users\34362\.aliyun\config.json`
3. ❌ 凭据配置文件 `C:\Users\34362\.alibabacloud\credentials.ini`
4. ❌ ECS 实例 RAM 角色(尝试连接代理 127.0.0.1:10809 失败)
## 解决方案
### 方案 1: 使用环境变量(推荐,最简单)
在 PowerShell 中运行:
```powershell
# 设置环境变量
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="您的AccessKey_ID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="您的AccessKey_Secret"
# 运行程序
python .\alibabacloud_sample\sample.py
```
### 方案 2: 使用 PowerShell 脚本(交互式)
```powershell
# 运行凭据配置脚本
.\set_credentials.ps1
# 脚本会提示输入凭据并自动设置环境变量
# 然后直接运行程序
python .\alibabacloud_sample\sample.py
```
### 方案 3: 创建凭据配置文件(永久配置)
创建文件 `C:\Users\34362\.alibabacloud\credentials.ini`
```ini
[default]
type = access_key
access_key_id = 您的AccessKey_ID
access_key_secret = 您的AccessKey_Secret
```
然后直接运行:
```powershell
python .\alibabacloud_sample\sample.py
```
## 获取 AccessKey
1. 访问阿里云 RAM 控制台: https://ram.console.aliyun.com/manage/ak
2. 创建或查看您的 AccessKey ID 和 AccessKey Secret
3. **重要**: 妥善保管 AccessKey Secret不要泄露
## 当前配置
- ✅ 手机号码: `13621242430`
- ✅ 验证码长度: 4 位数字
- ✅ 依赖已安装
- ✅ 错误处理已修复
## 注意事项
1. **代理问题**: 如果您使用了代理(如 127.0.0.1:10809可能需要临时关闭或配置 `NO_PROXY` 环境变量
2. **验证码**: API 会自动生成验证码,无法指定为 "1314"
3. **费用**: 发送短信会产生费用
## 完整示例
```powershell
# 1. 激活 conda 环境(如果需要)
conda activate douyin
# 2. 设置凭据
$env:ALIBABA_CLOUD_ACCESS_KEY_ID="LTAI5t..."
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET="your_secret"
# 3. 运行程序
python .\alibabacloud_sample\sample.py
```
## 预期输出
成功时会看到类似输出:
```json
{
"Code": "OK",
"Success": true,
"Message": "成功",
"Model": {
"VerifyCode": "1234",
"BizId": "...",
"RequestId": "..."
}
}
```

View File

@@ -0,0 +1,91 @@
# ✅ API 已成功连接!
## 🎉 当前状态
1. **API 连接成功**: 已成功调用阿里云短信服务 API
2. **代码已切换**: 从 `dypnsapi` 切换到正确的 `dysmsapi`
3. **凭据正确**: AccessKey 配置正确
4. **手机号已配置**: 13621242430
5. **验证码已配置**: 1314
## ⚠️ 最后一步:配置正确的短信模板
当前错误: `isv.SMS_TEMPLATE_ILLEGAL` - 该账号下找不到对应模板
**原因**: 模板代码 `SMS_474580174` 不存在或未审核通过
### 解决方案
1. **登录阿里云短信控制台**
- 短信模板管理: https://dysms.console.aliyun.com/domestic/text/template
2. **查看您的已审核通过的模板**
- 找到模板代码(格式: `SMS_xxxxxxxxx`
- 确保模板状态为"审核通过"
3. **更新代码中的模板代码**
编辑 `sample.py` 第 50 行和第 74 行:
```python
template_code='SMS_您的实际模板代码',
```
4. **确认模板参数**
如果您的模板内容是: `您的验证码是${code}有效期5分钟`
那么当前的配置已经正确:
```python
template_param=json.dumps({"code": "1314"})
```
如果模板变量名不是 `code`,请相应修改。
## 📝 当前代码配置
```python
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
phone_numbers='13621242430', # ✅ 手机号
sign_name='阿里云短信', # ✅ 签名(如果不对请修改)
template_code='SMS_474580174', # ⚠️ 需要替换为您的实际模板代码
template_param=json.dumps({"code": "1314"}) # ✅ 验证码参数
)
```
## 🚀 运行命令
配置完模板代码后:
```powershell
python .\alibabacloud_sample\sample.py
```
## ✅ 成功的响应示例
配置正确后,您会看到:
```json
{
"statusCode": 200,
"body": {
"Code": "OK",
"Message": "OK",
"BizId": "...",
"RequestId": "..."
}
}
```
## 📖 参考链接
- **短信模板管理**: https://dysms.console.aliyun.com/domestic/text/template
- **短信签名管理**: https://dysms.console.aliyun.com/domestic/text/sign
- **API 文档**: https://help.aliyun.com/zh/sms/developer-reference/api-dysmsapi-2017-05-25-sendsms
## 💡 提示
1. 如果签名名称也不对,请同时修改第 49 行和第 73 行的 `sign_name`
2. 模板必须是"审核通过"状态才能使用
3. 签名和模板必须匹配您的账号
**只需要更新正确的模板代码,程序就能成功发送短信了!**

View File

@@ -0,0 +1,69 @@
# ✅ 代码已跑通 - 还需配置短信签名和模板
## 🎉 成功进展
1.**凭据已硬编码**: AccessKey 已配置在代码中
2.**API 连接成功**: 已成功调用阿里云 API
3.**手机号已配置**: 13621242430
4.**验证码配置**: 4位数字
## ⚠️ 还需完成的配置
### 1. 短信签名 (SignName)
当前代码使用: `'阿里云'`
**您需要:**
- 在阿里云短信控制台创建并审核通过短信签名
- 控制台地址: https://dysms.console.aliyun.com/domestic/text/sign
-`@D:\ai_sms\alibabacloud_sample\sample.py:49` 中的 `'阿里云'` 替换为您的实际签名
### 2. 短信模板 (TemplateCode)
当前代码使用: `'SMS_123456789'` (占位符)
**您需要:**
- 在阿里云短信控制台创建并审核通过短信模板
- 控制台地址: https://dysms.console.aliyun.com/domestic/text/template
- 模板类型: 验证码
- 模板内容示例: `您的验证码是${code}有效期5分钟`
-`@D:\ai_sms\alibabacloud_sample\sample.py:50` 中的 `'SMS_123456789'` 替换为您的实际模板代码
## 📝 当前代码配置
```python
send_sms_verify_code_request = dypnsapi_20170525_models.SendSmsVerifyCodeRequest(
phone_number='13621242430', # ✅ 已配置
sign_name='阿里云', # ⚠️ 需要替换为您的签名
template_code='SMS_123456789', # ⚠️ 需要替换为您的模板代码
code_length=4, # ✅ 已配置
code_type=1 # ✅ 已配置 (数字验证码)
)
```
## 🚀 完成配置后运行
```powershell
python .\alibabacloud_sample\sample.py
```
## 📖 参考链接
- **短信签名管理**: https://dysms.console.aliyun.com/domestic/text/sign
- **短信模板管理**: https://dysms.console.aliyun.com/domestic/text/template
- **API 文档**: https://next.api.aliyun.com/document/Dypnsapi/2017-05-25/SendSmsVerifyCode
## 💡 注意事项
1. 签名和模板需要审核,通常需要几分钟到几小时
2. 签名和模板必须审核通过后才能使用
3. 验证码由 API 自动生成,无法指定为 "1314"
4. 发送短信会产生费用,请确保账户有余额
## 🔍 当前错误信息
最后一次运行的错误:
- `MissingTemplateCode`: 需要配置模板代码
- 诊断地址已在错误信息中提供
配置完签名和模板后,程序即可成功发送短信验证码!