### Initialize and Run OAuth2 Sample Application Source: https://github.com/volvo-cars/developer-portal-api-samples/blob/main/oauth2-code-flow-sample/README.md Commands to install project dependencies and start the local Node.js server. These commands assume a standard Node.js environment with npm installed. ```zsh npm install ``` ```zsh npm run start ``` -------------------------------- ### GET /vehicles/{vin} Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Retrieves detailed information for a specific vehicle using its VIN. ```APIDOC ## GET /vehicles/{vin} ### Description Fetches detailed metadata for a specific vehicle, including model name and model year. ### Method GET ### Endpoint https://api.volvocars.com/connected-vehicle/v2/vehicles/{vin} ### Parameters #### Path Parameters - **vin** (string) - Required - The unique VIN of the vehicle. #### Headers - **vcc-api-key** (string) - Required - Your application key. - **authorization** (string) - Required - Bearer token. ### Request Example curl -X GET "https://api.volvocars.com/connected-vehicle/v2/vehicles/YV1ABC12345678901" \ -H "accept: application/json" \ -H "vcc-api-key: YOUR_VCC_API_KEY" \ -H "authorization: Bearer YOUR_ACCESS_TOKEN" ### Response #### Success Response (200) - **modelYear** (integer) - The year of the vehicle model. - **descriptions** (object) - Contains the model name. #### Response Example { "modelYear": 2023, "descriptions": { "model": "XC90" } } ``` -------------------------------- ### GET /vehicles Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Fetches a list of all vehicles associated with the authenticated Volvo ID account. ```APIDOC ## GET /vehicles ### Description Retrieves an array of vehicle objects connected to the current user's Volvo ID account. ### Method GET ### Endpoint https://api.volvocars.com/connected-vehicle/v2/vehicles ### Parameters #### Headers - **vcc-api-key** (string) - Required - Your application key from the developer portal. - **authorization** (string) - Required - Bearer token obtained via OAuth2. ### Request Example curl -X GET "https://api.volvocars.com/connected-vehicle/v2/vehicles" \ -H "accept: application/json" \ -H "vcc-api-key: YOUR_VCC_API_KEY" \ -H "authorization: Bearer YOUR_ACCESS_TOKEN" ### Response #### Success Response (200) - **data** (array) - List of vehicle objects containing VIN and identifiers. #### Response Example { "data": [ { "vin": "YV1ABC12345678901" }, { "vin": "YV1XYZ98765432109" } ] } ``` -------------------------------- ### Connected Vehicle Sample Configuration - Bash Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Environment variables for the connected-vehicle-fetch-sample. Requires an API key for accessing Volvo's services and an OAuth2 Bearer token for authentication. ```bash # .env file for connected-vehicle-fetch-sample VCC_API_KEY=your_application_key_here ACCESS_TOKEN=your_oauth2_bearer_token_here ``` -------------------------------- ### OAuth2 Sample Configuration - Bash Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Environment variables for the oauth2-code-flow-sample. Includes client ID, client secret, redirect URI, requested scopes, and the port for the local server. ```bash # .env file for oauth2-code-flow-sample CLIENT_ID=your_client_id_here CLIENT_SECRET=your_client_secret_here REDIRECT_URI=http://localhost:3000/callback SCOPES=openid profile email PORT=3000 ``` -------------------------------- ### Initialize OAuth2 Configuration Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Discovers the Volvo ID OpenID configuration to set up the client for authorization and token exchange. ```javascript import * as client from "openid-client"; const clientId = process.env.CLIENT_ID; const clientSecret = process.env.CLIENT_SECRET; const config = await client.discovery( new URL("https://volvoid.eu.volvocars.com"), clientId, clientSecret ); ``` -------------------------------- ### Environment Configuration Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Environment variables for configuring the Connected Vehicle and OAuth2 samples. ```APIDOC ## Environment Configuration ### Connected Vehicle Sample Configuration #### Description Environment variables required for the Connected Vehicle sample. #### Variables - **VCC_API_KEY** (string) - Your application key for accessing the Connected Vehicle API. - **ACCESS_TOKEN** (string) - Your OAuth2 bearer token for authenticated requests. ### OAuth2 Sample Configuration #### Description Environment variables required for the OAuth2 code flow sample. #### Variables - **CLIENT_ID** (string) - Your OAuth2 client ID. - **CLIENT_SECRET** (string) - Your OAuth2 client secret. - **REDIRECT_URI** (string) - The redirect URI registered with Volvo ID. - **SCOPES** (string) - The requested OAuth2 scopes (e.g., "openid profile email"). - **PORT** (number) - The port the application will run on. ### Example .env file for Connected Vehicle Sample ```bash VCC_API_KEY=your_application_key_here ACCESS_TOKEN=your_oauth2_bearer_token_here ``` ### Example .env file for OAuth2 Sample ```bash CLIENT_ID=your_client_id_here CLIENT_SECRET=your_client_secret_here REDIRECT_URI=http://localhost:3000/callback SCOPES=openid profile email PORT=3000 ``` ``` -------------------------------- ### Generate OAuth2 Login URL with PKCE Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Creates a secure authorization URL using PKCE (Proof Key for Code Exchange) to facilitate the OAuth2 login flow. ```javascript app.get("/auth/login", async (req, res) => { let code_verifier = client.randomPKCECodeVerifier(); let code_challenge = await client.calculatePKCECodeChallenge(code_verifier); req.session.code_verifier = code_verifier; const parameters = { redirect_uri: process.env.REDIRECT_URI, scope: process.env.SCOPES, code_challenge, code_challenge_method: "S256", }; let loginUrl = client.buildAuthorizationUrl(config, parameters); res.status(200).json({ loginUrl: loginUrl.href }); }); ``` -------------------------------- ### Authorization Code Exchange Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Handles the OAuth2 callback after successful Volvo ID login. Exchanges the authorization code for access and refresh tokens using the PKCE code verifier. ```APIDOC ## GET /callback ### Description Handles the OAuth2 callback after successful Volvo ID login. Exchanges the authorization code for access and refresh tokens using the PKCE code verifier. ### Method GET ### Endpoint /callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from Volvo ID. - **state** (string) - Required - The state parameter used to prevent CSRF attacks. ### Request Example (No request body for GET request) ### Response #### Success Response (302) Redirects to the root path ('/') upon successful token exchange. #### Error Response (500) - **message** (string) - "Authentication failed" - If the token exchange fails. ### Request Example ```javascript // Server endpoint: GET /callback (your redirect URI path) app.get("/callback", async (req, res) => { try { const protocol = req.protocol; const host = req.get("host"); const originalUrl = req.originalUrl; const currentURL = `${protocol}://${host}${originalUrl}`; // Exchange authorization code for tokens let tokenSet = await client.authorizationCodeGrant( config, new URL(currentURL), { pkceCodeVerifier: req.session.code_verifier, idTokenExpected: true, } ); // Store tokens in cookies res.cookie("refresh_token", tokenSet.refresh_token); res.cookie("access_token", tokenSet.access_token); res.redirect("/"); } catch (e) { console.error(`Request failed with error "${e}"`); res.status(500).send("Authentication failed"); } }); ``` ``` -------------------------------- ### List Connected Vehicles via API Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Fetches a list of all vehicles associated with a Volvo ID account. Requires a valid VCC API key and an OAuth2 bearer token. ```javascript const baseUrl = "https://api.volvocars.com/connected-vehicle/v2"; const fetchVehicles = async () => { const response = await fetch(`${baseUrl}/vehicles`, { headers: { accept: "application/json", "vcc-api-key": process.env.VCC_API_KEY, authorization: `Bearer ${process.env.ACCESS_TOKEN}`, }, }); const responseBody = await response.json(); if (!response.ok) { throw new Error(`Request failed with status ${responseBody.status} and message "${responseBody.error.message}"`); } return responseBody.data; }; const vehicles = await fetchVehicles(); console.log(`There are ${vehicles.length} cars connected to this Volvo ID account.`); ``` ```bash curl -X GET "https://api.volvocars.com/connected-vehicle/v2/vehicles" \ -H "accept: application/json" \ -H "vcc-api-key: YOUR_VCC_API_KEY" \ -H "authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Authorization Code Exchange - JavaScript Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Handles the OAuth2 callback, exchanging an authorization code for access and refresh tokens using PKCE. It stores the tokens in cookies and redirects the user. This endpoint is typically the redirect URI specified during the OAuth2 client registration. ```javascript app.get("/callback", async (req, res) => { try { const protocol = req.protocol; const host = req.get("host"); const originalUrl = req.originalUrl; const currentURL = `${protocol}://${host}${originalUrl}`; // Exchange authorization code for tokens let tokenSet = await client.authorizationCodeGrant( config, new URL(currentURL), { pkceCodeVerifier: req.session.code_verifier, idTokenExpected: true, } ); // Store tokens in cookies res.cookie("refresh_token", tokenSet.refresh_token); res.cookie("access_token", tokenSet.access_token); res.redirect("/"); } catch (e) { console.error(`Request failed with error "${e}"`); res.status(500).send("Authentication failed"); } }); ``` -------------------------------- ### Retrieve Specific Vehicle Details Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Retrieves detailed information, such as model year and name, for a specific vehicle using its VIN. Requires authentication via VCC API key and bearer token. ```javascript const fetchVehicleDetails = async (vinNumber) => { const response = await fetch(`${baseUrl}/vehicles/${vinNumber}`, { headers: { accept: "application/json", "vcc-api-key": process.env.VCC_API_KEY, authorization: `Bearer ${process.env.ACCESS_TOKEN}`, }, }); const responseBody = await response.json(); if (!response.ok) { throw new Error(`Request failed with status ${responseBody.status} and message "${responseBody.error.message}"`); } return responseBody.data; }; const details = await fetchVehicleDetails("YV1ABC12345678901"); console.log(`Vehicle is a model ${details.descriptions.model} from ${details.modelYear}.`); ``` ```bash curl -X GET "https://api.volvocars.com/connected-vehicle/v2/vehicles/YV1ABC12345678901" \ -H "accept: application/json" \ -H "vcc-api-key: YOUR_VCC_API_KEY" \ -H "authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Refresh Access Token Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Uses a refresh token to obtain a new access token when the current one expires. ```APIDOC ## POST /auth/refresh ### Description Uses a refresh token to obtain a new access token when the current one expires. ### Method POST ### Endpoint /auth/refresh ### Parameters #### Request Body - **refreshToken** (string) - Required - The refresh token obtained during the initial authorization. ### Request Example ```json { "refreshToken": "your_refresh_token_here" } ``` ### Response #### Success Response (200) - **refreshToken** (string) - The new refresh token. - **accessToken** (string) - The new access token. #### Response Example ```json { "refreshToken": "new_refresh_token_here", "accessToken": "new_access_token_here" } ``` ### Client-side Usage Example ```javascript const postRefreshToken = async (refreshToken) => { const response = await fetch(`${window.location.origin}/auth/refresh`, { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ refreshToken }), }); return response.json(); }; const tokens = await postRefreshToken(currentRefreshToken); console.log("New access token:", tokens.accessToken); ``` ``` -------------------------------- ### Refresh Access Token - JavaScript Source: https://context7.com/volvo-cars/developer-portal-api-samples/llms.txt Uses a refresh token to obtain a new access token when the current one expires. This endpoint is designed to be called from the server to securely refresh tokens. A client-side function is also provided to demonstrate how to initiate the refresh request. ```javascript // Server endpoint: POST /auth/refresh app.post("/auth/refresh", async (req, res) => { const tokenSet = await client.refreshTokenGrant( config, req.body.refreshToken ); res.status(200).json({ refreshToken: tokenSet.refresh_token, accessToken: tokenSet.access_token, }); }); // Client-side usage const postRefreshToken = async (refreshToken) => { const response = await fetch(`${window.location.origin}/auth/refresh`, { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ refreshToken }), }); return response.json(); }; const tokens = await postRefreshToken(currentRefreshToken); console.log("New access token:", tokens.accessToken); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.