1 | |
2 | type Paylocity = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Obtain new client secret. |
8 | * Obtain new client secret for Paylocity-issued client id. See Weblink Authentication section for details. |
9 | */ |
10 | export async function main(auth: Paylocity, body: { code: string }) { |
11 | const url = new URL(`https://dc1prodgwext.paylocity.com/api/v2/credentials/secrets`) |
12 |
|
13 | const response = await fetch(url, { |
14 | method: 'POST', |
15 | headers: { |
16 | 'Content-Type': 'application/json', |
17 | Authorization: |
18 | 'Bearer ' + |
19 | (await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/token')) |
20 | }, |
21 | body: JSON.stringify(body) |
22 | }) |
23 | if (!response.ok) { |
24 | const text = await response.text() |
25 | throw new Error(`${response.status} ${text}`) |
26 | } |
27 | return await response.json() |
28 | } |
29 |
|
30 | async function getOAuthToken(auth: Paylocity, tokenUrl: string): Promise<string> { |
31 | const params = new URLSearchParams({ |
32 | grant_type: 'client_credentials', |
33 | client_id: auth.clientId, |
34 | client_secret: auth.clientSecret |
35 | }) |
36 |
|
37 | const response = await fetch(tokenUrl, { |
38 | method: 'POST', |
39 | headers: { |
40 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
41 | 'Content-Type': 'application/x-www-form-urlencoded' |
42 | }, |
43 | body: params.toString() |
44 | }) |
45 |
|
46 | if (!response.ok) { |
47 | const text = await response.text() |
48 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
49 | } |
50 |
|
51 | const data = await response.json() |
52 | return data.access_token |
53 | } |
54 |
|