1 | |
2 | type Paylocity = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Add/update emergency contacts |
8 | * Sends new or updated employee emergency contacts directly to Paylocity Payroll/HR solution. |
9 | */ |
10 | export async function main( |
11 | auth: Paylocity, |
12 | companyId: string, |
13 | employeeId: string, |
14 | body: { |
15 | address1?: string |
16 | address2?: string |
17 | city?: string |
18 | country?: string |
19 | county?: string |
20 | email?: string |
21 | firstName: string |
22 | homePhone?: string |
23 | lastName: string |
24 | mobilePhone?: string |
25 | notes?: string |
26 | pager?: string |
27 | primaryPhone?: string |
28 | priority?: string |
29 | relationship?: string |
30 | state?: string |
31 | syncEmployeeInfo?: false | true |
32 | workExtension?: string |
33 | workPhone?: string |
34 | zip?: string |
35 | } |
36 | ) { |
37 | const url = new URL( |
38 | `https://dc1prodgwext.paylocity.com/api/v2/companies/${companyId}/employees/${employeeId}/emergencyContacts` |
39 | ) |
40 |
|
41 | const response = await fetch(url, { |
42 | method: 'PUT', |
43 | headers: { |
44 | 'Content-Type': 'application/json', |
45 | Authorization: |
46 | 'Bearer ' + |
47 | (await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/token')) |
48 | }, |
49 | body: JSON.stringify(body) |
50 | }) |
51 | if (!response.ok) { |
52 | const text = await response.text() |
53 | throw new Error(`${response.status} ${text}`) |
54 | } |
55 | return await response.text() |
56 | } |
57 |
|
58 | async function getOAuthToken(auth: Paylocity, tokenUrl: string): Promise<string> { |
59 | const params = new URLSearchParams({ |
60 | grant_type: 'client_credentials', |
61 | client_id: auth.clientId, |
62 | client_secret: auth.clientSecret |
63 | }) |
64 |
|
65 | const response = await fetch(tokenUrl, { |
66 | method: 'POST', |
67 | headers: { |
68 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
69 | 'Content-Type': 'application/x-www-form-urlencoded' |
70 | }, |
71 | body: params.toString() |
72 | }) |
73 |
|
74 | if (!response.ok) { |
75 | const text = await response.text() |
76 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
77 | } |
78 |
|
79 | const data = await response.json() |
80 | return data.access_token |
81 | } |
82 |
|