如何用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:
payment_method_typesneeds to be an array: In the curl example, you're usingpayment_method_types[]=cardwhich tells Stripe this is an array. Your code passes a single string"card", whichhttrencodes as a scalar value instead of an array element.subscription_data$itemsmust be an array of objects: Stripe expectsitemsto be an array (even with one item), but your code passes a single listlist(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 usingencode = "form", wrapping the value in a list tellshttrto encode it as an array parameter (matching the curlpayment_method_types[]=cardsyntax).items = list(list(plan = "plan_XX")): This creates an array containing one object with theplankey.httrwill encode this correctly assubscription_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
相关产品推荐
相关产品推荐

