1 | |
2 | type Paylocity = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Get all employees |
8 | * Get All Employees API will return employee data currently available in Paylocity Payroll/HR solution. |
9 | */ |
10 | export async function main( |
11 | auth: Paylocity, |
12 | companyId: string, |
13 | pagesize: string | undefined, |
14 | pagenumber: string | undefined, |
15 | includetotalcount: string | undefined |
16 | ) { |
17 | const url = new URL(`https://dc1prodgwext.paylocity.com/api/v2/companies/${companyId}/employees`) |
18 | for (const [k, v] of [ |
19 | ['pagesize', pagesize], |
20 | ['pagenumber', pagenumber], |
21 | ['includetotalcount', includetotalcount] |
22 | ]) { |
23 | if (v !== undefined && v !== '' && k !== undefined) { |
24 | url.searchParams.append(k, v) |
25 | } |
26 | } |
27 | const response = await fetch(url, { |
28 | method: 'GET', |
29 | headers: { |
30 | Authorization: |
31 | 'Bearer ' + |
32 | (await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/token')) |
33 | }, |
34 | body: undefined |
35 | }) |
36 | if (!response.ok) { |
37 | const text = await response.text() |
38 | throw new Error(`${response.status} ${text}`) |
39 | } |
40 | return await response.json() |
41 | } |
42 |
|
43 | async function getOAuthToken(auth: Paylocity, tokenUrl: string): Promise<string> { |
44 | const params = new URLSearchParams({ |
45 | grant_type: 'client_credentials', |
46 | client_id: auth.clientId, |
47 | client_secret: auth.clientSecret |
48 | }) |
49 |
|
50 | const response = await fetch(tokenUrl, { |
51 | method: 'POST', |
52 | headers: { |
53 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
54 | 'Content-Type': 'application/x-www-form-urlencoded' |
55 | }, |
56 | body: params.toString() |
57 | }) |
58 |
|
59 | if (!response.ok) { |
60 | const text = await response.text() |
61 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
62 | } |
63 |
|
64 | const data = await response.json() |
65 | return data.access_token |
66 | } |
67 |
|