Metadata-Version: 2.4
Name: 35m-sdk
Version: 0.2.0
Summary: 35pay Python SDK · 5 行接入聚合支付（WeChat / Alipay / Stripe / Creem / 易支付），单文件零依赖；async 可选启用。pip install 35m-sdk[async] 启用 AsyncPay。
Project-URL: Homepage, https://pay.35team.com
Project-URL: Documentation, https://pay.35team.com/docs/sdk#python
Project-URL: Repository, https://github.com/guo2001china/35m-sdk
Project-URL: Issues, https://github.com/guo2001china/35m-sdk/issues
Author-email: 35m <sdk@35m.ai>
License: MIT License
        
        Copyright (c) 2026 35team
        
        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.
License-File: LICENSE
Keywords: 35pay,aggregated-payment,alipay,checkout,payment,stripe,wechat-pay
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Provides-Extra: async
Requires-Dist: httpx>=0.24; extra == 'async'
Description-Content-Type: text/markdown

# 35pay Python SDK

单文件 `pay35.py`，drop-in 任何 Python 3.9+ 项目。

- **同步 `Pay`**：零依赖（仅用 stdlib urllib + hmac），适合 Flask / Django sync / 脚本
- **异步 `AsyncPay`**：基于 httpx，适合 FastAPI / Starlette / Litestar / aiohttp 等 async 框架

## Install

```bash
# 方式 1：drop-in 单文件（同步用法）
curl -O https://pay.35team.com/sdk/python/pay35.py

# 方式 2：从 PyPI（同步用法）
pip install pay35

# 方式 3：async 用法（额外装 httpx）
pip install pay35[async]
```

## Usage（同步）

```python
import os
from pay35 import Pay

pay = Pay(api_key=os.environ["PAY_KEY"])

# 创建支付（dev: sk_test_xxx → 自动 mock；prod: sk_live_xxx → 真支付）
session = pay.create_checkout(
    amount=9900,                  # 单位：分
    currency="CNY",
    description="追思视频套餐",
    metadata={"order_id": str(order.id)},
    success_url="https://yoursite.com/orders/123",
)

# 跳到 35pay 托管收银台
return redirect(session["url"])
```

## Usage（异步，FastAPI / Starlette / Litestar / aiohttp）

```python
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from pay35 import AsyncPay

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.pay = AsyncPay(api_key=os.environ["PAY_KEY"])
    try:
        yield
    finally:
        await app.state.pay.aclose()

app = FastAPI(lifespan=lifespan)

@app.post("/checkout")
async def checkout():
    session = await app.state.pay.create_checkout(
        amount=9900, currency="CNY",
        metadata={"order_id": "..."},
        success_url="https://yoursite.com/done",
    )
    return {"url": session["url"]}
```

> async 内部使用单例 `httpx.AsyncClient`，复用 TCP 连接池。建议进程级单例（如 FastAPI 的 `lifespan`），不要每个请求 `new` 一次。

## Webhook 验签

```python
from pay35 import Pay

@app.route("/webhook", methods=["POST"])
def webhook():
    sig = request.headers.get("X-35pay-Signature", "")
    if not Pay.verify_webhook_signature(
        request.data.decode(), sig, WEBHOOK_SECRET
    ):
        return "invalid", 401
    event = request.get_json()
    if event["type"] == "payment.paid":
        order_id = event["data"]["metadata"]["order_id"]
        mark_order_paid(order_id)
    return "ok"
```

## API

同步 `Pay` 和异步 `AsyncPay` 方法签名一致，async 方法加 `await`。

| 方法 | 说明 |
|---|---|
| `Pay(api_key, base_url=..., timeout=15.0)` | 同步客户端 |
| `AsyncPay(api_key, base_url=..., timeout=15.0)` | 异步客户端，需 `pip install pay35[async]` |
| `(a)pay.create_checkout(amount, currency, ...)` | 创建支付 session，返回 `{"url": ..., "id": ...}` |
| `(a)pay.get_session(session_id)` | 查询状态 |
| `(a)pay.refund(record_id, amount=None, reason=None)` | 退款 |
| `await async_pay.aclose()` | 释放底层 httpx 连接池（推荐用 `async with`） |
| `Pay.verify_webhook_signature(payload, header, secret)` | static 方法，验签（同步/异步通用） |

## 兼容性

- Python 3.9+
- 默认零依赖（同步 `Pay` 用 `urllib`）
- 异步可选：`pip install pay35[async]` 拉入 `httpx>=0.24`
- 异常：HTTP 非 2xx 抛 `PayError(status, body)`
