0
Add Subscriber To Sequence
One script reply has been approved by the moderators Verified

Add a subscriber to a sequence

Created by hugo697 80 days ago Viewed 29 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 80 days ago
1
type Convertkit = {
2
	apiSecret: string
3
}
4

5
export async function main(
6
	resource: Convertkit,
7
	sequenceId: string,
8
	subscriberData: {
9
		email: string
10
		firstName?: string
11
		fields?: { [key: string]: string }
12
		tags?: number[]
13
	}
14
) {
15
	const endpoint = `https://api.convertkit.com/v3/sequences/${sequenceId}/subscribe`
16

17
	const body = {
18
		api_secret: resource.apiSecret,
19
		email: subscriberData.email,
20
		...(subscriberData.firstName && { first_name: subscriberData.firstName }),
21
		...(subscriberData.fields && { fields: subscriberData.fields }),
22
		...(subscriberData.tags && { tags: subscriberData.tags })
23
	}
24

25
	const response = await fetch(endpoint, {
26
		method: 'POST',
27
		headers: {
28
			'Content-Type': 'application/json; charset=utf-8'
29
		},
30
		body: JSON.stringify(body)
31
	})
32

33
	if (!response.ok) {
34
		throw new Error(`HTTP error! status: ${response.status}`)
35
	}
36

37
	const data = await response.json()
38

39
	return data.subscription
40
}
41