|
| 1 | +import axios from 'axios'; |
| 2 | +import { DataObject, OAuthResponse } from '../../lib/types'; |
| 3 | +import qs from 'qs'; |
| 4 | + |
| 5 | +export const init = async ({ body }: DataObject): Promise<OAuthResponse> => { |
| 6 | + try { |
| 7 | + const { |
| 8 | + clientId: client_id, |
| 9 | + clientSecret: client_secret, |
| 10 | + metadata: { code, redirectUri: redirect_uri, environment }, |
| 11 | + } = body; |
| 12 | + |
| 13 | + const url = |
| 14 | + environment === 'test' |
| 15 | + ? 'https://authstage.shipbob.com/connect/token' |
| 16 | + : 'https://auth.shipbob.com/connect/token'; |
| 17 | + |
| 18 | + const requestBody = { |
| 19 | + grant_type: 'authorization_code', |
| 20 | + code, |
| 21 | + client_id, |
| 22 | + client_secret, |
| 23 | + redirect_uri, |
| 24 | + }; |
| 25 | + |
| 26 | + const response = await axios({ |
| 27 | + url, |
| 28 | + method: 'POST', |
| 29 | + headers: { |
| 30 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 31 | + Accept: 'application/json', |
| 32 | + }, |
| 33 | + data: qs.stringify(requestBody), |
| 34 | + }); |
| 35 | + |
| 36 | + const { |
| 37 | + access_token: accessToken, |
| 38 | + refresh_token: refreshToken, |
| 39 | + token_type: tokenType, |
| 40 | + expires_in: expiresIn, |
| 41 | + } = response.data; |
| 42 | + |
| 43 | + const baseUrl = |
| 44 | + environment === 'test' |
| 45 | + ? 'https://sandbox-api.shipbob.com/2.0/' |
| 46 | + : 'https://api.shipbob.com/2.0/'; |
| 47 | + |
| 48 | + const channelResponse = await axios({ |
| 49 | + url: `${baseUrl}channel`, |
| 50 | + method: 'GET', |
| 51 | + headers: { |
| 52 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 53 | + Accept: 'application/json', |
| 54 | + Authorization: `Bearer ${accessToken}`, |
| 55 | + }, |
| 56 | + }); |
| 57 | + |
| 58 | + return { |
| 59 | + accessToken, |
| 60 | + refreshToken, |
| 61 | + expiresIn, |
| 62 | + tokenType: tokenType === 'bearer' ? 'Bearer' : tokenType, |
| 63 | + meta: { |
| 64 | + environment, |
| 65 | + baseUrl, |
| 66 | + channelId: channelResponse.data[0].id, |
| 67 | + }, |
| 68 | + }; |
| 69 | + } catch (error) { |
| 70 | + throw new Error(`Error fetching access token for ShipBob: ${error}`); |
| 71 | + } |
| 72 | +}; |
0 commit comments