0

Create or Update Subscriber

by
Published Aug 26, 2024
Script mailerlite Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 652 days ago
1
type MailerLite = {
2
	apiToken: string
3
}
4

5
export async function main(
6
	resource: MailerLite,
7
	body: {
8
		email: string //
9
		fields?: {
10
			name?: string
11
			last_name?: string
12
			company?: string
13
			country?: string
14
			city?: string
15
			phone?: string
16
			state?: string
17
			z_i_p?: string
18
		}
19
		groups?: string[]
20
		status?: 'active' | 'unsubscribed' | 'unconfirmed' | 'bounced' | 'junk'
21
		subscribed_at?: string // yyyy-MM-dd HH:mm:ss
22
		ip_address?: string
23
		opted_in_at?: string // yyyy-MM-dd HH:mm:ss
24
		optin_ip?: string
25
		unsubscribed_at?: string // yyyy-MM-dd HH:mm:ss
26
	}
27
) {
28
	const endpoint = `https://connect.mailerlite.com/api/subscribers`
29

30
	const response = await fetch(endpoint, {
31
		method: 'POST',
32
		headers: {
33
			'Content-Type': 'application/json',
34
			Accept: 'application/json',
35
			Authorization: `Bearer ${resource.apiToken}`
36
		},
37
		body: JSON.stringify(body)
38
	})
39

40
	if (!response.ok) {
41
		const error = await response.json()
42
		console.log(error.message)
43
		throw new Error(`HTTP error! status: ${response.status}`)
44
	}
45

46
	const { data } = await response.json()
47
	return data
48
}
49