1 | |
2 | |
3 | * Company Workers |
4 | * Array of workers (employee and contractor) for all of the companies who are associated with a specific company that your application has been granted access to. The combination of query parameters to be used with this endpoint are as follows: 1. givenname, familyname, legallastfour 2. from, to (start date, end date) 3. employeeid 4. locationid 5. offset, limit (paging). Note: Paging and filtering attributes cannot be applied together. |
5 | */ |
6 | export async function main( |
7 | auth: RT.Paychex, |
8 | companyId: string, |
9 | givenname?: string | undefined, |
10 | familyname?: string | undefined, |
11 | legallastfour?: string | undefined, |
12 | employeeid?: string | undefined, |
13 | from?: string | undefined, |
14 | to?: string | undefined, |
15 | locationid?: string | undefined |
16 | ) { |
17 | const accessToken = await getOAuthToken(auth, 'https://api.paychex.com/auth/oauth/v2/token') |
18 | const url = new URL(`https://api.paychex.com/companies/${companyId}/workers`) |
19 | for (const [k, v] of [ |
20 | ['givenname', givenname], |
21 | ['familyname', familyname], |
22 | ['legallastfour', legallastfour], |
23 | ['employeeid', employeeid], |
24 | ['from', from], |
25 | ['to', to], |
26 | ['locationid', locationid] |
27 | ]) { |
28 | if (v !== undefined && v !== '') { |
29 | url.searchParams.append(k, v) |
30 | } |
31 | } |
32 | const response = await fetch(url, { |
33 | method: 'GET', |
34 | headers: { |
35 | Authorization: 'Bearer ' + accessToken |
36 | }, |
37 | body: undefined |
38 | }) |
39 | if (!response.ok) { |
40 | const text = await response.text() |
41 | throw new Error(`${response.status} ${text}`) |
42 | } |
43 | return await response.json() |
44 | } |
45 |
|
46 | async function getOAuthToken(auth: RT.Paychex, tokenUrl: string): Promise<string> { |
47 | const params = new URLSearchParams({ |
48 | grant_type: 'client_credentials' |
49 | }) |
50 |
|
51 | const response = await fetch(tokenUrl, { |
52 | method: 'POST', |
53 | headers: { |
54 | Authorization: 'Basic ' + btoa(`${auth.client_id}:${auth.client_secret}`), |
55 | 'Content-Type': 'application/x-www-form-urlencoded' |
56 | }, |
57 | body: params.toString() |
58 | }) |
59 |
|
60 | if (!response.ok) { |
61 | const text = await response.text() |
62 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
63 | } |
64 |
|
65 | const data = await response.json() |
66 | return data.access_token |
67 | } |
68 |
|