Skip to main content

微信公众号发布服务 Python SDK

Project description

WeChat Publish SDK

微信公众号发布服务的 Python SDK,提供稳定、易用的 API 接口。

后端服务 wechat-publish-service 已部署在 yyps.net,统一接入 ai-as.cc OIDC 认证中台。

特性

  • M2M 双认证 — API Key(X-API-Key,推荐)或 OIDC(Authorization: Bearerclient_credentials
  • 类型安全 — 完整类型注解,IDE 提示友好
  • 自动 OIDC 刷新 — token 过期前自动刷新,线程安全
  • 统一异常体系 — 清晰的错误处理
  • 默认账号 — 设置 default_account 后无需每次传 account

安装

pip install wechat-publish-sdk

快速开始

方式一:API Key(推荐)

从 ai-as.cc 申请 API Key,service 侧通过 ai-as.cc /api/keys/validate 验证,一行配置即可。

from wechat_publish_sdk import WeChatClient, PublishRequest

client = WeChatClient(
    base_url="https://yyps.net",
    api_key="sk_live_xxx",          # 从 ai-as.cc 申请
    default_account="mingdeng",
)

result = client.publish_article(
    PublishRequest(title="测试文章", content="# 这是测试内容")
)
if result.success:
    print(f"发布成功,draft_id: {result.draft_id}")

方式二:OIDC(client_credentials

适合需要标准 OAuth2 token 的场景。SDK 内置 OIDC 客户端,自动 discovery + 刷新。

from wechat_publish_sdk import WeChatClient, PublishRequest, OIDCConfig

client = WeChatClient(
    base_url="https://yyps.net",
    oidc=OIDCConfig(
        client_id="your_client_id",
        client_secret="your_client_secret",
        # issuer 默认即 https://auth.ai-as.cc
    ),
    default_account="mingdeng",
)

result = client.publish_article(
    PublishRequest(title="测试文章", content="# 内容")
)

前置条件:OIDC Bearer 端到端生效依赖 service 侧 /api/mp/publish 支持 Bearer 认证。

上传素材

from wechat_publish_sdk import UploadRequest

upload = client.upload_image(UploadRequest(file_path="path/to/cover.jpg"))
if upload.success:
    media_id = upload.media_id

查询素材列表

result = client.list_materials(material_type="image", offset=0, count=20)
if result.success:
    for item in result.items:
        print(f"  - {item.name}: {item.url}")

Markdown 渲染

from wechat_publish_sdk import RenderRequest

result = client.render_markdown(
    RenderRequest(content="# 标题\n\n内容", theme="orange")
)
if result.success:
    print(result.html)

认证说明

SDK 定位 M2M(机器对机器),提供两条并行认证路径,均对接 ai-as.cc,二选一:

方式 入参 请求头 service 侧验证
API Key(推荐) api_key X-API-Key 调 ai-as.cc /api/keys/validate
OIDC oidc=OIDCConfig(...) Authorization: Bearer 本地 JWKS 验签(RS256)
签名(已废弃) signing_key service 已不校验,传入会触发 DeprecationWarning

配置说明

环境变量(推荐)

WECHAT_PUBLISH_URL=https://yyps.net
API_KEY=sk_live_xxx
# 或使用 OIDC
OIDC_CLIENT_ID=...
OIDC_CLIENT_SECRET=...
DEFAULT_ACCOUNT=mingdeng
import os
from wechat_publish_sdk import WeChatClient, OIDCConfig

client = WeChatClient(
    base_url=os.getenv("WECHAT_PUBLISH_URL"),
    api_key=os.getenv("API_KEY"),
    # 或 oidc=OIDCConfig(os.environ["OIDC_CLIENT_ID"], os.environ["OIDC_CLIENT_SECRET"]),
    default_account=os.getenv("DEFAULT_ACCOUNT"),
)

客户端参数

参数 类型 必填 说明
base_url str 后端服务地址,如 https://yyps.net
api_key str 三选一 API Key
oidc OIDCConfig 三选一 OIDC 配置
signing_key str 三选一 已废弃
default_account str 默认账号
api_version str API 版本,默认 v1
timeout int 请求超时(秒),默认 30

异常处理

from wechat_publish_sdk import (
    WeChatClient, PublishRequest,
    ValidationError, AccountNotFoundError, PublishFailedError, WeChatPublishError,
)

try:
    result = client.publish_article(PublishRequest(...))
except ValidationError as e:
    print(f"参数错误: {e}")
except AccountNotFoundError as e:
    print(f"账号不存在: {e}")
except PublishFailedError as e:
    print(f"发布失败: {e}")
except WeChatPublishError as e:
    print(f"其他错误: {e}")

安全建议

⚠️ 重要安全注意事项:

  1. 不要硬编码密钥:永远不要在代码中硬编码 api_key / client_secret
  2. 使用环境变量:通过 .env 文件或系统环境变量管理凭据
  3. 保护 .env 文件:确保 .env 已加入 .gitignore(本仓库已配置)
  4. 生产环境:使用密钥管理服务(AWS Secrets Manager、HashiCorp Vault)

开发

git clone https://github.com/helloworldtang/wechat-publish-sdk.git
cd wechat-publish-sdk
pip install -e ".[dev]"

pytest            # 单元测试
python -m build   # 构建产物
black src/        # 格式化
mypy src/         # 类型检查

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wechat_publish_sdk-1.1.0.tar.gz (14.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

wechat_publish_sdk-1.1.0-py3-none-any.whl (13.0 kB view details)

Uploaded Python 3

File details

Details for the file wechat_publish_sdk-1.1.0.tar.gz.

File metadata

  • Download URL: wechat_publish_sdk-1.1.0.tar.gz
  • Upload date:
  • Size: 14.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for wechat_publish_sdk-1.1.0.tar.gz
Algorithm Hash digest
SHA256 f89b0210c367480738e7f714b8afeb42b828171ecdecbadbeff29b21ed8216ce
MD5 05b0ce6682b4f088ff92a63427ebde92
BLAKE2b-256 97b1370d76fb74cb63ba66fd9eafdc79354065cce2d9ec0fa8a08a69dc180bd1

See more details on using hashes here.

Provenance

The following attestation bundles were made for wechat_publish_sdk-1.1.0.tar.gz:

Publisher: publish.yml on helloworldtang/wechat-publish-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file wechat_publish_sdk-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for wechat_publish_sdk-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 62401d45a5050aa83cb2bd5f99232ab0a9c9cc6900696e13f1d3ad87136bb47f
MD5 12602251d459e302fc7011385baea31a
BLAKE2b-256 d46c1769df6264d16d6c5a3720d286f41909cf33a54d4ed166aacb006f5d73fa

See more details on using hashes here.

Provenance

The following attestation bundles were made for wechat_publish_sdk-1.1.0-py3-none-any.whl:

Publisher: publish.yml on helloworldtang/wechat-publish-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page