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

如何用Python创建Stripe Payment Link?解决模块导入失败问题

问题描述

需要用Python通过Stripe API创建可长期有效(至少1个月)的Payment Link嵌入发票,替代有效期短且必须指定成功/取消URL的Checkout Session。现有Checkout Session代码可正常运行,但尝试使用Payment Link时,尽管本地stripe文件夹有payment_link.py模块,PyCharm中仍显示导入失败,无法正常运行代码。已查阅Stripe官方Payment Link相关API文档。

可正常运行的Checkout Session代码:

import stripe
stripe.api_key = 'my_stripe_key'

def add_price_to_product(
        product_id,
        price
):
    price = stripe.Price.create(
        unit_amount=price,
        currency='eur',
        product=product_id,
        recurring=None,
    )

    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'price': price.id,
            'quantity': 1,
        }],
        mode='payment',
        success_url='https://large-type.com/#Successful%20payment%2C%20have%20a%20nice%20day!',
        cancel_url='https://large-type.com/#Payment%20cancelled%2C%20try%20again.'
    )

    return session.url

print(add_price_to_product(product_id='prod_XXXXXXX', price=1554))

尝试使用的Payment Link代码:

import stripe
stripe.api_key = 'my_stripe_key'

def add_price_to_product(
        product_id,
        price
):
    price = stripe.Price.create(
        unit_amount=price,
        currency='eur',
        product=product_id,
        recurring=None,
    )

    payment_link = stripe.PaymentLink.create(
        line_items=[{
            'price': price.id,
            'quantity': 1,
        }],
    )

    return payment_link.url

print(add_price_to_product(product_id='prod_XXXXXXX', price=1554))
解决方法

1. 升级Stripe Python SDK

导入失败的核心原因是使用的Stripe SDK版本过低,Payment Link是较新的API功能,旧版本SDK未封装该接口。执行以下命令升级:

pip install --upgrade stripe

2. 优化Payment Link代码

升级SDK后,原代码的调用逻辑是正确的,还可以补充可选参数优化付款完成后的体验(无需指定外部成功/取消URL,Payment Link默认会处理跳转逻辑):

import stripe
stripe.api_key = 'my_stripe_key'

def create_payment_link(product_id, price):
    price = stripe.Price.create(
        unit_amount=price,
        currency='eur',
        product=product_id,
        recurring=None,
    )

    payment_link = stripe.PaymentLink.create(
        line_items=[{
            'price': price.id,
            'quantity': 1,
        }],
        # 自定义付款完成后的提示信息,替代外部URL
        after_completion={
            'type': 'message',
            'message': {
                'body': '付款成功!感谢您的支持。'
            }
        }
    )

    return payment_link.url

print(create_payment_link(product_id='prod_XXXXXXX', price=1554))

3. 验证导入状态

升级SDK后,在PyCharm中重新加载项目依赖(可通过File → Invalidate Caches...刷新缓存),即可正常识别stripe.PaymentLink类,导入错误提示会消失。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:26:01