JavaScript SDK Quickstart
Following the steps described on this page, you'll create a simple Node Js application that interacts with the Fatture in Cloud API.
If you want to download the complete working example you can find it here.
0️⃣ Prerequisites
In this guide, we assume that these prerequisites are met:
- Node.js installed
- A private app using the OAuth 2.0 Authorization Code Flow
- A Fatture in Cloud account.
1️⃣ Step One: Install the Fatture in Cloud SDK
In this quickstart, we'll use the Fatture in Cloud SDK, published to NPM.
To install it using Npm:
npm install @fattureincloud/fattureincloud-js-sdk
2️⃣ Step Two: Set up the OAuth access token retrieval
Create the file oauth.js copy in the following code:
const fs = require("fs");
const fattureInCloudSdk = require("@fattureincloud/fattureincloud-js-sdk");
const oauth = new fattureInCloudSdk.OAuth2AuthorizationCodeManager(
"CLIENT_ID",
"CLIENT_SECRET",
"http://localhost:8000/oauth"
);
async function saveAccessToken(req, res) {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
let query = req.url.split("?")[1];
let params = new URLSearchParams(query);
if (params.get("code") == null) {
res.writeHead(302, {
Location: oauth.getAuthorizationUrl(
[fattureInCloudSdk.Scope.ENTITY_SUPPLIERS_READ],
"EXAMPLE_STATE"
),
});
res.end();
} else {
try {
let token = await oauth.fetchToken(params.get("code"));
fs.writeFileSync(
"./token.json",
JSON.stringify(token, null, 4),
(err) => {
if (err) {
console.error(err);
return;
}
}
);
res.write("Token succesfully retrived and stored in token.json");
} catch (e) {
console.log(e);
}
res.end();
}
}
module.exports = {
saveAccessToken,
};
To make this code work properly the only thing you need to set your client id, client secret and eventually the redirect uri at line 3.
In this QuickStart the access token and refresh token are stored in a file. This is only for educational purposes, the OAuth access token and refresh token are sensitive data and should be saved securely on your database. Also, never share your Client Secret with third-party actors, or publish it to your frontend!
3️⃣ Step Three: Set up the sample
In this example, we'll show how to retrieve your Company ID using the JavaScript SDK. If you plan to manage only one company, you can insert it directly into your code as a variable. Check the Company-scoped Methods page for more info.
Create the files index.js and quickstart.js in your working directory and copy in the following code:
- index.js
- quickstart.js
const http = require("http");
const url = require("url");
const oauthPath = require("./oauth.js"); //import the oauth methods
const quickstart = require("./quickstart.js"); //import the quickstart
const hostname = "127.0.0.1"; //set your hostname
const port = 8000; //set your port
const server = http.createServer(async (req, res) => {
let pathname = url.parse(req.url).pathname;
//url routing
switch (pathname) {
case "/oauth": //oauth endpoint
res.end(oauthPath.getOAuthAccessToken(req, res));
break;
case "/quickstart": //quickstart endpoint
res.end(quickstart.getFirstCompanySuppliers());
break;
default:
res.end();
break;
}
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
const fattureInCloudSdk = require("@fattureincloud/fattureincloud-js-sdk");
const fs = require("fs");
async function getFirstCompanySuppliers() {
try {
let rawdata = fs.readFileSync(__dirname + "/token.json");
let json = JSON.parse(rawdata);
let defaultClient = fattureInCloudSdk.ApiClient.instance;
let OAuth2AuthenticationCodeFlow =
defaultClient.authentications["OAuth2AuthenticationCodeFlow"];
OAuth2AuthenticationCodeFlow.accessToken = json["access_token"];
// Retrieve the first company id
let userApiInstance = new fattureInCloudSdk.UserApi();
let userCompaniesResponse = await userApiInstance.listUserCompanies();
let firstCompanyId = userCompaniesResponse.data.companies[0].id;
// Retrieve the list of the Suppliers
let suppliersApiInstance = new fattureInCloudSdk.SuppliersApi();
let companySuppliers = await suppliersApiInstance.listSuppliers(
firstCompanyId
);
return JSON.stringify(companySuppliers.data);
} catch (e) {
return JSON.stringify(e);
}
}
module.exports = {
getFirstCompanySuppliers,
};
Make sure your FattureInCloud app redirect URL points at the just edited file (e.g. http://localhost:5000/Index).
5️⃣ Step Five: Run the sample
From the command line, run the following command:
node index.js
Now visit http://localhost:8000/auth (or whatever your URL is), you will be redirected to the Fatture in Cloud login page where you will be asked to grant some permissions, according to what scopes you specified previously. Finally, you will see the success message and the access token will be stored in the token.json file.
You can now visit http://localhost:8000/quickstart (or whatever your URL is) to test the application.
❓ What now?
In this example, we used a limited set of the available API methods to show how to use our SDK.
If you want to access the full documentation of the available methods and models, you can check the following resources:
- JavaScript SDK GitHub Repository: the Readme file contains the full list of the available methods and models
- API Reference: it contains the list of methods and models
- OpenAPI Specification: Our OpenAPI Specification contains the full description of the available methods and models
- NPM page: The main package page on NPM
- YarnPkg page: The main package page on Yarn