0
Update Subscriber
One script reply has been approved by the moderators Verified

Update a subscriber

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

5
export async function main(
6
	resource: Convertkit,
7
	subscriberId: string,
8
	payload: {
9
		firstName?: string
10
		email?: string
11
		fields?: { [key: string]: string }
12
	}
13
) {
14
	if (!Object.keys(payload).length) {
15
		throw new Error(`Provide at least one key-value pair in the payload!`)
16
	}
17

18
	const endpoint = `https://api.convertkit.com/v3/subscribers/${subscriberId}`
19

20
	const body = {
21
		api_secret: resource.apiSecret,
22
		...(payload.firstName && { first_name: payload.firstName }),
23
		...(payload.email && { email_address: payload.email }),
24
		...(payload.fields && { fields: payload.fields })
25
	}
26

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

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

39
	const data = await response.json()
40

41
	return data.subscriber
42
}
43