0
Create Multiple Purchases
One script reply has been approved by the moderators Verified

Creates multiple purchases

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

5
export async function main(
6
	resource: Convertkit,
7
	payload: {
8
		transactionId: string
9
		emailAddress: string
10
		firstName?: string
11
		currency: string
12
		transactionTime: string
13
		subtotal: number
14
		tax: number
15
		shipping: number
16
		discount: number
17
		total: number
18
		status: string
19
		products: {
20
			pid: number
21
			lid: number
22
			name: string
23
			sku: string
24
			unitPrice: number
25
			quantity: number
26
		}[]
27
	}
28
) {
29
	const endpoint = `https://api.convertkit.com/v3/purchases`
30

31
	const body = {
32
		api_secret: resource.apiSecret,
33
		purchase: {
34
			transaction_id: payload.transactionId,
35
			email_address: payload.emailAddress,
36
			first_name: payload.firstName,
37
			currency: payload.currency,
38
			transaction_time: payload.transactionTime,
39
			subtotal: payload.subtotal,
40
			tax: payload.tax,
41
			shipping: payload.shipping,
42
			discount: payload.discount,
43
			total: payload.total,
44
			status: payload.status,
45
			products: payload.products.map((product) => ({
46
				pid: product.pid,
47
				lid: product.lid,
48
				name: product.name,
49
				sku: product.sku,
50
				unit_price: product.unitPrice,
51
				quantity: product.quantity
52
			}))
53
		}
54
	}
55

56
	const response = await fetch(endpoint, {
57
		method: 'POST',
58
		headers: {
59
			'Content-Type': 'application/json'
60
		},
61
		body: JSON.stringify(body)
62
	})
63

64
	if (!response.ok) {
65
		const errorData = await response.json()
66
		console.error('Error response:', errorData)
67
		throw new Error(`HTTP error! status: ${response.status}`)
68
	}
69

70
	const data = await response.json()
71
	return data
72
}
73