0

Bulk Subscribe Profiles

by
Published Apr 8, 2025

Subscribe one or more profiles to email marketing, SMS marketing, or both.

Script klaviyo Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Klaviyo = {
3
  apiKey: string;
4
};
5
/**
6
 * Bulk Subscribe Profiles
7
 * Subscribe one or more profiles to email marketing, SMS marketing, or both.
8
 */
9
export async function main(
10
  auth: Klaviyo,
11
  revision: string,
12
  body: {
13
    data: {
14
      type: "profile-subscription-bulk-create-job";
15
      attributes: {
16
        custom_source?: string;
17
        profiles: {
18
          data: {
19
            type: "profile";
20
            id?: string;
21
            attributes: {
22
              email?: string;
23
              phone_number?: string;
24
              subscriptions?: {
25
                email?: {
26
                  marketing: { consent: "SUBSCRIBED"; consented_at?: string };
27
                };
28
                sms?: {
29
                  marketing?: { consent: "SUBSCRIBED"; consented_at?: string };
30
                  transactional?: {
31
                    consent: "SUBSCRIBED";
32
                    consented_at?: string;
33
                  };
34
                };
35
              };
36
              age_gated_date_of_birth?: string;
37
            };
38
          }[];
39
        };
40
        historical_import?: false | true;
41
      };
42
      relationships?: { list?: { data?: { type: "list"; id: string } } };
43
    };
44
  },
45
) {
46
  const url = new URL(
47
    `https://a.klaviyo.com/api/profile-subscription-bulk-create-jobs`,
48
  );
49

50
  const response = await fetch(url, {
51
    method: "POST",
52
    headers: {
53
      revision: revision,
54
      "Accept": "application/vnd.api+json",
55
      "Content-Type": "application/vnd.api+json",
56
      Authorization: "Klaviyo-API-Key " + auth.apiKey,
57
    },
58
    body: JSON.stringify(body),
59
  });
60
  if (!response.ok) {
61
    const text = await response.text();
62
    throw new Error(`${response.status} ${text}`);
63
  }
64
  return await response.json();
65
}
66