0

Create new Recurring Employee Earning

by
Published Oct 17, 2025

**Summary Description** This function will allow the API user to create a new earning on the employee record.

Script paylocity Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Paylocity = {
3
	clientId: string
4
	clientSecret: string
5
}
6
/**
7
 * Create new Recurring Employee Earning
8
 * **Summary Description**
9

10
This function will allow the API user to create a new earning on the employee record.
11
 */
12
export async function main(
13
	auth: Paylocity,
14
	companyId: string,
15
	employeeId: string,
16
	body: {
17
		effectiveFrom?: string
18
		effectiveTo?: string
19
		amount?: number
20
		rate?: number
21
		units?: number
22
		selfInsured?: false | true
23
		calculationCode?: string
24
		frequency?: string
25
		agency?: string
26
		miscellaneousInfo?: string
27
		rateCode?: string
28
		distribution?: {
29
			jobCode?: string
30
			costCenters?: { level?: number; code?: string }[]
31
		}
32
		limits?: {
33
			goal?: number
34
			paidToDate?: number
35
			payPeriodMinimum?: number
36
			payPeriodMaximum?: number
37
			annualMaximum?: number
38
		}
39
		code?: string
40
	}
41
) {
42
	const url = new URL(
43
		`https://dc1prodgwext.paylocity.com/apiHub/payroll/v1/companies/${companyId}/employees/${employeeId}/earnings`
44
	)
45

46
	const response = await fetch(url, {
47
		method: 'POST',
48
		headers: {
49
			'Content-Type': 'application/json',
50
			Authorization:
51
				'Bearer ' +
52
				(await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/token'))
53
		},
54
		body: JSON.stringify(body)
55
	})
56
	if (!response.ok) {
57
		const text = await response.text()
58
		throw new Error(`${response.status} ${text}`)
59
	}
60
	return await response.text()
61
}
62

63
async function getOAuthToken(auth: Paylocity, tokenUrl: string): Promise<string> {
64
	const params = new URLSearchParams({
65
		grant_type: 'client_credentials',
66
		client_id: auth.clientId,
67
		client_secret: auth.clientSecret
68
	})
69

70
	const response = await fetch(tokenUrl, {
71
		method: 'POST',
72
		headers: {
73
			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
74
			'Content-Type': 'application/x-www-form-urlencoded'
75
		},
76
		body: params.toString()
77
	})
78

79
	if (!response.ok) {
80
		const text = await response.text()
81
		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
82
	}
83

84
	const data = await response.json()
85
	return data.access_token
86
}
87