Adding a Stripe subscription through API

421 views Asked by At

I am trying to automate the creation of a customer and adding a subscription. I can create the customer through Zapier but I don't really know how to use Python or Javascript to add a subscription or invoice. I can pass in all the data I need into variables like the plan Id and invoice amount. Does anyone have experience with this?

1

There are 1 answers

0
KayCee On

You can create a subscription request if you have the customer_id and plan_id. If you want to do this with Zapier, you can make a POST request using the fetch library in the Code (Javascript) app.

Pass the customer_id and plan_id in the Input Data.

input data config Encode your secret key from Stripe in Base64. You can use this site to encode your key. Replace the encodedAPiKey in the code below and paste it into Zapier.

When this code step runs, it will create a subscription for the customer.

const url = 'https://api.stripe.com/v1/subscriptions';

//Replace with Base64 encoded secret key from Stripe.
const encodedApiKey = "c2tLsfdGVzdF9aYlFNVjdBSzE3Tm1sTVdMVjkwVWdWTz";

const headers = {
    'Authorization': `Basic ${encodedApiKey}`,
    'Content-Type': 'application/x-www-form-urlencoded'
};

fetch(`${url}?customer=${inputData.customer_id}&items[0][plan]=${inputData.plan_id}`, {method:'POST',
        headers: headers
       })
.then(res => res.json())
.then(json => {
  console.log(json);
  callback(null, json);
})
.catch(callback);

You will find documentation for this on Stripe here.

Note: If this code gets called multiple times, it will create multiple subscriptions for the customer. You might want to add some code to handle that or setup your Zaps in a way that this step doesn't get called twice.

Hope that helps!