0

Upsert Cost Center Code

by
Published Oct 17, 2025

**Summary Description** The Cost Center PUT endpoint is used to either create a new Cost Center resource or replace an existing one within the Paylocity system.

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
 * Upsert Cost Center Code
8
 * **Summary Description**
9

10
The Cost Center PUT endpoint is used to either create a new Cost Center resource or replace an existing one within the Paylocity system.
11
 */
12
export async function main(
13
	auth: Paylocity,
14
	companyId: string,
15
	level: string,
16
	code: string,
17
	body: { name: string; isActive?: false | true },
18
	testMode?: string
19
) {
20
	const url = new URL(
21
		`https://dc1prodgwext.paylocity.com/apiHub/corehr/v1/companies/${companyId}/costCenterLevels/${level}/costCenters/${code}`
22
	)
23

24
	const response = await fetch(url, {
25
		method: 'PUT',
26
		headers: {
27
			...(testMode ? { testMode: testMode } : {}),
28
			'Content-Type': 'application/json',
29
			Authorization:
30
				'Bearer ' +
31
				(await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/token'))
32
		},
33
		body: JSON.stringify(body)
34
	})
35
	if (!response.ok) {
36
		const text = await response.text()
37
		throw new Error(`${response.status} ${text}`)
38
	}
39
	return await response.text()
40
}
41

42
async function getOAuthToken(auth: Paylocity, tokenUrl: string): Promise<string> {
43
	const params = new URLSearchParams({
44
		grant_type: 'client_credentials',
45
		client_id: auth.clientId,
46
		client_secret: auth.clientSecret
47
	})
48

49
	const response = await fetch(tokenUrl, {
50
		method: 'POST',
51
		headers: {
52
			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
53
			'Content-Type': 'application/x-www-form-urlencoded'
54
		},
55
		body: params.toString()
56
	})
57

58
	if (!response.ok) {
59
		const text = await response.text()
60
		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
61
	}
62

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