-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
202 lines (171 loc) Β· 5.97 KB
/
index.js
File metadata and controls
202 lines (171 loc) Β· 5.97 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Load environment variables from .env file
require("dotenv").config();
const express = require("express");
const OAuthClient = require("intuit-oauth");
const QuickBooks = require("node-quickbooks");
// Import routes
const invoiceRoutes = require("./routes/invoiceRoutes");
// Initialize an Express application
const app = express();
const port = 3000;
// Add middleware to parse JSON requests
app.use(express.json());
// Configure the OAuthClient with credentials and environment
const oauthClient = new OAuthClient({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
environment: process.env.ENVIRONMENT,
redirectUri: process.env.REDIRECT_URL,
logging: true, // Enable OAuth client logging
});
// Log environment configuration
console.log("π Environment Configuration:", {
environment: process.env.ENVIRONMENT,
redirectUri: process.env.REDIRECT_URL,
clientId: process.env.CLIENT_ID ? "Set" : "Not Set",
clientSecret: process.env.CLIENT_SECRET ? "Set" : "Not Set",
});
// Initialize QuickBooks authentication
const initializeQuickBooks = async () => {
try {
console.log("π Initializing QuickBooks authentication...");
// Generate the authorization URL
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
state: "randomState",
});
console.log("π Generated Auth URI:", authUri);
console.log("β οΈ Please visit the auth endpoint to complete authentication");
console.log(" GET /auth");
} catch (error) {
console.error("β Error initializing QuickBooks:", {
message: error.message,
originalMessage: error.originalMessage,
intuit_tid: error.intuit_tid,
});
}
};
// Make oauthClient available to routes
app.set("oauthClient", oauthClient);
// Use routes
app.use("/api", invoiceRoutes);
// Authentication endpoint
app.get("/auth", (req, res) => {
console.log("π Starting OAuth Authentication Flow");
// Generate authorization URL
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
state: "randomState",
});
// Redirect to QuickBooks authorization page
res.redirect(authUri);
});
// Callback endpoint
app.get("/callback", async (req, res) => {
console.log("π Received OAuth Callback");
console.log("π₯ Callback URL:", req.url);
try {
// Exchange the auth code for tokens
console.log("π Exchanging auth code for tokens...");
const authResponse = await oauthClient.createToken(req.url);
console.log("β
Token Exchange Successful");
console.log("π Token Response:", {
realmId: authResponse.getToken().realmId,
tokenType: authResponse.getToken().token_type,
expiresIn: authResponse.getToken().expires_in,
});
// Store the tokens
oauthClient.setToken(authResponse.getToken());
console.log("β
Tokens stored successfully");
res.status(200).json({
success: true,
message: "Authentication successful",
realmId: authResponse.getToken().realmId,
});
} catch (error) {
console.error("β Error during authentication:", {
message: error.message,
originalMessage: error.originalMessage,
intuit_tid: error.intuit_tid,
});
res
.status(500)
.json({ error: "Authentication failed", details: error.message });
}
});
// Route to get all invoices
app.get("/api/invoices", async (req, res) => {
console.log("π Fetching Invoices");
try {
// Check if we have valid tokens
const isTokenValid = oauthClient.isAccessTokenValid();
console.log("π Token Validation:", { isValid: isTokenValid });
if (!isTokenValid) {
console.log("β οΈ Token invalid or expired, redirecting to auth");
return res.redirect("/auth");
}
// Get the tokens
const authResponse = oauthClient.getToken();
const { realmId, access_token, refresh_token } = authResponse;
console.log("π’ Company ID:", realmId);
// Initialize QuickBooks client
const qbo = new QuickBooks(
process.env.CLIENT_ID,
process.env.CLIENT_SECRET,
access_token,
false, // no token secret for oAuth 2.0
realmId,
process.env.ENVIRONMENT === "sandbox", // use sandbox?
true, // enable debugging
null, // minor version
"2.0", // oauth version
refresh_token
);
console.log("π’ Making API call to QuickBooks...");
// Use node-quickbooks to fetch invoices
qbo.findInvoices(
{
fetchAll: true, // Get all invoices
},
(err, invoices) => {
if (err) {
console.error("β Error fetching invoices:", {
message: err.message,
intuit_tid: err.intuit_tid,
});
return res.status(500).json({ error: "Failed to fetch invoices" });
}
console.log("β
API Call Successful");
console.log(
"π¦ Number of Invoices:",
invoices.QueryResponse?.Invoice?.length || 0
);
// Return the invoices
res.json(invoices);
}
);
} catch (error) {
console.error("β Error in invoice route:", {
message: error.message,
originalMessage: error.originalMessage,
intuit_tid: error.intuit_tid,
authResponse: error.authResponse,
});
if (error.authResponse && error.authResponse.status === 401) {
console.log("β οΈ Unauthorized (401), redirecting to auth");
return res.redirect("/auth");
}
res.status(500).json({ error: "Failed to fetch invoices" });
}
});
// Start the Express server
app.listen(port, async () => {
console.log(`π Server started on port: ${port}`);
console.log("π Available endpoints:");
console.log(" - GET /auth - Start OAuth flow");
console.log(" - GET /callback - OAuth callback");
console.log(" - GET /api/invoices - Get all invoices");
console.log(" - POST /api/invoices/create - Create new invoice");
// Initialize QuickBooks authentication
await initializeQuickBooks();
});