0
Delete subscriptions subscription exposed id
One script reply has been approved by the moderators Verified

Cancels a customer’s subscription immediately.

Created by hugo697 188 days ago Viewed 5576 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 188 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Delete subscriptions subscription exposed id
6
 * Cancels a customer’s subscription immediately.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  subscription_exposed_id: string,
11
  body: {
12
    cancellation_details?: {
13
      comment?: string | "";
14
      feedback?:
15
        | ""
16
        | "customer_service"
17
        | "low_quality"
18
        | "missing_features"
19
        | "other"
20
        | "switched_service"
21
        | "too_complex"
22
        | "too_expensive"
23
        | "unused";
24
      [k: string]: unknown;
25
    };
26
    expand?: string[];
27
    invoice_now?: boolean;
28
    prorate?: boolean;
29
  }
30
) {
31
  const url = new URL(
32
    `https://api.stripe.com/v1/subscriptions/${subscription_exposed_id}`
33
  );
34

35
  const response = await fetch(url, {
36
    method: "DELETE",
37
    headers: {
38
      "Content-Type": "application/x-www-form-urlencoded",
39
      Authorization: "Bearer " + auth.token,
40
    },
41
    body: encodeParams(body),
42
  });
43
  if (!response.ok) {
44
    const text = await response.text();
45
    throw new Error(`${response.status} ${text}`);
46
  }
47
  return await response.json();
48
}
49

50
function encodeParams(o: any) {
51
  function iter(o: any, path: string) {
52
    if (Array.isArray(o)) {
53
      o.forEach(function (a) {
54
        iter(a, path + "[]");
55
      });
56
      return;
57
    }
58
    if (o !== null && typeof o === "object") {
59
      Object.keys(o).forEach(function (k) {
60
        iter(o[k], path + "[" + k + "]");
61
      });
62
      return;
63
    }
64
    data.push(path + "=" + o);
65
  }
66
  const data: string[] = [];
67
  Object.keys(o).forEach(function (k) {
68
    if (o[k] !== undefined) {
69
      iter(o[k], k);
70
    }
71
  });
72
  return new URLSearchParams(data.join("&"));
73
}
74