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

如何用httr创建Stripe会话?Shiny支付流程开发报错求助

Fixing Stripe Checkout Session Creation with httr in R

Let's break down why you're hitting that error and how to fix it. The issue comes down to how httr encodes nested lists and array parameters when using encode = "form"—Stripe's API expects specific formatting for arrays and nested objects that your current code isn't producing.

Key Issues in Your Original Code:

  1. payment_method_types needs to be an array: In the curl example, you're using payment_method_types[]=card which tells Stripe this is an array. Your code passes a single string "card", which httr encodes as a scalar value instead of an array element.
  2. subscription_data$items must be an array of objects: Stripe expects items to be an array (even with one item), but your code passes a single list list(plan = "plan_XX") instead of a list containing that object. This causes the encoding mismatch that triggers your error.

Corrected Code

Here's the fixed version that properly formats all parameters for Stripe's API:

library(httr)

response <- httr::POST(
  url = "https://api.stripe.com/v1/checkout/sessions",
  config = httr::add_headers(
    Authorization = paste("Bearer", Sys.getenv("stripe_key"))
  ),
  body = list(
    success_url = "https://example.com/success",
    cancel_url = "https://example.com/cancel",
    # Encode as array by wrapping in a list
    payment_method_types = list("card"),
    subscription_data = list(
      # Items must be an array of objects (nested list)
      items = list(
        list(plan = "plan_XX")
      ),
      trial_period_days = 7
    )
  ),
  encode = "form"
)

# Check the response to confirm success
httr::content(response)

Why This Works:

  • payment_method_types = list("card"): When using encode = "form", wrapping the value in a list tells httr to encode it as an array parameter (matching the curl payment_method_types[]=card syntax).
  • items = list(list(plan = "plan_XX")): This creates an array containing one object with the plan key. httr will encode this correctly as subscription_data[items][0][plan]=plan_XX, which aligns with what Stripe's API expects for subscription line items.

If you need to add multiple plans to items, just extend the outer list:

items = list(
  list(plan = "plan_XX"),
  list(plan = "plan_YY")
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:54:36