withings-node-oauth2

1.0.1 • Public • Published

withings-node-oauth2

An OAuth2 API client library for Withings

Getting started

Install the library from npm

npm install withings-node-oauth2

API

Constructor

new WithingsNodeOauth2({
    clientId: "YOUR-WITHINGS-CLIENT-ID",
    clientSecret: "YOUR-WITHINGS-CLIENT-SECRET",
    callbackURL: "YOUR-WITHINGS-CALLBACK-URL"
});

Make sure you replace the above values(clientId, clientSecret, and callbackURL) with your withings application details. If you don't have a withings developer account yet, go read Create your developer account and follow the instruction.

Methods

getAuthorizeURL

getAuthorizeURL(state: string, scope: string): string

This method takes two strings (state, and scope). state is a value you define. It will be bound to the returned auth URL as a url query which can be used to make sure that the the redirect back to your site or app was not spoofed. scope Is a comma-separated list of permission scopes you want to ask your user for. Click here to see the Index Data API section from withings to know which scope you should use.

getAccessToken

getAccessToken(code: string): Promise<Object>

`getAuthorizeURL will redirect to your callback URL with a code query attached to it. That is your authorization code which can be used to request an access token.

This method will require the authorization code and will return the following payload

{
    "status": 0,
    "body": {
        "userid": "user-id",
        "access_token": "access-token",
        "refresh_token": "refresh-token",
        "scope": "requested scopes",
        "expires_in": 10800,
        "token_type": "Bearer"
    }
}

You will mostly need the access_token to make further requests to withings server.

PS: Withings uses the status 0 to mean a successful response.

refreshAccessToken

refreshAccessToken(refreshToken: string): Promise<Object>

If user's access token has expired, this is the method you will need to get a new access_token and be able to make requests again. PS: This also returns a new refresh token so you will need to overwrite the current one.

It will return the following payload

{
    "status": 0,
    "body": {
        "userid": "user-id",
        "access_token": "new access-token",
        "refresh_token": "new refresh-token",
        "scope": "requested scopes",
        "expires_in": 10800,
        "token_type": "Bearer"
    }
}

getUserDevices

getUserDevices(accessToken: string): Promise<Object>

Returns the list of user linked devices.

Example response

{
  "status": 0,
  "body": {
    "devices": [
      {
        "type": "Scale",
        "model": "Body Cardio",
        "model_id": 6,
        "battery": "medium",
        "deviceid": "892359876fd8805ac45bab078c4828692f0276b1",
        "hash_deviceid": "892359876fd8805ac45bab078c4828692f0276b1",
        "timezone": "Europe/Paris",
        "last_session_date": 1594159644
      }
    ]
  }
}

getUserGoals

getUserGoals(accessToken: string): Promise<Object>

Returns the goals of a user

Example response

{
  "status": 0,
  "body": {
    "goals": {
      "steps": 10000,
      "sleep": 28800,
      "weight": {
        "value": 70500,
        "unit": -3
      }
    }
  }
}

getUserMeasures

getUserMeasures(accessToken: string, options?: Object): Promise<Object>

Returns measures at a specific date collected by a user. options specifies additional data to be included in the response. Click here to see the list of available options.

getUserActivities

getUserActivities(accessToken: string, options?: Object): Promise<Object>

Provides user activity data of a user. To see the list of available options, click here.

getUserDailyActivities

getUserDailyActivities(accessToken: string, options?: Object): Promise<Object>

Returns user daily activity data. Here is a list of all possible options.

getUserWorkouts

getUserWorkouts(accessToken: string, options?: Object): Promise<Object>

Returns workout summaries. See possible options.

getHeartSummary

getHeartSummary(accessToken: string, options?: Object): Promise<Object>

Returns a list of ECG records and Afib classification for a given period of time. All options can be found here.

getSleepSummary

getSleepSummary(accessToken: string, options?: Object): Promise<Object>

Returns sleep activity summaries. Here is the list of available options.

Examples

Vanilla NodeJS

const http = require('http');
const url = require('url');
const WithingsNodeOauth2 = require('withings-node-oauth2');

const client = new WithingsNodeOauth2({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: process.env.CALLBACK_URL
});

const PORT = process.env.PORT || 5000;

const server = http.createServer((req, res) => {
    if (req.url === '/authorize' && req.method === 'GET') {
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.write((client.getAuthorizeURL("", "info, activity, metrics"));
        res.end();
    } else if (req.url.startsWith('/callback') && req.method === 'GET') {
        const { code } = url.parse(req.url, true).query;
        client.getAccessToken(code)
        .then((result) => {
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.write(JSON.stringify(result));
            res.end();
        }).catch((error) => {
            console.error(error);
            res.end();
        });
    } else if (req.url === '/sleep' && req.method === 'GET') {
        client.getSleepSummary('access-token')
            .then((result) => {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.write(JSON.stringify(result));
                res.end();
            }).catch((error) => {
                console.error(error);
                res.end();
            });
    } else {
        res.end('Route not found');
    }
});

server.listen(PORT);

ExpressJS

const express = require('express');
const WithingsNodeOauth2 = require('withings-node-oauth2');
const session = require('express-session');
require('dotenv').config();

const app = express();

app.use(express.json());
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true
}));

const PORT = process.env.PORT || 3000;

const client = new WithingsNodeOauth2({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: process.env.CALLBACK_URL
});

app.get('/authorize', (req, res) => {
    res.redirect(client.getAuthorizeURL("", "info, activity, metrics"));
});

app.get('/callback', (req, res) => {
    client.getAccessToken(req.query.code)
        .then(result => {
            req.session.withings = {
                accessToken: result.body.access_token,
                refreshToken: result.body.refresh_token,
                userId: result.body.userid
            };
            res.status(200).json(result);
        }).catch(error => {
            res.status(error.status).json(error)
        });
});

app.get('/activity', (req, res) => {
    client.getUserActivities(req.session.withings.accessToken)
        .then(result => {
            res.status(200).json(result);
        }).catch(error => {
            res.status(error.status).json(error);
        });
});

app.listen(PORT);

Package Sidebar

Install

npm i withings-node-oauth2

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

22.1 kB

Total Files

7

Last publish

Collaborators

  • desirekaleba