0

UpdateCatalogImage

by
Published Oct 17, 2025

Uploads a new image file to replace the existing one in the specified [CatalogImage]($m/CatalogImage) object. This `UpdateCatalogImage` endpoint accepts HTTP multipart/form-data requests with a JSON part and an image file part in JPEG, PJPEG, PNG, or GIF format. The maximum file size is 15MB.

Script square Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Square = {
3
  token: string;
4
};
5
type Base64 = string;
6
/**
7
 * UpdateCatalogImage
8
 * Uploads a new image file to replace the existing one in the specified [CatalogImage]($m/CatalogImage) object.
9

10
This `UpdateCatalogImage` endpoint accepts HTTP multipart/form-data requests with a JSON part and an image file part in
11
JPEG, PJPEG, PNG, or GIF format. The maximum file size is 15MB.
12
 */
13
export async function main(
14
  auth: Square,
15
  image_id: string,
16
  body: {
17
    request?: { idempotency_key: string };
18
    image_file?: {
19
      base64: Base64;
20
      type:
21
        | "image/png"
22
        | "image/jpeg"
23
        | "image/gif"
24
        | "application/pdf"
25
        | "appication/json"
26
        | "text/csv"
27
        | "text/plain"
28
        | "audio/mpeg"
29
        | "audio/wav"
30
        | "video/mp4";
31
      name: string;
32
    };
33
  },
34
) {
35
  const url = new URL(
36
    `https://connect.squareup.com/v2/catalog/images/${image_id}`,
37
  );
38

39
  const formData = new FormData();
40
  for (const [k, v] of Object.entries(body)) {
41
    if (v !== undefined) {
42
      if (["image_file"].includes(k)) {
43
        const { base64, type, name } = v as {
44
          base64: Base64;
45
          type: string;
46
          name: string;
47
        };
48
        formData.append(
49
          k,
50
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
51
            type,
52
          }),
53
          name,
54
        );
55
      } else {
56
        formData.append(k, String(v));
57
      }
58
    }
59
  }
60
  const response = await fetch(url, {
61
    method: "PUT",
62
    headers: {
63
      Authorization: "Bearer " + auth.token,
64
    },
65
    body: formData,
66
  });
67
  if (!response.ok) {
68
    const text = await response.text();
69
    throw new Error(`${response.status} ${text}`);
70
  }
71
  return await response.json();
72
}
73