OAuth 2.0 for Integrations (Fleetio)
This document explains how to implement OAuth 2.0 for Fleetio integrations, covers the simplified onboarding flow for Fleetio customers, the security benefits, required configuration steps, and working code samples (Java, PHP, Python, Go). The OAuth flow with Fleetio is a standard OAuth 2.0 Authorization Code flow with one important addition: the token exchange response includes an account_token value which must be captured and stored alongside access_token and refresh_token.
Why use OAuth 2.0 for Fleetio integrations?
Simplified onboarding for Fleetio users
- Users no longer need to create and share long-lived, unrestricted API keys with integration providers.
- Instead, users authenticate and authorize an integration via a standard OAuth consent flow.
Security benefits
- Fine-grained permissions and scopes limit the integration's access.
- Tokens can be revoked independently without rotating a user's API key.
- Reduces risk of credential leakage from partner infrastructure.
High-level steps
-
Register your integration in Fleetio and configure a Redirect URL for the OAuth flow (exact URL must match the redirect registered in Fleetio).
-
Copy your Client ID and Client Secret from the Fleetio integration Oauth 2.0 settings.
-
Implement the standard OAuth 2.0 Authorization Code flow:
- Redirect the user to the Fleetio authorization endpoint.
- User authenticates, reviews requested permissions, chooses a Fleetio account they are associated with, and consents.
- Fleetio redirects back to your registered Redirect URL with
code(andstate). - Exchange the
codefor access token, refresh token, and account token at Fleetio's token endpoint.
-
In the token exchange response capture and persist:
access_token,refresh_token,expires_in, andaccount_token. -
Associate these tokens with an existing user record in your database so your integration can act on behalf of that user/account.
-
Use the
Authorization: Bearer <access_token>header and theAccount-Token: <account_token>header when calling the Fleetio API. You should also be sure to sendX-Api-Versionwith the Fleetio API date version you have used in testing your application, to ensure that as the API evolves, your Integration functions as expected.
Endpoints (examples)
- Authorization endpoint (authorize user & consent):
https://secure.fleetio.com/oauth/authorize
- Token endpoint (exchange code for tokens):
https://secure.fleetio.com/oauth/token
- API base (example):
https://secure.fleetio.com/api
Token exchange response
When exchanging the authorization code for tokens, the response is the standard OAuth response plus an account_token field. Example JSON payload returned from the token endpoint:
{
"access_token": "eyJ...",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "def456...",
"scope": "read write",
"account_token": "32dn92dn92"
}
You must store account_token along with the other tokens.
Storage & security recommendations
- Persist
access_token,refresh_token,expires_at(calculated), andaccount_tokenin a secure secrets store or encrypted database column. - Individual users may be members of more than one Fleetio account, and may authorize these separately. It is recommended to support multiple credential sets for single users.
- Associate tokens with a local
user_id(or integration-owner record) so you can audit and revoke when needed. - Rotate client secret if it is ever exposed.
- Use the refresh token to obtain new access tokens before expiry. When refreshing, the token response will include a refreshed
access_tokenand may include a newrefresh_tokenbut theaccount_tokenwill not change. Update stored values accordingly.
API request example
All API requests must include both the bearer access token and the account token header. Example GET request to list vehicles:
GET https://secure.fleetio.com/api/vehicles
Authorization: Bearer <ACCESS_TOKEN>
Account-Token: <ACCOUNT_TOKEN>
X-Api-Version: "2025-05-05"
Code samples
Below are concise examples demonstrating the Authorization Code flow, token exchange, persisting tokens, and making an API request. These use commonly adopted libraries where applicable.
Important: these examples are illustrative. Handle errors, retries, secure storage and token refresh logic fully in your production implementation.
Java (using okhttp for HTTP requests)
// Maven deps: com.squareup.okhttp3:okhttp:4.x, com.fasterxml.jackson.core:jackson-databind
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class FleetioOAuth {
private static final String TOKEN_URL = "https://secure.fleetio.com/oauth/token";
private static final String FLEETIO_API_VERSION = "2025-05-05"
private final OkHttpClient client = new OkHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
public Map<String, Object> exchangeCode(String clientId, String clientSecret, String code, String redirectUri) throws IOException {
RequestBody form = new FormBody.Builder()
.add("grant_type", "authorization_code")
.add("code", code)
.add("redirect_uri", redirectUri)
.add("client_id", clientId)
.add("client_secret", clientSecret)
.build();
Request req = new Request.Builder()
.url(TOKEN_URL)
.post(form)
.build();
try (Response resp = client.newCall(req).execute()) {
if (!resp.isSuccessful()) throw new IOException("Token exchange failed: " + resp);
String body = resp.body().string();
return mapper.readValue(body, Map.class);
}
}
// Example: making an API request using stored tokens
public String getVehicles(String accessToken, String accountToken) throws IOException {
Request req = new Request.Builder()
.url("https://secure.fleetio.com/api/vehicles")
.addHeader("Authorization", "Bearer " + accessToken)
.addHeader("Account-Token", accountToken)
.addHeader("X-Api-Version", FLEETIO_API_VERSION)
.get()
.build();
try (Response resp = client.newCall(req).execute()) {
if (!resp.isSuccessful()) throw new IOException("API call failed: " + resp);
return resp.body().string();
}
}
}
PHP (using Guzzle)
// composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$tokenUrl = 'https://secure.fleetio.com/oauth/token';
$fleetioApiVersion = 'https://secure.fleetio.com/oauth/token';
$client = new Client();
function exchangeCode($clientId, $clientSecret, $code, $redirectUri) {
global $client, $tokenUrl;
$response = $client->post($tokenUrl, [
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $redirectUri,
'client_id' => $clientId,
'client_secret' => $clientSecret
]
]);
$body = (string) $response->getBody();
return json_decode($body, true);
}
function getVehicles($accessToken, $accountToken) {
global $client;
$res = $client->get('https://secure.fleetio.com/api/vehicles', [
'headers' => [
'Authorization' => "Bearer {$accessToken}",
'Account-Token' => $accountToken,
'X-Api-Version' => $fleetioApiVersion
]
]);
return (string) $res->getBody();
}
Python (using requests)
# pip install requests
import requests
TOKEN_URL = 'https://secure.fleetio.com/oauth/token'
FLEETIO_API_VERSION = "2025-05-05"
API_VEHICLES = 'https://secure.fleetio.com/api/vehicles'
def exchange_code(client_id, client_secret, code, redirect_uri):
data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'client_id': client_id,
'client_secret': client_secret,
}
r = requests.post(TOKEN_URL, data=data)
r.raise_for_status()
return r.json() # contains access_token, refresh_token, account_token, expires_in
def get_vehicles(access_token, account_token):
headers = {
'Authorization': f'Bearer {access_token}',
'Account-Token': account_token,
'X-Api-Version': FLEETIO_API_VERSION,
}
r = requests.get(API_VEHICLES, headers=headers)
r.raise_for_status()
return r.json()
# Example usage:
# token_resp = exchange_code(CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI)
# save token_resp['access_token'], token_resp['refresh_token'], token_resp['account_token']
# vehicles = get_vehicles(token_resp['access_token'], token_resp['account_token'])
Go (using golang.org/x/oauth2)
// go get golang.org/x/oauth2
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"golang.org/x/oauth2"
)
var (
oauthConfig = &oauth2.Config{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
RedirectURL: "https://yourapp.example.com/oauth/callback",
Scopes: []string{"read write"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://secure.fleetio.com/oauth/authorize",
TokenURL: "https://secure.fleetio.com/oauth/token",
},
}
)
const FleetioApiVersion = "2025-05-05"
// The token exchange using oauth2 lib returns an oauth2.Token, but the raw response
// may contain account_token. We need to capture it from the token endpoint response.
func exchangeCode(ctx context.Context, code string) (map[string]interface{}, error) {
// Use the oauth2 library to exchange the code, but we also need to access the raw response
token, err := oauthConfig.Exchange(ctx, code)
if err != nil {
return nil, err
}
// token contains AccessToken and RefreshToken and Expiry. To read account_token, do a manual request.
// Alternatively, you can re-request the token endpoint directly. Here's a simple manual exchange example:
resp, err := http.PostForm("https://secure.fleetio.com/oauth/token", url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {oauthConfig.RedirectURL},
"client_id": {oauthConfig.ClientID},
"client_secret": {oauthConfig.ClientSecret},
})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var raw map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
return nil, err
}
return raw, nil
}
func getVehicles(accessToken, accountToken string) ([]map[string]interface{}, error) {
req, _ := http.NewRequest("GET", "https://secure.fleetio.com/api/vehicles", nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Account-Token", accountToken)
req.Header.Set("X-Api-Version", FleetioApiVersion)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var data []map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
return data, nil
}
func main() {
// This main is illustrative. Hook the exchangeCode call into your OAuth callback handler.
fmt.Println("See functions exchangeCode and getVehicles for usage.")
}
Ruby (using oauth2 gem)
Dependencies
# Gemfile
gem 'oauth2'
gem 'faraday'
bundle install
OAuth Client Configuration
require 'oauth2'
require 'faraday'
require 'json'
require 'securerandom'
CLIENT_ID = ENV['FLEETIO_CLIENT_ID']
CLIENT_SECRET = ENV['FLEETIO_CLIENT_SECRET']
REDIRECT_URI = 'https://yourapp.example.com/oauth/callback'
SITE_URL = 'https://secure.fleetio.com'
AUTHORIZE_URL = '/oauth/authorize'
TOKEN_URL = '/oauth/token'
FLEETIO_API_VERSION = "2025-05-05"
Step 1: Redirect User to Fleetio Authorization
client = OAuth2::Client.new(
CLIENT_ID,
CLIENT_SECRET,
site: SITE_URL,
authorize_url: AUTHORIZE_URL,
token_url: TOKEN_URL
)
authorization_url = client.auth_code.authorize_url(
redirect_uri: REDIRECT_URI,
scope: 'read write',
state: SecureRandom.hex(16)
)
# Redirect the user to authorization_url
puts authorization_url
Step 2: Exchange Authorization Code for Tokens
Fleetio's token response includes a non-standard account_token field. The oauth2 gem exposes this value via token.params.
def exchange_code_for_tokens(client, code)
token = client.auth_code.get_token(
code,
redirect_uri: REDIRECT_URI
)
{
access_token: token.token,
refresh_token: token.refresh_token,
expires_at: token.expires_at,
account_token: token.params['account_token']
}
end
# Example usage in an OAuth callback handler
# tokens = exchange_code_for_tokens(client, params[:code])
# Persist tokens securely and associate with a user record
Step 3: Make an Authenticated Fleetio API Request
Example request to GET https://secure.fleetio.com/api/vehicles:
def get_vehicles(access_token, account_token)
conn = Faraday.new(url: 'https://secure.fleetio.com') do |f|
f.request :authorization, 'Bearer', access_token
f.response :raise_error
end
response = conn.get('/api/vehicles') do |req|
req.headers['Account-Token'] = account_token
req.headers['X-Api-Version'] = FLEETIO_API_VERSION
end
JSON.parse(response.body)
end
# vehicles = get_vehicles(user.access_token, user.account_token)
Refreshing the Access Token
def refresh_access_token(client, refresh_token)
token = OAuth2::AccessToken.new(client, nil, refresh_token: refresh_token)
refreshed = token.refresh!
{
access_token: refreshed.token,
refresh_token: refreshed.refresh_token,
expires_at: refreshed.expires_at,
account_token: refreshed.params['account_token']
}
end
Refreshing tokens
When access_token expires, call the token endpoint with grant_type=refresh_token and include the refresh_token, client credentials, etc. The response may include a new access_token, and refresh_token, but account_token will remain the same. Update stored tokens accordingly.
Error handling & revocation
- Handle standard OAuth errors (invalid_grant, invalid_client, etc.).
- If a user revokes access from Fleetio or you receive a 401, perform safe cleanup and notify the user.
- If you receive a 403, ensure that you have correctly configured the permissions required for your Integration. Also, ensure that the Fleetio user who has authorized your integration is able to access the resources needed for its functionality. If you have changed permissions for your Integration, you may need to ask the user to re-authorize it.
- Implement logging and monitoring for token refresh failures and repeated API errors.
Migration notes
- For integrations that previously required users to share API keys, migrating to OAuth 2.0 improves security and the user experience.
- Offer a migration path that re-associates existing user records with OAuth tokens once users complete the new OAuth consent flow.