Body format for Stripe POST operations

Viewed 9722

I'm accessing the stripe API directly with the REST API (not using a library) but, surprisingly, I can't find documentation on the appropriate body format post data.

Does Stripe expect JSON or form-encoded pairs?

4 Answers

Here is the sample of the curl code to Nodejs I am working on a similar problem

as you know we can't send JSON for the "post" method it must be URL encoded

here is the sample provided by stripe https://stripe.com/docs/api/checkout/sessions/create

curl https://api.stripe.com/v1/checkout/sessions \
>   -u stripe_key_here: \
>   -d success_url="https://example.com/success" \
>   -d cancel_url="https://example.com/cancel" \
>   -d "payment_method_types[]=card" \
>   -d "line_items[][name]=T-shirt" \
>   -d "line_items[][description]=Comfortable cotton t-shirt" \
>   -d "line_items[][amount]=1500" \
>   -d "line_items[][currency]=usd" \
>   -d "line_items[][quantity]=2"

-u means authorization which we provide in the headers
-d means body of the url

sample code in node js


const fetch = require("node-fetch");
const stripeKey = process.env.STRIPE_KEY;

async function getCheckoutID() {
  try {
    const endpoint = "https://api.stripe.com/v1/checkout/sessions";

    const query = objToQuery({
      success_url: "https://example.com/success",
      cancel_url: "https://example.com/cancel",
      "payment_method_types[]": "card",
      "line_items[][name]": "T-shirt",
      "line_items[][description]": "Comfortable cotton t-shirt",
      "line_items[][amount]": 1500,
      "line_items[][quantity]": 1,
      "line_items[][currency]": "usd"
    });

    // enpoint => "https://www.domin.com/api"
    // query => "?key=value&key1=value1"
    const URL = `${endpoint}${query}`;

    const fetchOpts = {
      method: "post",
      headers: {
        "Authorization": `Bearer ${stripeKey}`,
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }
    const checkout = await getJSON(URL, fetchOpts);

    console.log("CHECKOUT OBJECT : " , checkout);

    return checkout;
  }
  catch(e) {
      console.error(e);
   }
}


// hepler functions

// instead of using fetch
// getJSON will make it readable code
async function getJSON(url, options) {
  const http = await fetch(url, options);
  if (!http.ok) {
    console.log(http);
    throw new Error("ERROR STATUS IS NOT OK :");
  }
  return http.json();
}

// convert JS object to url query
// {key:"value" , key1: "value1"} to "key=value&key1=value1"
function objToQuery(obj) {
  const query = Object.keys(obj).map( k => `${k}=${obj[k]}`).join("&");
  return query.length > 0 ? `?${query}` : "";
}

Related