-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
176 lines (148 loc) · 5.91 KB
/
client.ts
File metadata and controls
176 lines (148 loc) · 5.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import Csrf from "csrf";
import { btoa } from "buffer";
import { fetch } from "bun";
import {
QBAuthenticationErrorResponse,
QBOAuthTokenResponse,
QBQueryResponse,
QBSuccessfulQueryResponse,
} from "./types";
const PROD_BASE_URL = "https://quickbooks.api.intuit.com";
const SANDBOX_BASE_URL = "https://sandbox-quickbooks.api.intuit.com";
const PROD_PRISERE_API_URL = process.env.PROD_PRISERE_API_URL;
const DEV_PRISERE_API_URL = process.env.DEV_PRISERE_API_URL;
export const QB_SCOPES = {
accounting: "com.intuit.quickbooks.accounting",
payment: "com.intuit.quickbooks.payment",
};
export interface IQuickbooksClient {
generateUrl(args: { scopes: (keyof typeof QB_SCOPES)[] }): { url: string; state: string };
generateToken(args: { code: string }): Promise<QBOAuthTokenResponse>;
refreshToken(args: { refreshToken: string }): Promise<QBOAuthTokenResponse>;
query<T>(args: {
/**
* The QuickBooks realm is the externalId of the company's QuickBooks company.
*
* QuickBooks calls this a "realm", it's just an ID
*/
qbRealm: string;
query: string;
accessToken: string;
}): Promise<QBQueryResponse<T>>;
}
export class QuickbooksClient implements IQuickbooksClient {
// generate authorization for getting token
private static readonly AUTHORIZATION_ENDPOINT = "https://appcenter.intuit.com/connect/oauth2";
// generate/refresh access tokens
private static readonly TOKEN_ENDPOINT = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";
// sandbox
// https://developer.api.intuit.com/.well-known/openid_sandbox_configuration
// prod
// https://developer.api.intuit.com/.well-known/openid_configuration
private state = new Csrf();
private clientId: string;
private clientSecret: string;
private environment: "sandbox" | "production";
private redirectUri: string;
private authHeaderToken: string;
private BASE_URL: string;
constructor({
clientId,
clientSecret,
environment,
}: {
clientId: string;
clientSecret: string;
environment: "sandbox" | "production";
}) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.environment = environment;
this.authHeaderToken = btoa(`${this.clientId}:${this.clientSecret}`);
this.BASE_URL = environment === "production" ? PROD_BASE_URL : SANDBOX_BASE_URL;
this.redirectUri =
environment === "production"
? // Note: Quickbooks Redirect URI was updated to match these URLs:
`${PROD_PRISERE_API_URL}/quickbooks/redirect`
: `${DEV_PRISERE_API_URL}/quickbooks/redirect`;
}
public generateUrl({ scopes }: { scopes: (keyof typeof QB_SCOPES)[] }) {
const scopeValues = scopes.map((s) => QB_SCOPES[s]);
const state = this.state.create(this.state.secretSync());
const params = new URLSearchParams({
response_type: "code",
redirect_uri: this.redirectUri,
client_id: this.clientId,
scope: scopeValues.join(" "),
state,
});
const url = `${QuickbooksClient.AUTHORIZATION_ENDPOINT}?${params.toString()}`;
return { url, state };
}
public async generateToken({ code }: { code: string }) {
const response = await fetch(QuickbooksClient.TOKEN_ENDPOINT, {
method: "POST",
headers: {
Accept: "application/json",
Authorization: `Basic ${this.authHeaderToken}`,
"Content-Type": "application/x-www-form-urlencoded",
Host: "oauth.platform.intuit.com",
},
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: this.redirectUri,
}),
}).then((res) => res.json() as unknown as QBOAuthTokenResponse);
return response;
}
public async refreshToken({ refreshToken }: { refreshToken: string }) {
const response = await fetch(QuickbooksClient.TOKEN_ENDPOINT, {
method: "POST",
headers: {
Accept: "application/json",
Authorization: `Basic ${this.authHeaderToken}`,
"Content-Type": "application/x-www-form-urlencoded",
Host: "oauth.platform.intuit.com",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
}),
}).then((res) => res.json() as unknown as QBOAuthTokenResponse);
return response;
}
async query<T>({
query,
qbRealm,
accessToken,
}: {
query: string;
qbRealm: string;
accessToken: string;
}): Promise<QBQueryResponse<T>> {
const params = new URLSearchParams({
// [FUTURE]: This query string is changed out based on what we are requestign (sort of like SQL)
// We might want to create a query builder or something down the road
query,
minorVersion: "75",
});
const url = `${this.BASE_URL}/v3/company/${qbRealm}/query?${params}`;
const response = await fetch(url, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
}).then(async (res): Promise<QBQueryResponse<T>> => {
if (res.status === 401) {
const response = (await res.json()) as unknown as QBAuthenticationErrorResponse;
if (response.fault.error[0].detail === "Token revoked") {
return { _id: "revoked" };
}
return { _id: "unauthorized" };
}
return { _id: "valid", data: (await res.json()) as QBSuccessfulQueryResponse<T>["data"] };
});
return response;
}
}