Obtain Access Token (JavaScript)

This guide offers a JavaScript code example for obtaining and managing access tokens for the 24SevenOffice API, ensuring automatic token renewal and seamless API integration.

Here, you’ll find a straightforward guide on how to securely obtain and use an access token for the 24SevenOffice API. Whether you’re a seasoned developer or just starting out, this page is designed to help you integrate our API smoothly and keep your access tokens valid at all times.

 

Disclaimer 

The code examples and implementation details provided on this page are for demonstration purposes only. They are intended to guide you in integrating with the 24SevenOffice API and managing access tokens. However, they may not account for all security considerations specific to your environment or application. It is your responsibility to review, test, and ensure that any implementation meets your security and operational requirements. 24SevenOffice assumes no liability for any potential security breaches, data loss, or other risks arising from the use of these examples. Please consult with your development and security teams to ensure that your integration is secure and compliant with best practices.

What’s an Access Token?

An access token is your gateway to accessing the 24SevenOffice API. It allows you to authenticate your requests and interact with our ERP features securely. However, tokens can expire, so you need to ensure your application always uses a valid token.

Access Token Documentation

Refer to our API documentation to learn more about how Authentication is set up here, how Scopes work here, and also see a step-by-step explanation on how to obtain client credentials and eventually an access token here

How to Get and Use Your Access Token

Follow the steps below to get and manage your access token efficiently.

Step 1: Prepare Your Credentials

Before diving into the code, make sure you have the following credentials ready:

  • Client ID (client_id)
  • Client Secret (client_secret)
  • Organization ID (login_organization)

For details, please, refer to step 9 in the documentation here.

Step 2: Set Up Your Project

First, ensure you have Node.js installed on your machine. Then, create a new project directory and initialize a new Node.js project:

mkdir my-24sevenoffice-app
cd my-24sevenoffice-app
npm init -y

Step 3: Install Required Packages

You will need the node-fetch package to make HTTP requests. Install it using the following command:

npm install node-fetch

Step 4: Write the Code to Obtain Access Token

Create a new JavaScript file, e.g., getAccessToken.js, and open it in your code editor. Use the following code to set up the access token retrieval process:

// Import fetch from node-fetch (only needed for Node.js environments)
const fetch = require('node-fetch');

// Define the credentials and request details
const clientId = 'zzz'; // Replace with your client ID
const clientSecret = 'yyy'; // Replace with your client secret
const loginOrganization = '123'; // Replace with your login organization
const tokenUrl = 'https://login.24sevenoffice.com/oauth/token';
const audience = 'https://api.24sevenoffice.com';

// Initialize variables for caching the token and expiration time
let cachedToken = null;
let tokenExpirationTime = null;

// Function to obtain a new access token
async function getNewAccessToken() {
const body = JSON.stringify({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
audience: audience,
login_organization: loginOrganization
});

const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: body
};

const response = await fetch(tokenUrl, options);

if (!response.ok) {
throw new Error(`Failed to obtain access token: ${response.statusText}`);
}

const data = await response.json();

// Cache the token and calculate the expiration time
cachedToken = data.access_token;
tokenExpirationTime = Date.now() + (data.expires_in - 60) * 1000; // Refresh 60 seconds before expiration

return cachedToken;
}

// Function to get the access token, using the cache if possible
async function getAccessToken() {
if (cachedToken && Date.now() < tokenExpirationTime) {
return cachedToken;
}
return await getNewAccessToken();
}

Example Usage

You can use the following code snippet to make a sample API request using the obtained access token. This section can be copied and pasted into the same file or another file for testing.

// Define the API endpoint as a separate variable
const apiEndpoint = 'https://rest.api.24sevenoffice.com/v1/taxes';

// Example usage
async function fetchData() {
try {
let token = await getAccessToken();

// Use the token to make an API request
let apiResponse = await fetch(apiEndpoint, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}
});

if (!apiResponse.ok) {
// Check for 403 Forbidden error
if (apiResponse.status === 403) {
console.log('Token may be expired or insufficient permissions. Refreshing token...');
token = await getNewAccessToken(); // Fetch a new token

// Retry the API request with the new token
apiResponse = await fetch(apiEndpoint, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}
});
}

if (!apiResponse.ok) {
throw new Error(`API request failed: ${apiResponse.statusText}`);
}
}

const data = await apiResponse.json();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error.message);
}
}

// Run the fetchData function for testing
fetchData();

Running the Code

To execute your code, run the following command in your terminal:

node getAccessToken.js

Make sure to replace the placeholder values for clientIdclientSecret, and loginOrganization with your actual credentials before running the code.

 
With this code in place, you’ll never have to worry about expired tokens interrupting your API calls. The code handles token expiration seamlessly, making your integration with the 24SevenOffice API smooth and reliable.