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

Creates a new purchase

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
	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
		product: {
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.product]
46
		}
47
	}
48

49
	const response = await fetch(endpoint, {
50
		method: 'POST',
51
		headers: {
52
			'Content-Type': 'application/json'
53
		},
54
		body: JSON.stringify(body)
55
	})
56

57
	if (!response.ok) {
58
		const errorData = await response.json()
59
		console.error('Error response:', errorData)
60
		throw new Error(`HTTP error! status: ${response.status}`)
61
	}
62

63
	const data = await response.json()
64
	return data
65
}
66