【问题标题】:How do I download PDF invoices from stripe.com for previous year?如何从 stripe.com 下载上一年的 PDF 发票?
【发布时间】:2023-02-20 01:17:02
【问题描述】:

出于会计目的,我需要从 stripe.com 下载过去一年的所有发票。我没有找到那个按钮,当我联系 stripe.com 支持时,他们说这是不可能的,如果可以的话我应该使用 API。

我找到了this page,但没有用。我不想花那么多时间在上面,因为我确信这是一个常见的用例,以及金融科技独角兽为什么不支持这个简单的用例。好吧,所以我为此编写了一个 Python 脚本并在此处共享。因为我花了一些时间在上面,所以我在这里分享它,希望对其他人也有用。

【问题讨论】:

    标签: python stripe-payments invoice


    【解决方案1】:

    这些是创建新的 Stripe API Key 的步骤:

    • 登录您的Stripe dashboard
    • 转到API Keys 部分。
    • 单击“创建密钥”或“创建受限密钥”(推荐)。
      • 如果您选择使用受限密钥,请选择Invoices -> Read 权限。 点击保存,复制密钥并将其粘贴到STRIPE_KEY
    import os
    import arrow
    import requests
    
    STRIPE_KEY = "{digrin.com}"
    SAVE_PATH = "./Invoices/"
    
    import stripe
    
    
    def get_invoices(year):
        last_item_id = None
        result = []
        while True:
            invoices = stripe.Invoice.list(
                api_key=STRIPE_KEY,
                status='paid',
                created={'gte': int(arrow.get(f"{year}-01-01").timestamp()), 'lte': int(arrow.get(f"{year}-12-31 23:59").timestamp())},
                limit=100,
                starting_after=last_item_id,
            )
            for invoice in invoices['data']:
                result.append({"number": invoice['number'], "url": invoice['invoice_pdf']})
    
            if not invoices['data']:
                break
            last_item_id = invoices['data'][-1]['id']
        return result
    
    
    if __name__ == "__main__":
    
        invoices = get_invoices(2022)
        print(f"There are {len(invoices)} invoices.")
        for invoice in invoices:
            with open(f"{SAVE_PATH}{invoice['number']}.pdf", "wb") as f:
                f.write(requests.get(invoice['url']).content)
                print(f"Saved file {invoice['number']}.pdf")
    
        # check count
        file_list = os.listdir(SAVE_PATH)
        pdf_list = [file for file in file_list if file.endswith(".pdf")]
        if len(pdf_list) != len(invoices):
            print(f"WARNING: There are {len(invoices)} invoices but {len(pdf_list)} pdf files in the directory.")
        else:
            print(f"There are {len(pdf_list)} files in the directory, matches stripe response.")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多