You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Stripe Payment Intent接口失败,请求排查逻辑问题

问题分析与修复建议

以下是代码中导致内部服务器错误的核心问题及对应修复方案:

  • 未定义变量触发运行时异常
    代码中application_fees被注释但仍在参数中引用,同时CaptureMethod.MANUAL既未定义也未导入,这两处都会直接抛出NameError中断执行:

    • 取消application_fees = int(0.1 * price)的注释,确保计算后的金额为最小货币单位(如美元用分),比如10美元的10%手续费需传100(对应1美元)。
    • 将CaptureMethod.MANUAL替换为字符串"manual",无需额外导入枚举,避免不必要的依赖。
  • 请求路径格式错误
    使用http.client.HTTPSConnection时,conn.request的第二个参数仅需传入API路径(/v1/payment_intents),而非完整URL。当前传入的完整URL会导致请求路径变为https://api.stripe.com/https://api.stripe.com/v1/payment_intents,完全不符合Stripe的API规范。

  • Stripe-Account头值错误
    Stripe-Account头需要传入Stripe连接账户ID(格式如acct_xxxxxx),而非艺术家的银行账户号码。银行账户号码用于创建连接账户的外部账户信息,不能直接作为连接账户的标识使用。

  • Amount参数单位风险
    Stripe的amount参数要求传入最小货币单位的整数(如美元用分),若你的price是美元浮点数(如10.99),需转换为int(price * 100)后再传入。

修复后的核心代码示例

import http.client
import urllib.parse

def create_payment_intent(customer_id, price, artist_stripe_account_id):
    # 转换价格为最小货币单位(分)
    amount_in_cents = int(price * 100)
    # 计算手续费(同样转为分)
    application_fees = int(0.1 * amount_in_cents)

    api_path = "/v1/payment_intents"

    try:
        parameters = {
            "amount": amount_in_cents,
            "currency": "usd",
            "customer": customer_id,
            "application_fee_amount": application_fees,
            "capture_method": "manual"  # 直接使用字符串替代未定义的枚举
        }
    
        request_body = urllib.parse.urlencode(parameters).encode('utf-8')
    
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer sk_test_你的实际测试密钥",  # 替换为有效密钥
            "Stripe-Account": artist_stripe_account_id  # 传入正确的连接账户ID
        }
    
        conn = http.client.HTTPSConnection("api.stripe.com")
        print("log-1")
        # 传递正确的API路径而非完整URL
        conn.request("POST", api_path, request_body, headers)
        print("log-2")
    
        response = conn.getresponse()
        response_data = response.read().decode('utf-8')
        print(response.status, response_data)
    
        return response_data, response.status

    except http.client.HTTPException as http_err:
        print("HTTP error occurred:", http_err)
        return str(http_err), 500
    except Exception as e:
        print("Error:", str(e))
        return str(e), 500

内容的提问来源于stack exchange,提问作者Shruti Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 17:05:55