0
Post files
One script reply has been approved by the moderators Verified

To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file.

All of Stripe’s officially supported Client libraries support sending multipart/form-data.

Created by hugo697 188 days ago Viewed 5604 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 188 days ago
1
type Stripe = {
2
  token: string;
3
};
4
type Base64 = string;
5
/**
6
 * Post files
7
 * To upload a file to Stripe, you need to send a request of type multipart/form-data. Include the file you want to upload in the request, and the parameters for creating a file.
8

9
All of Stripe’s officially supported Client libraries support sending multipart/form-data.
10
 */
11
export async function main(
12
  auth: Stripe,
13
  body: {
14
    expand?: string[];
15
    file: {
16
      base64: Base64;
17
      type:
18
        | "image/png"
19
        | "image/jpeg"
20
        | "image/gif"
21
        | "application/pdf"
22
        | "appication/json"
23
        | "text/csv"
24
        | "text/plain"
25
        | "audio/mpeg"
26
        | "audio/wav"
27
        | "video/mp4";
28
      name: string;
29
    };
30
    file_link_data?: {
31
      create: boolean;
32
      expires_at?: number;
33
      metadata?: { [k: string]: string } | "";
34
      [k: string]: unknown;
35
    };
36
    purpose:
37
      | "account_requirement"
38
      | "additional_verification"
39
      | "business_icon"
40
      | "business_logo"
41
      | "customer_signature"
42
      | "dispute_evidence"
43
      | "identity_document"
44
      | "pci_document"
45
      | "tax_document_user_upload"
46
      | "terminal_reader_splashscreen";
47
  }
48
) {
49
  const url = new URL(`https://api.stripe.com/v1/files`);
50

51
  const formData = new FormData();
52
  for (const [k, v] of Object.entries(body)) {
53
    if (v !== undefined && v !== "") {
54
      if (["file"].includes(k)) {
55
        const { base64, type, name } = v as {
56
          base64: Base64;
57
          type: string;
58
          name: string;
59
        };
60
        formData.append(
61
          k,
62
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
63
            type,
64
          }),
65
          name
66
        );
67
      } else {
68
        formData.append(k, String(v));
69
      }
70
    }
71
  }
72
  const response = await fetch(url, {
73
    method: "POST",
74
    headers: {
75
      Authorization: "Bearer " + auth.token,
76
    },
77
    body: formData,
78
  });
79
  if (!response.ok) {
80
    const text = await response.text();
81
    throw new Error(`${response.status} ${text}`);
82
  }
83
  return await response.json();
84
}
85