Shan
Shan

Reputation: 958

Delete a Stripe Subscription Item using Fetch (Not NPM)

Trying to delete a stripe subscription item using Fetch method like below

export async function update(subItemId, data) {

  const apiKey = "sk_test_XXXXXXXXX"; 

  const response = await fetch("https://api.stripe.com/v1/subscription_items/" + subItemId, {
    method: 'post',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": "Bearer " + apiKey
    },
    body: encodeBody(data)
  });

  if (response.status >= 200 && response.status < 300) {
    const ret = await response.json();
  let alphastatus = 'approved';
    return {ret, "alphastatus": alphastatus};
}
    let res = await response.json();
  let alphastatus = 'declined';
    return {res, "alphastatus": alphastatus};
}

function encodeBody(data){
  let encoded = "";

  for (let [k, v] of Object.entries(data)) {
  encoded = encoded.concat(k,"=", encodeURI(v), "&");
  return encoded; 
  }
}

I have tried passing the parameter 'deleted: true' but it returns an error message saying the 'deleted' parameter is not recognized.

Currently I'm trying to send these parameters from my page:

let data = {
    "deleted": true,
    "prorate": "false"
};
    update(subItemId, data)

I tried following the documentation but I do not understand how to pass DELETE like below

curl https://api.stripe.com/v1/subscription_items/si_ElRqBpvFaZlfnq \
  -u sk_test_XXXXXXXXXXXX: \
  -X DELETE

Upvotes: 1

Views: 252

Answers (1)

karllekko
karllekko

Reputation: 7238

I'd recommend using the stripe-node library — since you should be writing this code on a backend sever using Node. You should never be running this kind of code accessing the subscriptions API from the frontend(like a browser) and using fetch in that environment, as that means your Stripe secret key would be exposed and compromised.

await stripe.subscriptionItems.del(
  subItemId,
  {
    prorate : false
  }
);

https://stripe.com/docs/api/subscription_items/delete?lang=node

Another way to do this(closer to your original code) is like this:

let planToRemove = "plan_EauxYB7fNpQtLn"
let items = subscription.items.data;
items = items.filter(item => item.plan.id == planToRemove)
  .map(item => { return {id: item.id, deleted:true} })
await stripe.subscriptions.update(subscription.id, {
    items : items,
    prorate : false,
});

Upvotes: 1

Related Questions