### Aircall OAuth Flow Example (Ruby) Source: https://developer.aircall.io/api-references This example, referenced from GitHub, illustrates the implementation of the Aircall OAuth flow using Ruby. It provides a practical guide for developers to integrate their applications with Aircall's services. ```ruby # This is a placeholder for the actual Ruby code example. # Please refer to the official Aircall documentation or their GitHub repository # for the complete and up-to-date Ruby example. # # Example structure might involve: # 1. Setting up routes for install_uri and redirect_uri. # 2. Redirecting to Aircall's authorization URL. # 3. Handling the callback with the authorization code. # 4. Exchanging the code for an access token. # 5. Storing the access token for subsequent API calls. # require 'sinatra' # require 'rest-client' # require 'json' # # ... (rest of the example code) ``` -------------------------------- ### Basic Web Server Setup (Node.js) Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works A simple Node.js web server setup using Express to handle incoming requests from Aircall during the OAuth flow. ```APIDOC ## Web Server Setup ### Description This example demonstrates a basic Node.js web server using the Express framework. It's configured to parse URL-encoded and JSON request bodies, which are necessary for handling data sent by Aircall during the OAuth process. ### Language Node.js (JavaScript) ### Code ```javascript /** * server.js * Configure your app server with express */ const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // body-parser will be useful later // to extract POST params Aircall will send app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); const PORT = 5000; app.listen(PORT, () => { console.info('[server] server started'); console.info('[server] visit http://localhost:' + PORT); }); ``` ### Usage 1. Save the code as `server.js`. 2. Install dependencies: `npm install express body-parser`. 3. Start the server: `node server.js`. ``` -------------------------------- ### Full Aircall Integration Example Source: https://developer.aircall.io/tutorials/build-a-smart-routing-system This comprehensive example demonstrates a full Aircall integration, including setting up an Express server, parsing JSON bodies, and implementing functions to get contact information, associate agents, retrieve agent Aircall IDs, and forward calls. It requires Express, body-parser, and request libraries. ```javascript const app = require('express')(), bodyParser = require('body-parser'), request = require('request'); const API_ID = 'YOUR_APP_ID'; const API_TOKEN = 'YOUR_APP_TOKEN'; app.use(bodyParser.json()); /** * Your App framework */ const myApp = { /** * Return a contact found in your Database * @phoneNumber: the contact phoneNumber, e164 formatted */ getContact: (phoneNumber) => { // TODO: Search for a contact in your Database here // and set the contactFetched variable: const contactFetched = ...; // your secret recipe return contactFetched; }, /** * Match a contact to an agent * Return the agent email * @contact: a contact ID of your own */ getAssociatedAgentEmail: (contact) => { // TODO: Match the associated agent with the contact param // and set the associatedAgentEmail variable: const associatedAgentEmail = ...; // your secret recipe again return associatedAgentEmail; }, /** * Match a contact to an agent * @agentEmail: your agent email address */ getAgentAircallID: (agentEmail, callback) => { // Populate Aircall API url with API_ID ann API_TOKEN const uri = `https://${API_ID}:${API_TOKEN}@api.aircall.io/v1/users`; request.get(uri, (error, response, body) => { // We use ES6 `Array.prorotype.find` function to find // a user in the body.users array: const data = JSON.parse(body); const agent = data.users.find((user) => { return user.email === agentEmail; }); callback(agent.id); }); }, /** * Forward a call to a user * @callId: the call you want to be transferred * @userId: the user you want to forward the call to */ forwardCall: (callId, userId) => { // Populate Aircall API url with API_ID ann API_TOKEN const uri = `https://${API_ID}:${API_TOKEN}@api.aircall.io/v1/calls/${callId}/transfers`; request.post(uri, { json: { user_id: userId } }, (error, response, body) => { console.log(`Call ${callId} transferred to ${userId}`); } ); } }; /** * [GET] / route will show a basic JSON file */ app.get('/', (req, res) => { res.json({'message': 'Server is running'}); }); /** * [POST] /aircall/calls will listen to Aircall webhook */ app.post('/aircall/calls', (req, res) => { if (req.body.event === 'call.created') { if (req.body.data.direction === 'inbound') { // 1. Get the caller contact: ``` -------------------------------- ### GET /oauth/install Source: https://developer.aircall.io/labs/weather Initiates the OAuth installation process by redirecting the user to Aircall's authorization URL. ```APIDOC ## GET /oauth/install ### Description Install page, redirects to Aircall authorize URL ### Method GET ### Endpoint /oauth/install ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (302) - **Redirect** - Redirects to the Aircall authorization URL. #### Response Example None ``` -------------------------------- ### Contact Response Example - GET /v1/contacts Source: https://developer.aircall.io/api-references Example JSON response for the 'List all Contacts' endpoint, showcasing the structure of contact objects, including metadata, and nested arrays for phone numbers and emails. Timestamps are in UTC format. ```JSON { "meta": { "count": 2, "total": 2, "current_page": 1, "per_page": 20, "next_page_link": null, "previous_page_link": null }, "contacts": [ { "id": 710, "direct_link": "https://api.aircall.io/v1/contacts/710", "first_name": "Vicente", "last_name": "Abad", "company_name": null, "information": null, "is_shared": true, "created_at": 1400691054, "updated_at": 1444336506, "emails": [], "phone_numbers": [ { "id": 3367, "label": "Mobile", "value": "+34664673697" } ] }, { "id": 711, "direct_link": "https://api.aircall.io/v1/contacts/711", "first_name": "Margaret", "last_name": "Morrison", "company_name": "TeleWorm", "information": null, "is_shared": true, "created_at": 1400692007, "updated_at": 1444336507, "emails": [], "phone_numbers": [ { "id": 3368, "label": "Mobile", "value": "+34768776683" }, { "id": 3369, "label": "Work", "value": "+49111000460" } ], "emails": [ { "id": 3200, "label": "Work", "value": "m.morrison@teleworm.es" } ] } ] } ``` -------------------------------- ### List all Users V2 - Response Source: https://developer.aircall.io/api-references This is an example JSON response for the GET /v2/users endpoint. It contains metadata about the pagination and a list of user objects, each with detailed attributes like ID, name, email, and availability status. ```JSON { "meta": { "count": 3, "total": 3, "current_page": 1, "per_page": 20, "next_page_link": null, "previous_page_link": null }, "users": [ { "id": 456, "direct_link": "https://api.aircall.io/v2/users/456", "name": "John Doe", "email": "john.doe@aircall.io", "available": true, "availability_status": "available", "created_at": "2019-12-29T10:03:18.000Z", "time_zone": "America/New_York", "language": "en-US", "substatus": "always_opened", "wrap_up_time": 0, "extension": "001" }, { "id": 457, "direct_link": "https://api.aircall.io/v2/users/457", "name": "Amy Rudd", "email": "amy.rudd@aircall.io", "available": true, "availability_status": "custom", "created_at": "2019-12-30T18:10:21.000Z", "time_zone": "Etc/UTC", "language": "en-US", "substatus": "always_opened", "wrap_up_time": 0, "extension": "002" }, { "id": 458, "direct_link": "https://api.aircall.io/v2/users/458", "name": "Vera Martin", "email": "vera.martin@aircall.io", "available": false, "availability_status": "unavailable", "created_at": "20120-01-02T09:01:58.000Z", "time_zone": "Europe/Paris", "language": "fr-FR", "substatus": "always_opened", "wrap_up_time": 0, "extension": "003" } ] } ``` -------------------------------- ### Pagination Meta Object Example Source: https://developer.aircall.io/api-references This example demonstrates the structure of the 'meta' object returned in API responses when results are paginated. It includes details about the current page, total items, and links for navigation. ```json { "meta": { "count": 20, "total": 2234, "current_page": 1, "per_page": 20, "next_page_link": "https://api.aircall.io/v1/calls?page=2&per_page=20", "previous_page_link": null }, ... } ``` -------------------------------- ### POST /v1/integrations/enable - Enable Integration Source: https://developer.aircall.io/api-references Enables the integration associated with the access token and activates webhooks. This endpoint can be used to re-enable a disabled integration. If the `install` query parameter is set to true, the user will be redirected to the integration's settings page in the dashboard after installation. ```APIDOC ## POST /v1/integrations/enable ### Description Enables the integration associated with the access token and activates webhooks. This endpoint can be used to re-enable a disabled integration. If the `install` query parameter is set to true, the user will be redirected to the integration's settings page in the dashboard after installation. This endpoint can only be used for integrations built by Aircall or third-party integrations using OAuth. ### Method POST ### Endpoint /v1/integrations/enable ### Parameters #### Query Parameters - **install** (boolean) - Optional. If true, redirects the user to the integration settings page after installation. #### Request Body None ### Response #### Success Response (204) Success. #### Error Responses - **403** - Forbidden. Invalid Bearer access token. - **403** - Forbidden. Cannot be used with API KEY (Oauth only). ### Request Example ``` POST /v1/integrations/enable?install=true ``` ### Response Example Status: 204 OK ``` -------------------------------- ### Implement install_uri Endpoint for OAuth Source: https://developer.aircall.io/labs/weather Defines the public GET endpoint '/oauth/install' which redirects users to Aircall's consent page. It uses the 'install' method from the OAuth Controller to construct the Aircall authorization URL. ```javascript import { install } from '../controllers/oauth_controller'; router.get('/oauth/install', install); ``` -------------------------------- ### Initialize Aircall Call Queues and Start Web Application Source: https://developer.aircall.io/advanced-tutorials/inbound-call-queues Initializes data structures for Aircall call queues by querying Aircall Numbers API. It then starts the web application on a specified port. Dependencies include the 'request' library and API_KEY/PORT constants. This function is crucial for setting up the application's core data. ```javascript /* Define various functions that will be re-used to help improve portability and readability. */ const callQueueMgmtApp = { /* * Function that initializes the various data structures. */ initialize: () => { console.log("Populating the queues for each Aircall number..."); // Create the options for the API request var numbersQuery = { 'method': 'GET', 'url': 'https://api.aircall.io/v1/numbers?per_page=50', 'headers': { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + API_KEY } }; // Make API request (TO-DO: paginate if results are too large) request(numbersQuery, (err, res) => { if (err) throw new Error(err); // Contains the JSON-formatted data from response const data = JSON.parse(res.body); // For each Aircall phone number returned... data.numbers.forEach((number) => { // Keep track of the "general" call queue and "waiting" call queue console.log("Creating a queue for Aircall Number ID " + number.id + " (" + number.name + ")"); callQueues[number.id] = {'general': {}, 'waiting': {}}; }); }); // TO-DO: If you need to pull the URL MP3s for welcome messages from // another source, you can do that here } }; // Initialize the queues for each Aircall phone number in this instance callQueueMgmtApp.initialize(); // Start listening to specific port app.listen(PORT, () => { console.log("Starting app at port: " + PORT); }); ``` -------------------------------- ### Dockerfile for Aircall Weather App Source: https://developer.aircall.io/labs/weather A multi-stage Dockerfile used to build and run the Aircall Weather application. It sets up the Node.js environment, installs dependencies, copies application code, and defines the command to start the server. It includes stages for building dependencies and for the final release image. ```dockerfile FROM node:12-alpine as base WORKDIR /app COPY package.json . FROM base as dependencies RUN npm install --production ########## RELEASE ########## FROM base as release COPY --from=dependencies /app/node_modules node_modules COPY . . LABEL "com.datadoghq.ad.logs"='[{"source": "nodejs", "service": "weather"}]' EXPOSE 5000 CMD ["node", "-r", "dotenv/config", "src/server.js"] ########## TEST ########## FROM dependencies as test COPY . . RUN npm install --development ``` -------------------------------- ### Docker Compose for Local Development Source: https://developer.aircall.io/labs/weather Command to start the Aircall Weather application using Docker Compose. This command builds the Docker images if necessary and then starts the services defined in the docker-compose.yml file, providing a complete local development environment. ```bash docker-compose up --build ``` -------------------------------- ### GET / Source: https://developer.aircall.io/labs/weather Renders the main page of the application. ```APIDOC ## GET / ### Description Render the main page ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **HTML** - The main application page. #### Response Example None ``` -------------------------------- ### Create Basic Server Route (Go) Source: https://developer.aircall.io/tutorials/how-to-create-a-webhook-integration Initializes a Gin web server in Go, setting up a GET route for the root path that returns a JSON message. This requires the 'gin-gonic/gin' package and assumes the PORT environment variable is set. ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { port := os.Getenv("PORT") if port == "" { log.Fatal("$PORT must be set") } router := gin.Default() router.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Server is running"}) }) router.Run(":" + port) } ``` -------------------------------- ### Install URI Endpoint Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint is called by Aircall when an Admin initiates the OAuth flow. It redirects the user to Aircall's authorization server. ```APIDOC ## GET /aircall/oauth/install ### Description This endpoint is the first step in the Aircall OAuth flow. It redirects the user to Aircall's authorization server to grant permissions. ### Method GET ### Endpoint /aircall/oauth/install ### Query Parameters - **client_id** (string) - Required - The client ID provided by Aircall upon app registration. - **redirect_uri** (string) - Required - The callback URI registered with Aircall. - **response_type** (string) - Required - Must be set to `code`. - **scope** (string) - Required - Must be set to `public_api`. - **state** (string) - Optional - A string value used to maintain state and prevent CSRF attacks. ### Request Example (No request body for GET requests) ### Response #### Redirect - **302 Found** - Redirects the user to the Aircall authorization URL. #### Response Example (This is a redirect, not a JSON response) Redirects to: `https://dashboard.aircall.io/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=https://your.server.com/aircall/oauth/callback&response_type=code&scope=public_api` ``` -------------------------------- ### Setup Express Web Server for Aircall OAuth Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This Javascript code sets up a basic Express web server using Node.js. It configures the server to listen on a specified port and uses body-parser to handle incoming request data, which is necessary for processing Aircall's authentication requests. ```javascript /** * server.js * Configure your app server with express */ const express = require('express'); bodyParser = require('body-parser'); const app = express(); // body-parser will be useful later // to extract POST params Aircall will send app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); const PORT = 5000; app.listen(PORT, () => { console.info('[server] server started'); console.info('[server] visit http://localhost:' + PORT); }); ``` -------------------------------- ### NodeJS Web Server Setup with Express Source: https://developer.aircall.io/labs/weather Sets up the main NodeJS web server using the Express framework. It includes middleware for handling request bodies and serving static files from the 'public/' directory. ```javascript const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // Middleware to parse request bodies app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // Middleware to serve static files app.use(express.static('public')); // ... other configurations and routes ... const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` -------------------------------- ### Implement Aircall Install URI Endpoint (JavaScript) Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint is the first step in the Aircall OAuth flow. It redirects the user to Aircall's authorization server with necessary parameters like client ID, callback URI, response type, and scope. It requires HTTPS for secure communication. ```javascript /** * server.js */ ... /** * Endpoint requested by Aircall as the first step of the Install flow */ app.get('/aircall/oauth/install', (req, res) => { // Aircall endpoint that we need to redirect this request to: const aircallUrl = 'https://dashboard.aircall.io/oauth/authorize'; // client_id given by Aircall when you registered your app: const clientId = 'YOUR_CLIENT_ID'; // Callback endpoint given to Aircall when registering your app (see next step) const callbackUri = 'https://your.server.com/aircall/oauth/callback'; // The final url composed of: // - clientId // - callbackUri // - response_type=code // - scope=public_api const finalUrl = aircallUrl + '?client_id=' + clientId + '&redirect_uri=' + callbackUri + '&response_type=code' + '&scope=public_api'; // Redirect immediately this request to the finalUrl res.redirect(finalUrl); }); ``` -------------------------------- ### List All Calls - Response Example Source: https://developer.aircall.io/api-references This snippet provides an example of a successful JSON response when listing calls. It includes metadata about the pagination and a list of call objects, each containing details like ID, direction, status, timestamps, duration, associated user, contact, number, comments, tags, and IVR options selected. The `fetch_contact` parameter defaults to false, meaning contact details are not included unless explicitly requested. ```json { "meta": { "count": 20, "total": 2234, "current_page": 1, "per_page": 20, "next_page_link": "https://api.aircall.io/v1/calls?order=asc&page=2&per_page=20", "previous_page_link": null }, "calls": [ { "id": 812, "sid": "CA1234567890", "direct_link": "https://api.aircall.io/v1/calls/812", "direction": "outbound", "status": "done", "missed_call_reason": null, "started_at": 1584998199, "answered_at": 1584998205, "ended_at": 1584998210, "duration": 11, "voicemail": null, "recording": null, "asset": null, "raw_digits": "+1 800-123-4567", "user": { "id": 456, "direct_link": "https://api.aircall.io/v1/users/456", "name": "John Doe", "email": "john.doe@aircall.io", "available": true, "availability_status": "available", "created_at": "2019-12-29T10:03:18.000Z", "time_zone": "America/New_York", "language": "en-US" }, "contact": null, "archived": false, "assigned_to": null, "transferred_by": null, "transferred_to": null, "cost": "2.34", "number": { "id": 1234, "direct_link": "https://api.aircall.io/v1/numbers/1234", "name": "French Office", "digits": "+33 1 76 11 11 11", "created_at": "2020-01-02T11:41:01.000Z", "country": "FR", "time_zone": "Europe/Paris", "open": true, "availability_status": "custom", "is_ivr": true, "live_recording_activated": true, "priority": null, "messages": { ... } }, "comments": [ { "id": 735, "content": "Please call back this customer!", "posted_at": 1587994808, "posted_by": { "id": 456, "direct_link": "https://api.aircall.io/v1/users/456", "name": "Johnn Doe", "email": "john.doe@aircall.io", "available": true, "availability_status": "available", "created_at": "2019-12-29T10:03:18.000Z" } }, ... ], "tags": [ { "id": 678, "name": "General Inquiries", "created_at": 1587995020, "tagged_by": { "id": 456, "direct_link": "https://api.aircall.io/v1/users/456", "name": "Johnn Doe", "email": "john.doe@aircall.io", "available": true, "availability_status": "available", "created_at": "2019-12-29T10:03:18.000Z" } }, ... ], "teams": [], "ivr_options_selected": [ { "id": "5cb41cde-aed2-4357-a98c-e1b33d68851a", "title": "", "key": "1", "branch": "Default", "created_at": "2024-10-01T06:54:45.556Z", "transition_started_at": "2024-10-01T06:54:35.332Z", "transition_ended_at": "2024-10-01T06:54:45.513Z" } ] }, { "id": 813, "direct_link": "https://api.aircall.io/v1/calls/813", "direction": "inbound", "status": "done", "missed_call_reason": "no_available_agent", "started_at": 1584998199, "answered_at": null, "ended_at": 1584998210, "duration": 22, "voicemail": null, "recording": null, "asset": null, "raw_digits": "+1 800-123-4567", "user": null, "contact": null, "archived": false, "assigned_to": null, "transferred_by": null, "transferred_to": null, "cost": "0", "number": { "id": 1234, ... } }, ... ] } ``` -------------------------------- ### Enable Integration (POST /v1/integrations/enable) Source: https://developer.aircall.io/api-references Enables an integration associated with the access token and activates its webhooks. This is useful for re-enabling a previously disabled integration. An optional 'install' query parameter can redirect users to the integration's settings page upon first enablement. This endpoint is restricted to Aircall-built or OAuth-based third-party integrations. ```http POST /v1/integrations/enable?install=true ``` -------------------------------- ### POST /v1/oauth/token Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works Exchanges an OAuth code for a permanent access token. This token is required for authenticating all subsequent requests to the Aircall Public API. ```APIDOC ## POST /v1/oauth/token ### Description Exchanges an OAuth `code` for a permanent `access_token`. This `access_token` is then used as a Bearer token for all Public API requests. ### Method POST ### Endpoint `https://api.aircall.io/v1/oauth/token` ### Parameters #### Query Parameters None #### Request Body - **code** (string) - Required - The OAuth `code` received from Aircall. - **redirect_uri** (string) - Required - The URL previously defined for redirection. - **client_id** (string) - Required - Your application's client ID provided by Aircall. - **client_secret** (string) - Required - Your application's client secret provided by Aircall. - **grant_type** (string) - Required - Must be set to `authorization_code`. ### Request Example ```json { "code": "oauth_code_from_step_4", "redirect_uri": "https://your.server.com/aircall/oauth/callback", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "grant_type": "authorization_code" } ``` ### Response #### Success Response (200) - **access_token** (string) - The permanent access token. - **token_type** (string) - The type of token, usually 'Bearer'. - **expires_in** (integer) - The number of seconds until the token expires. #### Response Example ```json { "access_token": "permanent_access_token", "token_type": "Bearer", "expires_in": 7200 } ``` ``` -------------------------------- ### Redirect URI Endpoint Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint is called by Aircall after the Admin authorizes the application. It receives an OAuth code that needs to be exchanged for an access token. ```APIDOC ## GET /aircall/oauth/callback ### Description This endpoint is called by Aircall after the user authorizes the application. It receives an OAuth code in the query parameters, which is then used to obtain an access token. ### Method GET ### Endpoint /aircall/oauth/callback ### Query Parameters - **code** (string) - Required - The OAuth code provided by Aircall, valid for 10 minutes. - **state** (string) - Optional - The state parameter passed during the authorization request, used for verification. ### Request Example (No request body for GET requests) Example URL: `https://your.server.com/aircall/oauth/callback?code=AUTHORIZATION_CODE&state=CSRF_STATE_VALUE` ### Response #### Redirect - **302 Found** - Redirects the user to a success page or Aircall's success URL. #### Response Example (This is a redirect, not a JSON response) Redirects to: `https://dashboard.aircall.io/oauth/success` ``` -------------------------------- ### Set Up Server Endpoints with Sinatra (Ruby) Source: https://developer.aircall.io/tutorials/synchronize-contacts-with-your-web-application Defines the basic server structure using Sinatra with three endpoints: a contact listing page, a contact fetch endpoint, and a webhook handler. Assumes a 'Contact' model for data persistence. ```ruby require 'sinatra' get '/' do @contacts = Contact.all erb :index end post '/fetch' do end post '/webhook' do end ``` -------------------------------- ### Aircall OAuth Flow - Token Exchange Endpoint Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works After an admin authorizes your app, Aircall redirects them to your `redirect_uri` with an authorization `code`. This endpoint is where you exchange that code for an `access_token`. ```APIDOC ## POST /oauth/token ### Description This endpoint is used to exchange the authorization `code` received after user authorization for an `access_token`. This token is then used to authenticate requests to the Aircall Public API. ### Method POST ### Endpoint `https://dashboard.aircall.io/oauth/token` ### Parameters #### Request Body - **grant_type** (string) - Required - Must be set to `authorization_code`. - **client_id** (string) - Required - Your application's client ID. - **client_secret** (string) - Required - Your application's client secret. - **code** (string) - Required - The authorization code received from the redirect. - **redirect_uri** (string) - Required - The same redirect URI used in the initial authorization request. ### Request Example ```json { "grant_type": "authorization_code", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "code": "AUTHORIZATION_CODE_FROM_REDIRECT", "redirect_uri": "YOUR_REDIRECT_URI" } ``` ### Response #### Success Response (200 OK) - **access_token** (string) - The token used to authenticate API requests. - **token_type** (string) - The type of token, usually `Bearer`. - **expires_in** (integer) - The lifetime in seconds of the access token. - **refresh_token** (string) - A token to obtain a new access token without user re-authorization. - **scope** (string) - The scopes granted to the access token. #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 7200, "refresh_token": "REFRESH_TOKEN_FOR_NEW_ACCESS", "scope": "read:calls read:messages" } ``` ``` -------------------------------- ### Sample API JSON Response for User Availabilities Source: https://developer.aircall.io/advanced-tutorials/activity-tracker This is a sample JSON payload returned by the /v1/users/availabilities endpoint. It includes metadata about the response and a list of users, each with their unique ID and current availability status (e.g., 'available', 'offline', 'do_not_disturb'). ```JSON { "meta": { "count": 3, "total": 3, "current_page": 1, "per_page": 20, "next_page_link": null, "previous_page_link": null }, "users": [ { "id": 456, "availability": "available" }, { "id": 457, "availability": "offline" }, { "id": 458, "availability": "do_not_disturb" } ] } ``` -------------------------------- ### Aircall OAuth Flow - Authorization Endpoint Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint is where Aircall redirects the admin to authorize your application. It's typically used to display a settings page or instructions before forwarding the user to the authorization URL. ```APIDOC ## POST /oauth/authorize ### Description This endpoint is part of the Aircall OAuth flow. After an admin installs an app, Aircall redirects them to your `install_uri`. This endpoint should then redirect the admin to the Aircall OAuth authorization URL. ### Method POST ### Endpoint `https://dashboard.aircall.io/oauth/authorize` ### Parameters #### Query Parameters - **client_id** (string) - Required - Your application's client ID. - **redirect_uri** (string) - Required - The URI where Aircall will redirect the user after authorization. - **scope** (string) - Optional - The requested permissions for the application. ### Request Example ```json { "client_id": "YOUR_CLIENT_ID", "redirect_uri": "YOUR_REDIRECT_URI", "scope": "read:calls read:messages" } ``` ### Response #### Success Response (302 Found) - **Location** (string) - Redirects to the Aircall authorization page. #### Response Example (HTTP 302 Redirect to Aircall's authorization URL) ``` -------------------------------- ### POST /v1/webhooks Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint allows you to create a new webhook subscription in your Aircall account. Upon successful creation, Aircall returns a unique token that must be used to associate webhook events with your users. ```APIDOC ## POST /v1/webhooks ### Description Creates a new webhook subscription to receive real-time event notifications from Aircall. The response includes a unique token to identify the webhook. ### Method POST ### Endpoint https://api.aircall.io/v1/webhooks ### Parameters #### Query Parameters None #### Request Body - **custom_name** (string) - Required - A custom name for your webhook, typically your application's name. - **url** (string) - Required - The URL of your server endpoint where Aircall will send webhook events. ### Request Example ```json { "custom_name": "YOUR_APP_NAME", "url": "https://your.server.com/aircall/webhook" } ``` ### Response #### Success Response (201 Created) - **webhook** (object) - Contains details of the newly created webhook. - **id** (integer) - The unique identifier for the webhook. - **custom_name** (string) - The custom name provided during creation. - **url** (string) - The URL where events are sent. - **token** (string) - A unique token associated with the webhook, used for event identification. - **created_at** (string) - The timestamp when the webhook was created. #### Response Example ```json { "webhook": { "id": 12345, "custom_name": "YOUR_APP_NAME", "url": "https://your.server.com/aircall/webhook", "token": "YOUR_UNIQUE_WEBHOOK_TOKEN", "created_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### OAuth Controller Setup Source: https://developer.aircall.io/labs/weather Initializes the OAuth controller, providing a reference to a tutorial on how the Aircall OAuth flow works. It imports necessary modules like path and logger. ```javascript /** * OAuth Controller * * Read this tutorial for more information: * https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works/ */ const path = require('path'), Logger = require('./../modules/logger'), ``` -------------------------------- ### Make Unauthenticated API Request (JavaScript) Source: https://developer.aircall.io/tutorials/basic-authentication This example shows how to make an HTTPS GET request to the Aircall API's ping endpoint without authentication. It will result in an 'Unauthorized' error, demonstrating the need for authentication. ```javascript const https = require('https'); let options = { host: 'api.aircall.io', path: '/v1/ping', port: 443 }; // Sending the HTTP request https.get(options, (res) => { let body = ''; res.on('data', (data) => { body += data; }); res.on('end', () => { console.log(body); }); res.on('error', (e) => { console.log('Error: ', e.message); }); }); ``` -------------------------------- ### User Wrap-Up Time Start Event Payload (JSON) Source: https://developer.aircall.io/api-references The 'user.wut_start.v2' event is triggered when a user begins their wrap-up time (WUT) according to their settings. The payload contains event information, resource, timestamp, token, and user data. ```json { "event": "user.wut_start.v2", "resource": "user", "timestamp": 158554819, "token": "45XXYYZZa08", "data": { // the User v2 object } } ``` -------------------------------- ### Get User's Google Calendar Events Source: https://developer.aircall.io/tutorials/synchronize-agent-availability-with-google-calendar This section details how to retrieve a user's Google Calendar events using the Google Calendar API. It provides Ruby code examples for fetching calendar lists and events. ```APIDOC ## Get User's Google Calendar Events ### Description This endpoint retrieves a user's Google Calendar events. For demonstration, it fetches all events from the primary calendar. A more efficient approach for production would involve fetching events for a specific upcoming period and storing them. ### Method `GET` ### Endpoint `https://www.googleapis.com/calendar/v3/users/me/calendarList` (for calendar list) `https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events` (for events) ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for Google OAuth. ### Request Example ```ruby require 'httparty' def get_calendar_list url = 'https://www.googleapis.com/calendar/v3/users/me/calendarList' HTTParty.get( url, headers: { 'Authorization' => "Bearer #{@user.google_oauth_token}" } ) end def get_events calendar = get_calendar_list['items'].first return if calendar.nil? url = "https://www.googleapis.com/calendar/v3/calendars/#{calendar['id']}/events" HTTParty.get( url, headers: { 'Authorization' => "Bearer #{@user.google_oauth_token}" } ) end ``` ### Response #### Success Response (200) Returns a list of calendar events, each with `start` and `end` times. #### Response Example ```json { "id": "465qfgq7p5mcvdpm9kfsgn0i3f", "summary": "My Meeting", "status": "confirmed", "start": { "dateTime": "2018-03-21T14:00:00+01:00" }, "end": { "dateTime": "2018-03-21T14:15:00+01:00" } ... } ``` ``` -------------------------------- ### Retrieve User ID-to-Username Mappings from Internal Data Repository (Pseudocode) Source: https://developer.aircall.io/advanced-tutorials/activity-tracker This pseudocode demonstrates how to retrieve user ID-to-username mappings from an internal data repository. It initializes a data structure, queries the database, and populates the structure by iterating through the query results. This is essential for correlating user IDs with their corresponding usernames. ```pseudocode // Create data struct userdb = {}; // Retrieve user ID-to-username mappings from internal data repository db_response = database.query("SELECT ... FROM ... WHERE ..."); // Iterate over each row returned from query... db_response.foreach((row) => { // Key: User ID // Value: Username userdb[row[0]] = row[1]; }); ``` -------------------------------- ### Implement Aircall Redirect URI Endpoint (JavaScript) Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This endpoint is called by Aircall after the admin authorizes the application. It receives an OAuth code as a query parameter, which is then used to retrieve an access token. The endpoint redirects to a success URL upon completion. It requires HTTPS for secure communication. ```javascript /** * server.js */ ... /** * Endpoint requested by Aircall after Admin authorizes your app, * with the OAuth code needed to get the final `access_token` */ app.get('/aircall/oauth/callback', (req, res) => { const oauthCode = req.query.code; // will be implemented at next step! retrieveAccessToken(oauthCode); // At this point, the flow is over. // You can either display your own success screen or Aircall's one: const successUrl = 'https://dashboard.aircall.io/oauth/success'; res.redirect(successUrl); }); ``` -------------------------------- ### Setup & Object Relationships Source: https://developer.aircall.io/advanced-tutorials/activity-tracker Retrieve information about Aircall object IDs and their relationships. This data is relatively static and should be refreshed occasionally. ```APIDOC ## GET /v1/users ### Description Retrieves a list of all users in the Aircall account. ### Method GET ### Endpoint https://api.aircall.io/v1/users ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **users** (array) - An array of user objects. - **id** (integer) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "users": [ { "id": 123, "name": "John Doe", "email": "john.doe@example.com" } ] } ``` ``` ```APIDOC ## GET /v1/teams ### Description Retrieves a list of all teams in the Aircall account. ### Method GET ### Endpoint https://api.aircall.io/v1/teams ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **teams** (array) - An array of team objects. - **id** (integer) - The unique identifier for the team. - **name** (string) - The name of the team. #### Response Example ```json { "teams": [ { "id": 456, "name": "Sales Team" } ] } ``` ``` ```APIDOC ## GET /v1/numbers ### Description Retrieves a list of all phone numbers in the Aircall account. ### Method GET ### Endpoint https://api.aircall.io/v1/numbers ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **numbers** (array) - An array of number objects. - **id** (integer) - The unique identifier for the phone number. - **number** (string) - The phone number. - **name** (string) - The name assigned to the phone number. #### Response Example ```json { "numbers": [ { "id": 789, "number": "+1234567890", "name": "Support Line" } ] } ``` ``` -------------------------------- ### User Wrap-up Time Start Event (v1) Source: https://developer.aircall.io/api-references This event is triggered when a user begins their wrap-up time (WUT). It includes event details and the User v1 object. Special conditions apply if wrap-up time is zero and call tagging is mandatory. ```json { "event": "user.wut_start", "resource": "user", "timestamp": 158554819, "token": "45XXYYZZa08", "data": { // the User v1 object } } ``` -------------------------------- ### Store Aircall Access Token using Node.js Source: https://developer.aircall.io/tutorials/how-aircall-oauth-flow-works This Node.js snippet shows how to store the retrieved Aircall access token and associate it with the current user. It provides a placeholder using Mongoose syntax for database interaction, emphasizing that this function should be adapted to the specific database implementation of the user's application. ```javascript /** * server.js */ // Match the Public API accessToken to one of your user // Here you should have access to the user logged in with the current session. // Save the accessToken in your own database! const storeAccessToken = (accessToken) => { // In this example, we'll use mongoose' syntax. // Please adapt this function to your own database: curentUser.aircallAccessToken = accessToken; currentUser.save(); } ```