Fastapi Alipay Pay Skill 标志

Fastapi Alipay Pay Skill

社区
jiushiwon
fastapi-alipay-pay-skill

FastAPI 支付宝模块技能(独立版)。面向已有 FastAPI 项目,提供支付宝完整能力:当面付/扫码、手机网站支付(WAP)、PC 网站支付、App 支付、退款、回调验签、订单查询、关单。**不包含微信支付**,如需微信请引入 fastapi-wechat-pay-skill。触发词:"支付宝"、"当面付"、"扫码支付"、"手机网站支付"、"WAP支付"、"PC支付"、"APP支付"、"支付宝退款"、"支付宝回调"、"alipay"、"RSA2验签"。

概览

发布者jiushiwon
代码仓库wg-skills
技能名称fastapi-alipay-pay-skill
星标数
123
复刻数
38
附带文件
3
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 3 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 jiushiwon 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Fastapi Alipay Pay Skill AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/fastapi-alipay-pay-skill
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/jiushiwon/wg-skills.git /tmp/wg-skills
mkdir -p .claude/skills
cp -r /tmp/wg-skills/vibeCoding/backend/python/fastapi-module/fastapi-alipay-pay-skill .claude/skills/fastapi-alipay-pay-skill
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Fastapi Alipay Pay Skill,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Fastapi Alipay Pay Skill。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Fastapi Alipay Pay Skill 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

FastAPI Alipay Module Skill

支付宝独立模块,只覆盖支付宝渠道。Python FastAPI 实现。

与合一版的关系

Skill范围推荐度
fastapi-alipay-pay-skill(本)仅支付宝⭐⭐⭐⭐⭐ 单一渠道
fastapi-wechat-pay-skill仅微信 V3⭐⭐⭐⭐⭐ 单一渠道
fastapi-payment-module-skill微信+支付宝合一旧版,已不推荐

能力清单

能力适用场景接口
当面付线下扫码 / 收银台POST /api/alipay/precreate
手机网站支付移动端浏览器 H5POST /api/alipay/wap
PC 网站支付PC 浏览器POST /api/alipay/page
App 支付iOS / Android AppPOST /api/alipay/app
退款全场景通用POST /api/alipay/refund
查询订单全场景通用GET /api/alipay/query/{order_no}
关单全场景通用POST /api/alipay/close/{order_no}
对账单下载财务对账GET /api/alipay/bill
回调验签全场景通用POST /api/alipay/notify

前置依赖

依赖说明
fastapi-init-skill项目骨架(必须)
fastapi-auth-module-skill当前用户获取(推荐)
python-redis-module-skill幂等防重 + 限流(推荐)

核心实现

1. 依赖

bash
# 支付宝官方 Python SDK
pip install python-alipay-sdk

# 或新版 pycryptodome(签名需要)
pip install pycryptodome

2. 配置(config.py)

python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    # ====== 必填项:从开放平台获取 ======
    alipay_app_id: str = "2021000000000000"           # 16 位 APPID
    alipay_private_key: str = ""                       # 应用私钥(PEM PKCS8,含 BEGIN/END 头)
    alipay_public_key: str = ""                        # 支付宝公钥(**不是应用公钥**)

    # ====== 业务地址 ======
    alipay_gateway: str = "https://openapi.alipay.com/gateway.do"
    alipay_sandbox_gateway: str = "https://openapi.alipaydev.com/gateway.do"
    alipay_notify_url: str = "https://yourdomain.com/api/alipay/notify"
    alipay_return_url: str = "https://yourdomain.com/pay/return"

    # ====== 可选 ======
    alipay_sign_type: str = "RSA2"                     # 固定 RSA2
    alipay_charset: str = "UTF-8"
    alipay_format: str = "json"
    alipay_debug: bool = False

    class Config:
        env_file = ".env"

settings = Settings()

3. 数据模型(models.py)

python
import enum
from sqlalchemy import Column, BigInteger, String, DateTime, Enum as SQLEnum, Numeric, Text
from sqlalchemy.sql import func
from database import Base


class PayScene(str, enum.Enum):
    PRECREATE = "PRECREATE"   # 当面付
    WAP = "WAP"               # 手机网站
    PAGE = "PAGE"             # PC 网站
    APP = "APP"               # App 支付


class PayStatus(str, enum.Enum):
    PENDING = "PENDING"
    PAID = "PAID"
    CLOSED = "CLOSED"
    REFUNDED = "REFUNDED"


class RefundStatus(str, enum.Enum):
    PENDING = "PENDING"
    SUCCESS = "SUCCESS"
    FAILED = "FAILED"


class AlipayPayOrder(Base):
    __tablename__ = "wg_alipay_pay_order"
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    order_no = Column(String(64), unique=True, nullable=False, index=True)
    trade_no = Column(String(64), comment="支付宝交易号")
    scene = Column(SQLEnum(PayScene))
    status = Column(SQLEnum(PayStatus), default=PayStatus.PENDING)
    # 金额单位:元(BigDecimal 对应 Python Decimal / Numeric)
    amount = Column(Numeric(10, 2), nullable=False)
    subject = Column(String(200))
    qr_code = Column(Text, comment="当面付二维码内容")
    paid_at = Column(DateTime)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())


class AlipayRefundOrder(Base):
    __tablename__ = "wg_alipay_refund_order"
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    refund_no = Column(String(64), unique=True, nullable=False)
    order_no = Column(String(64), nullable=False, index=True)
    refund_id = Column(String(64), comment="支付宝退款单号")
    refund_amount = Column(Numeric(10, 2), nullable=False)
    total_amount = Column(Numeric(10, 2), nullable=False)
    status = Column(SQLEnum(RefundStatus), default=RefundStatus.PENDING)
    reason = Column(String(200))
    refunded_at = Column(DateTime)
    created_at = Column(DateTime, server_default=func.now())

4. 服务层(核心)

python
# services/alipay_pay_service.py
from decimal import Decimal
from datetime import datetime
from typing import Optional

from sqlalchemy.orm import Session
from alipay import AliPay

from config import settings
from models import AlipayPayOrder, AlipayRefundOrder, PayStatus, RefundStatus, PayScene
from common.exceptions import BusinessException


class AlipayPayService:
    def __init__(self, db: Session):
        self.db = db
        self._client: Optional[AliPay] = None

    def _get_client(self) -> AliPay:
        if self._client is None:
            self._client = AliPay(
                appid=settings.alipay_app_id,
                app_notify_url=settings.alipay_notify_url,
                app_private_key_string=settings.alipay_private_key,
                alipay_public_key_string=settings.alipay_public_key,
                sign_type=settings.alipay_sign_type,  # RSA2
                debug=settings.alipay_debug,
            )
        return self._client

    # ============== 统一下单 ==============

    def precreate(self, order_no: str, amount: Decimal, subject: str) -> str:
        """当面付(生成二维码)"""
        if self.db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first():
            raise BusinessException(-3004, "订单号已存在")

        try:
            qr_code = self._get_client().api_alipay_trade_precreate(
                out_trade_no=order_no,
                total_amount=str(amount),
                subject=subject,
                notify_url=settings.alipay_notify_url,
            )
        except Exception as e:
            raise BusinessException(-3001, f"当面付预创建失败: {e}")

        order = AlipayPayOrder(
            order_no=order_no, scene=PayScene.PRECREATE,
            amount=amount, subject=subject,
            qr_code=qr_code, status=PayStatus.PENDING,
        )
        self.db.add(order)
        self.db.commit()
        return qr_code

    def wap_pay(self, order_no: str, amount: Decimal, subject: str) -> str:
        """手机网站支付(返回 form HTML)"""
        try:
            form_html = self._get_client().api_alipay_trade_wap_pay(
                out_trade_no=order_no,
                total_amount=str(amount),
                subject=subject,
                return_url=settings.alipay_return_url,
                notify_url=settings.alipay_notify_url,
                product_code="QUICK_WAP_WAY",
            )
        except Exception as e:
            raise BusinessException(-3001, f"WAP 支付失败: {e}")

        self._persist(order_no, PayScene.WAP, amount, subject)
        return form_html

    def page_pay(self, order_no: str, amount: Decimal, subject: str) -> str:
        """PC 网站支付(返回 form HTML,浏览器自动跳转)"""
        try:
            form_html = self._get_client().api_alipay_trade_page_pay(
                out_trade_no=order_no,
                total_amount=str(amount),
                subject=subject,
                return_url=settings.alipay_return_url,
                notify_url=settings.alipay_notify_url,
            )
        except Exception as e:
            raise BusinessException(-3001, f"PC 支付失败: {e}")

        self._persist(order_no, PayScene.PAGE, amount, subject)
        return form_html

    def app_pay(self, order_no: str, amount: Decimal, subject: str) -> str:
        """App 支付(返回 orderStr,App 端用 SDK 调起)"""
        try:
            order_str = self._get_client().api_alipay_trade_app_pay(
                out_trade_no=order_no,
                total_amount=str(amount),
                subject=subject,
                notify_url=settings.alipay_notify_url,
                product_code="QUICK_MSECURITY_PAY",
            )
        except Exception as e:
            raise BusinessException(-3001, f"App 支付失败: {e}")

        self._persist(order_no, PayScene.APP, amount, subject)
        return order_str

    def _persist(self, order_no: str, scene: PayScene, amount: Decimal, subject: str):
        if self.db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first():
            raise BusinessException(-3004, "订单号已存在")
        order = AlipayPayOrder(
            order_no=order_no, scene=scene,
            amount=amount, subject=subject, status=PayStatus.PENDING,
        )
        self.db.add(order)
        self.db.commit()

    # ============== 退款 ==============

    def refund(self, order_no: str, refund_no: str, refund_amount: Decimal, reason: str = "") -> dict:
        order = self.db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first()
        if not order:
            raise BusinessException(-3003, "原订单不存在")
        if order.status != PayStatus.PAID:
            raise BusinessException(-3005, "订单未支付")
        if refund_amount > order.amount:
            raise BusinessException(-3005, "退款金额超限")

        ro = AlipayRefundOrder(
            refund_no=refund_no, order_no=order_no,
            refund_amount=refund_amount, total_amount=order.amount,
            reason=reason, status=RefundStatus.PENDING,
        )
        self.db.add(ro)
        self.db.commit()

        try:
            result = self._get_client().api_alipay_trade_refund(
                out_trade_no=order_no,
                refund_amount=str(refund_amount),
                out_request_no=refund_no,
                refund_reason=reason,
            )
            if result.get("code") == "10000":
                return {"refundNo": refund_no, "status": "PROCESSING"}
            ro.status = RefundStatus.FAILED
            self.db.commit()
            raise BusinessException(-3005, f"退款失败: {result.get('sub_msg')}")
        except BusinessException:
            raise
        except Exception as e:
            ro.status = RefundStatus.FAILED
            self.db.commit()
            raise BusinessException(-3005, f"退款异常: {e}")

    # ============== 查询 / 关单 ==============

    def query_order(self, order_no: str) -> AlipayPayOrder:
        order = self.db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first()
        if not order:
            raise BusinessException(-3003, "订单不存在")
        return order

    def close_order(self, order_no: str) -> None:
        order = self.db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first()
        if not order:
            raise BusinessException(-3003, "订单不存在")

        try:
            result = self._get_client().api_alipay_trade_close(
                out_trade_no=order_no,
            )
            if result.get("code") == "10000":
                order.status = PayStatus.CLOSED
                self.db.commit()
            else:
                raise BusinessException(-3006, f"关单失败: {result.get('sub_msg')}")
        except BusinessException:
            raise
        except Exception as e:
            raise BusinessException(-3006, f"关单异常: {e}")

5. 路由

python
# routers/alipay_pay.py
from decimal import Decimal
from fastapi import APIRouter, Depends, Request, Form
from sqlalchemy.orm import Session

from database import get_db
from services.alipay_pay_service import AlipayPayService
from common.response import ApiResponse

router = APIRouter(prefix="/api/alipay", tags=["支付宝"])


@router.post("/precreate")
def precreate(order_no: str, amount: Decimal, subject: str, db: Session = Depends(get_db)):
    qr_code = AlipayPayService(db).precreate(order_no, amount, subject)
    return ApiResponse.ok({"qrCode": qr_code})


@router.post("/wap")
def wap(order_no: str, amount: Decimal, subject: str, db: Session = Depends(get_db)):
    html = AlipayPayService(db).wap_pay(order_no, amount, subject)
    return ApiResponse.ok({"formHtml": html})


@router.post("/page")
def page(order_no: str, amount: Decimal, subject: str, db: Session = Depends(get_db)):
    html = AlipayPayService(db).page_pay(order_no, amount, subject)
    return ApiResponse.ok({"formHtml": html})


@router.post("/app")
def app(order_no: str, amount: Decimal, subject: str, db: Session = Depends(get_db)):
    order_str = AlipayPayService(db).app_pay(order_no, amount, subject)
    return ApiResponse.ok({"orderStr": order_str})


@router.post("/refund")
def refund(order_no: str, refund_no: str, refund_amount: Decimal, reason: str = "", db: Session = Depends(get_db)):
    return ApiResponse.ok(AlipayPayService(db).refund(order_no, refund_no, refund_amount, reason))


@router.get("/query/{order_no}")
def query(order_no: str, db: Session = Depends(get_db)):
    return ApiResponse.ok(AlipayPayService(db).query_order(order_no))


@router.post("/close/{order_no}")
def close(order_no: str, db: Session = Depends(get_db)):
    AlipayPayService(db).close_order(order_no)
    return ApiResponse.ok()


@router.post("/notify")
async def notify(request: Request, db: Session = Depends(get_db)):
    """支付宝回调(form 表单 POST)"""
    from config import settings
    form = await request.form()
    data = dict(form)

    # 验签(SDK 内部完成)
    from alipay import AliPay
    alipay = AliPay(
        appid=settings.alipay_app_id,
        app_notify_url=None,
        app_private_key_string=settings.alipay_private_key,
        alipay_public_key_string=settings.alipay_public_key,
        sign_type=settings.alipay_sign_type,
    )

    if not alipay.verify(data, data.pop("sign")):
        # 验签失败返回 fail
        from fastapi.responses import PlainTextResponse
        return PlainTextResponse("fail", status_code=400)

    order_no = data.get("out_trade_no")
    trade_no = data.get("trade_no")
    trade_status = data.get("trade_status")

    order = db.query(AlipayPayOrder).filter(AlipayPayOrder.order_no == order_no).first()
    if order:
        if trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            order.status = PayStatus.PAID
            order.trade_no = trade_no
            order.paid_at = datetime.now()
        elif trade_status == "TRADE_CLOSED":
            order.status = PayStatus.CLOSED
        db.commit()

    # 必须返回纯文本 "success"(小写无空格)
    from fastapi.responses import PlainTextResponse
    return PlainTextResponse("success")

关键踩坑

坑现象解决
验签失败回调报 INVALID_SIGN用的是应用公钥,换成支付宝公钥
App 支付无反应报 INVALID_PARAMETERproduct_code 必须填 QUICK_MSECURITY_PAY
私钥格式错ValueError: Could not deserialize必须 PKCS8(PEM 头是 -----BEGIN PRIVATE KEY-----)
当面付返回的 code_url 不到账没有扫码买家账号必须用沙箱 App登录
沙箱 404网关用错沙箱用 openapi.alipaydev.com
Decimal 精度0.1 + 0.2 = 0.30000000000004用 Decimal(str(amount)) 不用 float

不做

  • ❌ 商户号开通(参考 merchant-onboarding.md)
  • ❌ 密钥生成(参考同上)
  • ❌ UI 组件
  • ❌ 微信支付(独立 skill)

触发场景

  • 「帮我加支付宝(Python 版)」
  • 「FastAPI 集成当面付 / WAP / App 支付」
  • 「做支付宝退款」
  • 「配置支付宝 RSA2 签名」

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Fastapi Alipay Pay Skill AI 技能有什么作用?

FastAPI 支付宝模块技能(独立版)。面向已有 FastAPI 项目,提供支付宝完整能力:当面付/扫码、手机网站支付(WAP)、PC 网站支付、App 支付、退款、回调验签、订单查询、关单。**不包含微信支付**,如需微信请引入 fastapi-wechat-pay-skill。触发词:"支付宝"、"当面付"、"扫码支付"、"手机网站支付"、"WAP支付"、"PC支付"、"APP支付"、"支付宝退款"、"支付宝回调"、"alipay"、"RSA2验签"。

为什么在 TypingMind 中使用 Fastapi Alipay Pay Skill?

因为您只需安装一次,就能搭配任何模型使用。Fastapi Alipay Pay Skill 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Fastapi Alipay Pay Skill?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/fastapi-alipay-pay-skill。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Fastapi Alipay Pay Skill?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Fastapi Alipay Pay Skill 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Fastapi Alipay Pay Skill 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Fastapi Alipay Pay Skill AI 技能免费吗?

是的。jiushiwon 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇