1 | |
2 | |
3 | * Worker Checks |
4 | * Get check(s) that are for a specific worker within a processed or unprocessed pay period. |
5 | */ |
6 | export async function main( |
7 | auth: RT.Paychex, |
8 | workerId: string, |
9 | payperiodid: string | undefined, |
10 | filterbyuserid?: string | undefined |
11 | ) { |
12 | const accessToken = await getOAuthToken(auth, 'https://api.paychex.com/auth/oauth/v2/token') |
13 | const url = new URL(`https://api.paychex.com/workers/${workerId}/checks`) |
14 | for (const [k, v] of [ |
15 | ['payperiodid', payperiodid], |
16 | ['filterbyuserid', filterbyuserid] |
17 | ]) { |
18 | if (v !== undefined && v !== '') { |
19 | url.searchParams.append(k, v) |
20 | } |
21 | } |
22 | const response = await fetch(url, { |
23 | method: 'GET', |
24 | headers: { |
25 | Authorization: 'Bearer ' + accessToken |
26 | }, |
27 | body: undefined |
28 | }) |
29 | if (!response.ok) { |
30 | const text = await response.text() |
31 | throw new Error(`${response.status} ${text}`) |
32 | } |
33 | return await response.json() |
34 | } |
35 |
|
36 | async function getOAuthToken(auth: RT.Paychex, tokenUrl: string): Promise<string> { |
37 | const params = new URLSearchParams({ |
38 | grant_type: 'client_credentials' |
39 | }) |
40 |
|
41 | const response = await fetch(tokenUrl, { |
42 | method: 'POST', |
43 | headers: { |
44 | Authorization: 'Basic ' + btoa(`${auth.client_id}:${auth.client_secret}`), |
45 | 'Content-Type': 'application/x-www-form-urlencoded' |
46 | }, |
47 | body: params.toString() |
48 | }) |
49 |
|
50 | if (!response.ok) { |
51 | const text = await response.text() |
52 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
53 | } |
54 |
|
55 | const data = await response.json() |
56 | return data.access_token |
57 | } |
58 |
|