Edits history of script submission #17549 for ' Company Checks (paychex)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    /**
     * Company Checks
     * Get check(s) that are for a specific company within a processed or unprocessed pay period.
     */
    export async function main(
    	auth: RT.Paychex,
    	companyId: string,
    	payperiodid: string | undefined,
    	offset?: string | undefined,
    	limit?: string | undefined,
    	filterbyuserid?: string | undefined
    ) {
    	const accessToken = await getOAuthToken(auth, 'https://api.paychex.com/auth/oauth/v2/token')
    	const url = new URL(`https://api.paychex.com/companies/${companyId}/checks`)
    	for (const [k, v] of [
    		['payperiodid', payperiodid],
    		['offset', offset],
    		['limit', limit],
    		['filterbyuserid', filterbyuserid]
    	]) {
    		if (v !== undefined && v !== '') {
    			url.searchParams.append(k, v)
    		}
    	}
    	const response = await fetch(url, {
    		method: 'GET',
    		headers: {
    			Authorization: 'Bearer ' + accessToken
    		},
    		body: undefined
    	})
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    	return await response.json()
    }
    
    async function getOAuthToken(auth: RT.Paychex, tokenUrl: string): Promise<string> {
    	const params = new URLSearchParams({
    		grant_type: 'client_credentials'
    	})
    
    	const response = await fetch(tokenUrl, {
    		method: 'POST',
    		headers: {
    			Authorization: 'Basic ' + btoa(`${auth.client_id}:${auth.client_secret}`),
    			'Content-Type': 'application/x-www-form-urlencoded'
    		},
    		body: params.toString()
    	})
    
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
    	}
    
    	const data = await response.json()
    	return data.access_token
    }
    

    Submitted by hugo697 235 days ago