Metadata-Version: 2.4
Name: wechat-sdk-python
Version: 0.1.0
Summary: A Python SDK foundation for WeChat APIs
Author: TiyeeJiang
License: MIT License
        
        Copyright (c) 2026 TiyeeJiang
        
        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://github.com/tiyee/wechat-sdk-python
Project-URL: Repository, https://github.com/tiyee/wechat-sdk-python
Project-URL: Issues, https://github.com/tiyee/wechat-sdk-python/issues
Keywords: wechat,weixin,sdk,api
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: cryptography<46,>=41
Requires-Dist: typing-extensions>=4.6
Requires-Dist: pydantic<3,>=2.11
Dynamic: license-file

# wechat-sdk-python

用于在 Python 服务端调用微信 API 的同步 SDK，支持 Python 3.9 及以上版本。

## 安装

使用 pip 从 PyPI 安装：

```bash
python -m pip install wechat-sdk-python
```

## 选择客户端

| 微信业务 | 导入方式 |
| --- | --- |
| 小程序 | `from wechat_sdk.miniapp import MiniAppClient` |
| 公众号（订阅号、服务号） | `from wechat_sdk.official_account import OfficialAccountClient` |
| 微信小店 | `from wechat_sdk.store import StoreClient` |
| 视频号 | `from wechat_sdk.channels import ChannelsClient` |
| 微信开放平台 | `from wechat_sdk.open_platform import OpenPlatformClient` |
| 企业微信 | `from wechat_sdk.work.client import WorkClient` |
| 微信支付 | `from wechat_sdk.pay import PayV2Client, PayV3Client` |
| x402 支付 | `from wechat_sdk.pay.aipay import X402Client` |

每个客户端对应一个调用账号。小程序、公众号、视频号和微信小店使用该账号的 `app_id` 和 `secret_id` 初始化。首次调用需要全局凭据的接口时，客户端自动获取并缓存 `access_token`，在临近到期时续取。需要读取当前凭据时，调用 `client.get_access_token()`。

## 调用尚未封装的接口

如果 SDK 尚未封装某个微信接口，可以直接调用对应业务客户端的 `request()` 方法。按微信接口文档传入 HTTP 方法和相对路径，用 `params=` 传查询参数，用 `json=` 传 JSON 请求体。

下面以公众号查询用户标签为例，演示如何直接发起请求。将该公众号下用户的 OpenID 写入环境变量 `WECHAT_OPENID`。客户端会自动附加公众号的 `access_token`，检查微信错误码后，再将响应解析为 `UserTagsResponse`。

```python
from os import environ

from wechat_sdk.core.models import BaseResponse
from wechat_sdk.core.responses import response_parser
from wechat_sdk.official_account import OfficialAccountClient


class UserTagsResponse(BaseResponse):
    tagid_list: list[int]


with OfficialAccountClient(
    app_id=environ["WECHAT_APP_ID"], secret_id=environ["WECHAT_APP_SECRET"]
) as client:
    result = client.request(
        "POST",
        "/cgi-bin/tags/getidlist",
        json={"openid": environ["WECHAT_OPENID"]},
        result_processor=response_parser(UserTagsResponse),
    )
    print(result.tagid_list)
```

## 小程序

### 登录

小程序前端调用 `wx.login()` 并将取得的临时登录凭证发给服务端。下面用环境变量 `WECHAT_LOGIN_CODE` 传入这次请求的凭证。

```python
from os import environ

from wechat_sdk.miniapp import MiniAppClient

with MiniAppClient(
    app_id=environ["WECHAT_APP_ID"], secret_id=environ["WECHAT_APP_SECRET"]
) as client:
    session = client.user_login.code2session(environ["WECHAT_LOGIN_CODE"])
    openid = session.openid
    session_key = session.session_key
```

`openid` 标识该用户在当前小程序下的身份，`session_key` 供服务端校验用户会话。登录凭证只能使用一次。如果请求超时，请让前端重新调用 `wx.login()` 获取凭证。

### 支付、配送和回调

虚拟支付使用客户端的 `app_key`，B2B 账务使用 `b2b_app_key`，即时配送使用 `delivery_secrets={shopid: 配送密钥}`。接口需要用户态签名时，传入该用户的 `session_key`。

接收小程序事件时，在客户端配置消息推送的 `callback_token`。将原始请求体以及 URL 中的时间戳、随机串和签名交给 `client.callback.receive`，处理后用 `client.callback.reply` 应答。安全模式还需配置 `encoding_aes_key`。[小程序调用与回调示例](examples/miniapp.py)

## 公众号

订阅号和服务号均使用 `OfficialAccountClient`。可通过方法文档查看适用的账号类型和认证条件，例如 `help(client.custommenu.createcustommenu)`。

### 发送模板消息

已认证的服务号选用模板后，将接收用户的 OpenID、模板 ID 和模板数据传给 `sendtemplatemessage`。请将 `thing1` 换成所选模板的字段名。

```python
from os import environ

from wechat_sdk.official_account import OfficialAccountClient

with OfficialAccountClient(
    app_id=environ["WECHAT_APP_ID"], secret_id=environ["WECHAT_APP_SECRET"]
) as client:
    result = client.notify.template.sendtemplatemessage(
        touser=environ["WECHAT_OPENID"],
        template_id=environ["WECHAT_TEMPLATE_ID"],
        data={"thing1": {"value": "取件通知"}},
    )
    print(result.msgid)
```

### 素材与网页授权

使用 `client.notify.message.uploadimage(media)` 上传图文正文图片，可传入图片的文件路径或二进制流，图片须为小于 1 MiB 的 JPEG 或 PNG。从成功上传的响应中读取 `url`，即可在正文中引用图片。

通过 `client.webdev.access` 换取或刷新网页授权凭据后，客户端按 AppID 和 OpenID 保存用户凭据。调用 `client.webdev.access.snsuserinfo(openid)` 可读取该用户的资料。[草稿发布、用户分页和数据查询示例](examples/official_account.py)

## 微信小店接口

`StoreClient` 提供商家 `shop`、达人 `talent`、带货机构 `leagueheadsupplier` 和供货商 `supplier` 四个入口。每个客户端绑定一个调用账号，角色入口共用该账号的凭据。[接口清单和官方详情页](docs/store-api-inventory.md)

下面用达人账号查询一笔佣金单。列表里的 `order_id`、`sku_id` 和可选的 `special_id` 都按微信返回的原值传入详情接口。

```python
from os import environ

from wechat_sdk.store import StoreClient

with StoreClient(
    app_id=environ["WECHAT_TALENT_APP_ID"],
    secret_id=environ["WECHAT_TALENT_APP_SECRET"],
) as client:
    orders = client.talent.order
    page = orders.get_order_list(order_id=environ["WECHAT_ORDER_ID"], page_size=1)
    if page.order_list:
        item = page.order_list[0]
        if item.order_id and item.sku_id:
            detail = orders.get_order_detail(
                order_id=item.order_id, sku_id=item.sku_id, special_id=item.special_id
            )
```

## 微信支付

调用微信支付 API v2 时使用 `PayV2Client`，调用 API v3 时使用 `PayV3Client`。

普通商户可通过 V3 客户端创建 Native 订单，取得供用户扫码的 `code_url`。订单金额以分为单位。

```python
from os import environ

from wechat_sdk.pay import PayV3Client
from wechat_sdk.pay.sign import MerchantCredential, PlatformCredential

merchant = MerchantCredential.from_pem_files(
    "1230000109", "apiclient_cert.pem", "apiclient_key.pem"
)
platform = PlatformCredential.from_public_key_file("PUB_KEY_ID_...", "pub_key.pem")
with PayV3Client(app_id="wx...", merchant=merchant, platforms=[platform]) as client:
    transactions = client.transactions
    order = transactions.native.prepay(
        description="商品",
        out_trade_no=environ["WECHAT_ORDER_NO"],
        notify_url="https://merchant.example/pay/notify",
        amount={"total": 125},
    )
    code_url = order.code_url
```

用 `code_url` 生成二维码，供用户扫码支付。用原商户订单号调用 `client.transactions.get_order(out_trade_no=...)` 可查询支付状态。下单请求超时后也应先用原单号查单。

商户可同时配置多个可信的平台公钥或证书，客户端按响应头选择公钥验签。接口接收明文敏感字段，默认使用列表中的首个凭据加密，也可用 `wechatpay_serial` 指定加密凭据。[合单、退款、账单下载和支付回调示例](examples/pay.md)

## 返回值与异常

结构化响应可通过属性读取，也可用 `result.model_dump(exclude_unset=True)` 导出微信实际返回的字段。声明返回 `StatusResponse` 的操作接口在成功时返回该对象。下载小程序码、素材等文件时可直接读取返回的 `bytes`。

微信拒绝业务请求时，客户端直接抛出当前模块的异常，即使 HTTP 状态为 200。比如小程序登录失败可捕获 `wechat_sdk.miniapp.exceptions.MiniAppAPIError`，支付 V3 请求失败可捕获 `wechat_sdk.pay.exceptions.PayAPIError`。两者都提供 `errcode`、`errmsg` 和原始 HTTP 响应 `response`。可从 `wechat_sdk` 导入以下异常类型，或用 `ClientException` 统一捕获客户端异常。

| 异常 | 调用方可用的信息和处理方式 |
| --- | --- |
| `WeChatBusinessError` | 读取 `exc.errcode` 和 `exc.errmsg`，判断凭据无效、参数错误等业务原因。 |
| `WeChatNetworkError` | 连接中断或超时时，请求结果可能未知。涉及支付时，先查询交易状态。 |
| `WeChatSystemError` | 微信系统繁忙、响应格式异常或验签失败时，可读取 `exc.status_code` 和 `exc.message`。 |

入参不符合接口约束，或成功响应缺少模型必填字段时，会抛出 `pydantic.ValidationError`。支持 `max_retries` 的客户端默认不自动重试。启用后，仅允许重复发送的 GET、HEAD 请求会在遇到网络故障时自动重试。

## 凭据与通信加密

小程序、公众号、视频号和微信小店默认在客户端实例内缓存凭据。多个实例需要共用凭据时，可传入共享的 `token_store`。服务商代调用时，将授权方的凭据放入对应账号的凭据存储。

小程序、视频号和微信小店在创建业务 Client 时可通过 `encryption` 配置服务通信加密。下例中的 `aes_key` 为 Base64 解码后的 32 字节密钥，`app_private_key` 和 `platform_public_key` 为 RSA 密钥对象。

```python
with MiniAppClient(
    app_id=app_id,
    secret_id=app_secret,
    encryption={
        "key_serial": key_serial,
        "key": aes_key,
        "private_key": app_private_key,
        "platform_keys": {platform_serial: platform_public_key},
    },
) as client:
    phone = client.user_info.phone_number.getphonenumber(code)
```

支持服务通信加密的接口会自动加密请求并签名，收到响应后验签并解密。
