0

Create Event

by
Published Apr 8, 2025

Create a new event to track a profile's activity.

Script klaviyo Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Klaviyo = {
3
  apiKey: string;
4
};
5
/**
6
 * Create Event
7
 * Create a new event to track a profile's activity.
8
 */
9
export async function main(
10
  auth: Klaviyo,
11
  revision: string,
12
  body: {
13
    data: {
14
      type: "event";
15
      attributes: {
16
        properties: {};
17
        time?: string;
18
        value?: number;
19
        value_currency?: string;
20
        unique_id?: string;
21
        metric: {
22
          data: {
23
            type: "metric";
24
            attributes: { name: string; service?: string };
25
          };
26
        };
27
        profile: {
28
          data: {
29
            type: "profile";
30
            id?: string;
31
            attributes: {
32
              email?: string;
33
              phone_number?: string;
34
              external_id?: string;
35
              anonymous_id?: string;
36
              _kx?: string;
37
              first_name?: string;
38
              last_name?: string;
39
              organization?: string;
40
              locale?: string;
41
              title?: string;
42
              image?: string;
43
              location?: {
44
                address1?: string;
45
                address2?: string;
46
                city?: string;
47
                country?: string;
48
                latitude?: string | number;
49
                longitude?: string | number;
50
                region?: string;
51
                zip?: string;
52
                timezone?: string;
53
                ip?: string;
54
              };
55
              properties?: {};
56
              meta?: {
57
                patch_properties?: {
58
                  append?: {};
59
                  unappend?: {};
60
                  unset?: string | string[];
61
                };
62
              };
63
            };
64
          };
65
        };
66
      };
67
    };
68
  },
69
) {
70
  const url = new URL(`https://a.klaviyo.com/api/events`);
71

72
  const response = await fetch(url, {
73
    method: "POST",
74
    headers: {
75
      revision: revision,
76
      "Accept": "application/vnd.api+json",
77
      "Content-Type": "application/vnd.api+json",
78
      Authorization: "Klaviyo-API-Key " + auth.apiKey,
79
    },
80
    body: JSON.stringify(body),
81
  });
82
  if (!response.ok) {
83
    const text = await response.text();
84
    throw new Error(`${response.status} ${text}`);
85
  }
86
  return await response.json();
87
}
88