Metadata-Version: 2.4
Name: py-lmobile
Version: 1.0.0
Summary: 微网通联（51welink）短信服务 Python SDK，提供同步和异步两种发送方式，支持请求签名认证
Author-email: Guolei <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2026 郭磊
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://gitee.com/guolei19850528/py_lmobile
Project-URL: Repository, https://gitee.com/guolei19850528/py_lmobile.git
Project-URL: Documentation, https://www.lmobile.cn/ApiPages/index.html
Keywords: lmobile,python,client,api,微网通联,短信,sms,51welink
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Topic :: Communications
Classifier: Topic :: Communications :: Telephony
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0
Requires-Dist: jsonpath-ng>=1.5.3
Requires-Dist: jsonschema>=4.21.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: flake8>=6.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Dynamic: license-file

# py-lmobile

微网通联短信服务 Python SDK

[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/Python-3.10+-green.svg)](https://python.org)

## 简介

`py_lmobile` 是一个用于接入微网通联（51welink）短信服务的 Python SDK，提供同步和异步两种发送方式，支持请求签名认证，帮助开发者快速集成短信发送功能。

**官方文档**: [https://www.lmobile.cn/ApiPages/index.html](https://www.lmobile.cn/ApiPages/index.html)

主要特性:
- ✅ 支持同步和异步短信发送
- ✅ 内置请求签名认证机制（SHA256）
- ✅ 使用 Pydantic 进行响应数据模型化
- ✅ 基于 httpx 实现 HTTP 请求，支持自定义配置
- ✅ 提供丰富的工具函数辅助开发

## 安装

```bash
pip install py_lmobile
```

或者使用 `uv`（推荐）:

```bash
uv add py_lmobile
```

## 快速开始

### 同步发送短信

```python
from py_lmobile.sms import Sms

# 初始化客户端
sms = Sms(
    base_url="https://api.51welink.com/",
    account_id="your_account_id",
    password="your_password",
    product_id="your_product_id"
)

# 发送短信
response = sms.send(
    phone_nos="13800138000",
    content="您的验证码是：123456"
)

# 处理响应
print(response.json())
```

### 异步发送短信

```python
import asyncio
from py_lmobile.sms import Sms

async def main():
    # 初始化客户端
    sms = Sms(
        base_url="https://api.51welink.com/",
        account_id="your_account_id",
        password="your_password",
        product_id="your_product_id"
    )
    
    # 异步发送短信
    response = await sms.async_send(
        phone_nos=["13800138000", "13900139000"],
        content="您的验证码是：123456"
    )
    
    # 处理响应
    print(response.json())

asyncio.run(main())
```

## API 文档

**官方文档**: [https://www.lmobile.cn/ApiPages/index.html](https://www.lmobile.cn/ApiPages/index.html)

### Sms 类

#### 初始化参数

| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| base_url | str | 否 | `https://api.51welink.com/` | API服务器地址 |
| account_id | str | 是 | - | 账号ID |
| password | str | 是 | - | 密码 |
| product_id | str/int | 是 | - | 产品ID |
| smms_encrypt_key | str | 否 | `SMmsEncryptKey` | 加密密钥 |
| client_kwargs | dict | 否 | - | 传递给httpx.Client的额外配置 |

#### 方法

##### `send()` - 同步发送短信

```python
def send(
    client: Optional[httpx.Client] = None,
    phone_nos: Optional[Union[str, list, tuple]] = None,
    content: Optional[str] = None,
    **kwargs
) -> httpx.Response
```

**参数**:

| 参数 | 类型 | 说明 |
|------|------|------|
| client | httpx.Client | 可选的HTTP客户端实例 |
| phone_nos | str/list/tuple | 接收短信的手机号码 |
| content | str | 短信内容 |
| **kwargs | - | 传递给httpx.Client.request的额外参数 |

**返回**: `httpx.Response` - HTTP响应对象

##### `async_send()` - 异步发送短信

```python
async def async_send(
    client: Optional[httpx.AsyncClient] = None,
    phone_nos: Optional[Union[str, list, tuple]] = None,
    content: Optional[str] = None,
    **kwargs
) -> httpx.Response
```

**参数**:

| 参数 | 类型 | 说明 |
|------|------|------|
| client | httpx.AsyncClient | 可选的异步HTTP客户端实例 |
| phone_nos | str/list/tuple | 接收短信的手机号码 |
| content | str | 短信内容 |
| **kwargs | - | 传递给httpx.AsyncClient.request的额外参数 |

**返回**: `httpx.Response` - HTTP响应对象

##### `client()` - 创建同步客户端

```python
def client() -> httpx.Client
```

**返回**: `httpx.Client` - 配置好的同步HTTP客户端实例

##### `async_client()` - 创建异步客户端

```python
def async_client() -> httpx.AsyncClient
```

**返回**: `httpx.AsyncClient` - 配置好的异步HTTP客户端实例

## 工具函数

### `timestamp()`

生成当前时间戳（毫秒）

```python
from py_lmobile.sms.utils import timestamp

ts = timestamp()  # 返回示例: 1630000000000
```

### `random_digits(length: int = 10)`

生成指定长度的随机数字

```python
from py_lmobile.sms.utils import random_digits

digits = random_digits(10)  # 返回示例: 1234567890
```

### `sha256_signature()`

生成SHA256签名，用于请求认证

```python
from py_lmobile.sms.utils import sha256_signature

signature = sha256_signature(
    account_id="your_account_id",
    password="your_password",
    phone_nos="13800138000",
    random_digits="1234567890",
    timestamp="1630000000000",
    smms_encrypt_key="SMmsEncryptKey"
)
```

**签名生成规则**:

1. 密码先经过 MD5 加密（使用 `smms_encrypt_key` 作为盐值）
2. 按照固定顺序拼接参数：`AccountId`, `PhoneNos`(第一个), `Password`(MD5后大写), `Random`, `Timestamp`
3. 使用 `&` 符号连接各参数
4. 对拼接后的字符串进行 SHA256 加密

### `convert_to_result_eq_succ()`

将HTTP响应转换为标准化的响应模型

```python
from py_lmobile.sms.utils import convert_to_result_eq_succ

response = sms.send(phone_nos="13800138000", content="test")
result = convert_to_result_eq_succ(response)
print(result.Result)  # "succ"
```

### `result_eq_succ_validator()`

校验响应是否符合成功响应的JSON Schema

```python
from py_lmobile.sms.utils import result_eq_succ_validator

response = sms.send(phone_nos="13800138000", content="test")
is_valid = result_eq_succ_validator(response)  # True 或 False
```

### `json_find_first()`

使用JSONPath表达式从数据中查找第一个匹配项

```python
from py_lmobile.sms.utils import json_find_first

data = {"Result": "succ", "Data": {"Code": "123456"}}
result = json_find_first("$.Result", data)  # "succ"
```

### `json_is_valid()`

校验JSON数据是否符合指定的JSON Schema

```python
from py_lmobile.sms.utils import json_is_valid

schema = {"type": "object", "properties": {"Result": {"type": "string"}}}
data = {"Result": "succ"}
is_valid = json_is_valid(schema, data)  # True
```

## 响应模型

### `Base`

所有响应模型的基类，包含通用的错误码字段

```python
from py_lmobile.sms.responses import Base

response_data = {"Result": "succ", "Message": "发送成功"}
base = Base(**response_data)
print(base.Result)  # "succ"
```

### `RESULT_EQ_SUCC`

成功响应模型，继承自Base模型，限制Result字段值为"succ"

```python
from py_lmobile.sms.responses import RESULT_EQ_SUCC

result = RESULT_EQ_SUCC(Result="succ")
print(result.Result)  # "succ"
```

## 配置说明

### httpx 客户端配置

可以通过 `client_kwargs` 参数自定义 httpx 客户端配置：

```python
sms = Sms(
    account_id="your_account_id",
    password="your_password",
    product_id="your_product_id",
    client_kwargs={
        "timeout": 30,
        "verify": True,
        "proxies": "http://proxy:8080"
    }
)
```

### 客户端复用

建议复用HTTP客户端以提高性能：

```python
from py_lmobile.sms import Sms
import httpx

sms = Sms(
    account_id="your_account_id",
    password="your_password",
    product_id="your_product_id"
)

# 创建客户端并复用
with sms.client() as client:
    response1 = sms.send(client=client, phone_nos="13800138000", content="验证码1")
    response2 = sms.send(client=client, phone_nos="13900139000", content="验证码2")
```

## 签名流程详解

微网通联API使用SHA256签名进行身份认证，签名生成流程如下：

1. **密码加密**: `MD5(password + smms_encrypt_key)`
2. **参数拼接**: `AccountId={account_id}&PhoneNos={first_phone}&Password={md5_password_upper}&Random={random}&Timestamp={timestamp}`
3. **SHA256签名**: `SHA256(拼接后的字符串)`

**注意**: 参数顺序必须严格按照上述顺序，否则签名验证会失败。

## 注意事项

1. ⚠️ 密码会在内部进行MD5加密后参与签名计算
2. ⚠️ 签名算法使用SHA256，按照API要求的参数顺序拼接
3. ⚠️ 多个手机号请使用逗号分隔或传入列表
4. ⚠️ 建议复用HTTP客户端以提高性能
5. ⚠️ 确保服务器时间与标准时间同步，避免签名验证失败
6. ⚠️ 短信内容需要符合平台规定的格式和长度限制

## 开发

### 安装依赖

```bash
uv install -e ".[dev]"
```

### 运行测试

```bash
uv run pytest
```

### 代码格式化

```bash
uv run black src/
uv run isort src/
uv run flake8 src/
```

## 许可证

MIT License

## 主页

[https://gitee.com/guolei19850528/py_lmobile](https://gitee.com/guolei19850528/py_lmobile)

## 官方文档

[https://www.lmobile.cn/ApiPages/index.html](https://www.lmobile.cn/ApiPages/index.html)

## 作者

Guolei <174000902@qq.com>
