invoice-system/auth.js

67 lines
2.2 KiB
JavaScript

const OAuthClient = require('intuit-oauth');
const express = require('express');
const app = express();
// 1. Konfiguration (Füge hier deine Development Keys ein)
const oauthClient = new OAuthClient({
clientId: process.env.QBO_CLIENT_ID,
clientSecret: process.env.QBO_CLIENT_SECRET,
environment: process.env.QBO_ENVIRONMENT, // Wichtig: 'sandbox' für Development Keys
redirectUri: process.env.QBO_REDIRECT_URI,
});
// 2. Start-Route: Generiert die Login-URL und leitet dich weiter
app.get('/', (req, res) => {
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.Payment],
state: 'testState',
});
console.log('Öffne Browser für Login...');
res.redirect(authUri);
});
// 3. Callback-Route: Hierhin kommt QBO zurück mit dem Code
app.get('/callback', async (req, res) => {
try {
// 1. Tokens holen
const authResponse = await oauthClient.createToken(req.url);
const tokens = authResponse.getJson();
const realmId = authResponse.token.realmId;
// 2. Test-Abruf (Kunden)
const url = oauthClient.environment == 'sandbox'
? OAuthClient.environment.sandbox
: OAuthClient.environment.production;
const apiResponse = await oauthClient.makeApiCall({
url: `${url}v3/company/${realmId}/query?query=select * from Customer MAXRESULTS 5`,
method: 'GET',
});
// 3. Ausgabe in der Konsole
console.log('\n--- DEINE TOKENS (BITTE SICHERN) ---');
console.log('Realm ID:', realmId);
console.log('Access Token:', tokens.access_token);
console.log('Refresh Token:', tokens.refresh_token);
console.log('------------------------------------\n');
console.log("Test-Abruf Ergebnis:");
// KORREKTUR: .getJson() statt .text()
console.log(JSON.stringify(apiResponse.getJson(), null, 2));
// 4. Antwort an Browser (Erst ganz am Ende senden!)
res.send(`<h1>Erfolg!</h1><p>Tokens sind in der Konsole.</p>`);
} catch (e) {
console.error("Ein Fehler ist aufgetreten:", e);
// Nur senden, wenn noch nichts gesendet wurde
if (!res.headersSent) res.send('Fehler: Siehe Konsole');
}
});
// Server starten
app.listen(3000, async () => {
console.log('Server läuft auf http://localhost:3000');
});