如何在Disnake Discord机器人中集成YooKassa v3实现支付创建与状态查询?
问题解决步骤与可运行代码
1. 捕获完整错误响应体
YooKassa抛出的ApiError异常包含完整的响应详情,只需捕获该异常并解析响应内容,就能明确400错误的具体原因:
import yookassa from yookassa import ApiError try: # 你的支付创建逻辑 payment = yookassa.Payment.create(...) except ApiError as e: # 打印完整错误信息 print("错误详情:", e.response.json()) raise
2. 适配disnake的完整可运行代码
初始化配置
import disnake from disnake.ext import commands import yookassa # 配置YooKassa账户信息 yookassa.Configuration.account_id = "你的YooKassa账户ID" yookassa.Configuration.secret_key = "你的YooKassa密钥" # 初始化Discord机器人 bot = commands.Bot(command_prefix="!", intents=disnake.Intents.all())
创建支付命令
@bot.slash_command(name="create_payment", description="生成YooKassa支付链接") async def create_payment(inter: disnake.ApplicationCommandInteraction, amount: int, description: str): try: payment_params = { "amount": { "value": f"{amount}.00", # 金额必须为带两位小数的字符串格式 "currency": "RUB" # 按需更换支持的币种,如USD、EUR }, "confirmation": { "type": "redirect", "return_url": "https://你的回调域名/return" # 需为合法HTTPS地址,本地测试可用ngrok生成临时地址 }, "description": description[:128], # 描述长度限制128字符 "metadata": { "user_id": inter.user.id, "guild_id": inter.guild.id } } # 创建支付订单 payment = yookassa.Payment.create(payment_params) await inter.response.send_message(f"支付链接:{payment.confirmation.confirmation_url}", ephemeral=True) except yookassa.ApiError as e: error_info = e.response.json() await inter.response.send_message(f"创建失败:{error_info['message']}\n详情:{error_info['description']}", ephemeral=True)
查询支付状态命令
@bot.slash_command(name="check_payment", description="查询支付订单状态") async def check_payment(inter: disnake.ApplicationCommandInteraction, payment_id: str): try: payment = yookassa.Payment.find_one(payment_id) status = payment.status amount = f"{payment.amount.value} {payment.amount.currency}" user_id = payment.metadata.get("user_id", "未知") await inter.response.send_message( f"支付ID:{payment_id}\n状态:{status}\n金额:{amount}\n关联用户:{user_id}", ephemeral=True ) except yookassa.ApiError as e: error_info = e.response.json() await inter.response.send_message(f"查询失败:{error_info['message']}\n详情:{error_info['description']}", ephemeral=True) # 启动机器人 bot.run("你的Discord机器人Token")
3. 常见400错误排查点
- 参数格式问题:金额必须是带两位小数的字符串(如
"99.00"),不能直接传整数;币种需为YooKassa支持的代码。 - 回调地址无效:
return_url必须是HTTPS协议的合法地址,不能用HTTP或本地IP。 - 账户权限问题:确认
account_id和secret_key是否正确,且账户已开启API调用权限。 - 描述内容违规:
description不能包含敏感词,长度不能超过128字符。
内容的提问来源于stack exchange,提问作者L1te
相关产品推荐
相关产品推荐

