65.9K
CodeProject 正在变化。 阅读更多。
Home

FitJS 简介,适用于 Fitbit 的 AJAX 库

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.91/5 (3投票s)

2013年11月4日

CPOL

8分钟阅读

viewsIcon

16125

FitJS 简介,一款用于开发 Fitbit 应用的 AJAX 库

介绍  

Google Code: https://code.google.com/p/fitjs/ 

Fitbit 是一款很棒的设备,可以跟踪日常活动、睡眠等。然而,该网站本身除了显示数据和一些基本图表外,为用户提供的应用程序非常有限。像您这样的第三方开发者可以通过提供与游戏化或激励相关的应用程序来抓住这个机会,为这个新市场开发出色的应用程序。  

 Fitbit 提供 RESTful API 来访问用户数据。其优点是您可以开发适用于各种平台的应用程序,而无需下载任何内容。缺点是您需要编写大量繁琐的代码来调用 API。  

 FitJS 是一个围绕 Fitbit 的 RESTful API 构建的 AJAX 库。您可以直接调用 Javascript 函数来请求令牌、访问令牌,甚至创建弹出窗口来重定向用户授权您的访问。

 FitJS 在 Apache License 2.0 下完全开源。您可以在以下网址帮助开发该库:

 https://code.google.com/p/fitjs/ 

 1.0 版本目前仅支持 OAuth 授权功能。 但在下一次更新中,将支持资源访问。非常感谢您对该库的贡献。  

使用代码 

先决条件:

使用该库 

下载并放置文件 

1. 前往 https://code.google.com/p/fitjs/ 并从 Google Drive 下载 ZIP 文件

2. 将此文件解压到您的网站文件夹

3. 在您的网页中包含 fitjs.js     

 <script src="fitjs/fitjs.js"></script>  

4. 确保您的服务器运行 PHP。如果不是,您可能需要进行以下更改

  • 打开 "fitjs.js"
  • 找到 FitJS_OAuth() 方法。更改以下代码 
    this.url={
       ........
        verifier:"fitjs/oauthverifier.php",
        signature:'fitjs/oauthsignature.php',
        proxy:"fitjs/proxy.php"        
    }; 

以反映您选择的 Web 语言,例如 ASP、JSP 等。

5. 用您实现相同功能的自己的文件替换 FitJS 文件夹中的文件。

"oauthverifier.php" 返回 Fitbit 在用户授权访问后返回的验证器。请注意,Fitbit 将调用您提供的一个 URL,一旦用户授权了您的访问。该 URL 应将此调用返回的验证器和令牌写入您的数据库。"oauthverifier.php" 仅从您的数据库中提取这两个变量,并以以下格式打印它们:

verifier=XXX&token=XXX  

"oauthsignature.php" 使用 HMAC-SHA1 方法,用您的 consumer secret 对基本字符串进行签名。如果您希望使用其他哈希方法,请确保您的 FitJS 对象构造函数能够反映这一点。  

"proxy.php" 是 XMLHttpRequest 的代理,用于避免大多数浏览器中的跨域调用限制。Javascript 函数将首先向此文件发送特定请求,然后此文件调用 Fitbit API 并返回响应。该文件使用 POST 方法接收 1) Fitbit 请求所需的标头 2) 请求的正文 3) 请求到 Fitbit 的方法,例如 POST 或 GET。您可以阅读源代码以更好地理解其功能。  

使用 JS 方法: 

0. FitJS OAuth 基础知识 

下图演示了 FitJS OAuth 流程。 

1. 初始化 FitJS 

foauth=new FitJS_OAuth("http://example.com/oauthverifier.php",  //callback URL for OAuth verifier
                                "999999999999999999999999", //consumer key provided by Fitbit
                                "HMAC-SHA1" // hash method. FitJS 1.0 only supports HMAC-SHA1.
                                );  

2. 请求令牌    

var baseString=foauth.oauthBaseString("request_token"); // create base string of the signature
    var signature=foauth.oauthSignatureString(baseString); // generate signature string with HMAC-SHA1
    foauth.requestToken(signature, true, readyStateChange);   // request token  
    // second parameter means whether it is an asynchronous call
    // third parameter is a call back function for handling state changes on the XMLHttpRequest 

请注意,"readyStategChange" 是一个回调函数,它带有一个标准的 XMLHttpRequest 参数。要检查您是否收到了有效响应,您可能需要执行以下操作:

function readyStateChange(xmlhttp)
{
    if (xmlhttp.readyState===4 && xmlhttp.status===200)
    {
        //receive temporary token from Fitbit API successfully
    }
    else
    {
        // error handling
    }
}  

3. 将用户重定向到 Fitbit.com 进行授权 

在从 Fitbit.com 收到有效令牌后,您应该将用户重定向到 Fitbit.com 以便他们授权您访问数据。在下面的示例中,仅在收到令牌时才发出重定向。因此,该代码位于 "readyStateChange" 函数中(在上一步)。 

 function readyStategChange(xmlhttp)
{
    if (xmlhttp.readyState===4 && xmlhttp.status===200)
    {
        foauth.authorize(true, "en_US", false, 800, 500);
       // first parameter means whether you want the redirection to be done in the main window or a popup. If you choose to use Popup, you may want to ensure the browser has not blocked pop-up first
      // second parameter is the locale of the window. For a list of locales Fitbit support, you can check out https://wiki.fitbit.com/display/API/API+Localization
      // third parameter means whether the page is for a mobile device
      // fourth and fifth parameters are the width and height of the pop-up respectively if you choose to redirect the user via a pop-up
        foauth.checkOAuthVerifier(2000, 10000, onTimeOut, onFinished, onFailed);
       // First parameter means how frequently (in milliseconds) should the webpage talk to the server to figure out whether users has authorized the access. Please implement the code in "oauthverifier.php" located in the "FitJS" folder to look up your database and return with format specified in the php file
       // Second parameter means timeout in milliseconds (if the server does not respond within this threshold, the connection will be shut down. 
       // the last three parameters are the functions that handles different events
    }
} 

在上面的示例中,您可以看到一旦生成弹出窗口,就会启动常量检查。一旦检测到 "oauthverifier" 在用户授权访问后已经返回了验证器,检查就会停止。

onTimeOut、onFinished 和 onFailed 都是回调函数,它们接受一个标准的 XMLHttpRequest 参数。在第 5 步中,您可以看到 onFinished 是如何实现的。 

4. 访问令牌 

 function onFinished()
{
    var basestring=foauth.oauthBaseString("access_token");
    // generate the base string for access token request 
    var signature=foauth.oauthSignatureString(basestring);  
    // generate signatur string for the access token request 
    foauth.accessToken(signature, true, onAccessTokenStateChange);
    // second parameter means whether it is an asynchronous call
    // third parameter is a call back function for handling state changes on the XMLHttpRequest
}


function onAccessTokenStateChange(xmlhttp)
{
        if (xmlhttp.readyState===4 && xmlhttp.status===200)
    {
        alert("token:"+foauth.oauth_token+" token secret:"+foauth.oauth_token_secret+" user id: "+foauth.oauth_token_secret);    
    }
} 

API 参考 

有关最新的 API 参考,您可能需要阅读:https://code.google.com/p/fitjs/wiki/API_Reference 

开始之前,您可能需要查看 http://tools.ietf.org/html/draft-hammer-oauth-10 以了解 OAuth 1.0 协议,从而了解 Fitbit 如何授权您的应用程序访问用户数据。

成员函数

构造函数

FitJS_OAuth(callbackUrl, consumerKey, hashMethod)

参数

返回: 已初始化的 Fitbit 实例副本
callbackUrlFitbit API 在用户授权访问其数据后回调的 URL。该 URL 应与记录的匹配,除非 Fitbit.com 上没有剩余记录。此 URL 应将 Fitbit 返回的令牌和验证器写入数据库。
consumerKeyFitbit 提供的 consumer key 字符串
hashMethodFitJS 目前 仅接受 HMAC-SHA1。但未来将支持 HMAC-SHA1、RSA-SHA1、PLAINTEXT。

示例 

 foauth=new FitJS_OAuth("http://example.com/oauthcomplete.php",  //callback url
                                "7c799999999999e8a149499999", //consumer key
                                "HMAC-SHA1" //hash method
                                ); 

签名请求

OAuth 请求通常涉及多个标头。但复杂的部分是 1) 组装请求基本字符串 2) 对其进行签名。3) 组装请求标头。

2) 需要您的 secret。出于安全原因,强烈建议不要在 Javascript 中存储您的 OAuth secret。为此,您应该将 Fitbit OAuth secret 存储在 "oauthsignature.php" 中。

有关签名 OAuth 请求的更多信息,请参阅

http://tools.ietf.org/html/draft-hammer-oauth-10#section-3.4

生成基本字符串

oauthBaseString(stage);

此函数将根据请求类型生成用于签名的基本字符串。

参数

stage这是一个枚举变量,有两个可能的值:"request_token" 和 "access_token"。

返回: 该函数将根据提供的请求类型返回一个用于生成签名字符串的基本字符串。

示例

var baseString=foauth.oauthBaseString("request_token");
var basestring=foauth.oauthBaseString("access_token"); 

oauthSignatureString (baseString)

此函数使用 HMAC-SHA1 对基本字符串进行签名。目前,HMAC-SHA1 是 FitJS 1.0 版本中唯一允许的方法。

参数

baseString用于生成签名的 OAuth 请求基本字符串。此字符串由 oauthBaseString() 函数生成。

返回: 使用 HMAC-SHA1 生成的签名字符串

示例

var signature=foauth.oauthSignatureString(baseString);  

请求临时令牌

requestToken (signature, async, onreadyStateChange)

参数

signature基于此请求基本字符串的签名字符串
async此请求是否为异步
onreadyStateChange ready state change 事件的回调函数。仅当请求是异步的时,才会调用此函数。

返回: 如果请求是异步的,此函数不返回任何内容。如果函数是同步的,则返回一个标准的 XMLHttpRequest

示例 

 foauth.requestToken(signature, true, readyStategChange);  

授权访问

通过 OAuth 授权过程,用户必须授予您的应用程序访问其在 Fitbit 服务器上的数据的权限。因此,您的应用程序需要重定向用户或使用弹出窗口,允许用户访问 fitbit.com/authorize。

authorize(usePopUp, locale, mobile, popupWidth, popupHeight)

此函数允许弹出窗口和重定向,尽管强烈建议使用弹出窗口以保留 Javascript 中的数据。

参数

usePopUp访问 fitbit.com 是通过弹出窗口还是重定向
locale您的弹出窗口的区域设置
mobile 用户访问 fitbit.com 是在移动设备上
popupWidth您的弹出窗口的宽度
popupHeight 您的弹出窗口的高度

返回: 无

示例

 foauth.authorize(true, "en_US", false, 800, 500); 

checkOAuthVerifier(interval, timeout, onTimedOut, onFinished, onFailed)

此函数向 "oauthverifier.php" 发送请求,以检查您的网站是否已从 fitbit.com 获取 OAuth 验证器(这仅在用户授权访问后发生)。因此,先决条件是实现一个允许 fitbit.com 发送验证器和令牌的回调 URL,以及 "oauthverifier.php",它从存储验证器和令牌的数据库中提取数据。

注意,"oauthverifier.php" 必须以以下格式返回验证器和令牌:

"verifier=XXX&token=XXX"

参数

interval以毫秒为单位的检查 "oauthverifier.php" 的频率
timeout单个请求超时阈值(以毫秒为单位)
onTimedOut超时时的回调函数(返回 XMLHttpRequest)
onFinished完成时的回调函数(返回 XMLHttpRequest)
onFailed发生错误时的回调函数(返回 XMLHttpRequest)

返回

示例 

 foauth.checkOAuthVerifier(2000, 10000, onTimeOut, onFinished, onFailed); 

stopCheckingOAuthVerifier()

"checkOAuthVerifier()" 会在从 "oauthverifier" 获取验证器和令牌后自动停止发送请求。但是,如果您想在某些情况下手动停止检查,可以调用此函数。

参数

返回: 无

示例

  stopCheckingOAuthVerifier(); 

访问令牌

accessToken(signature, async, onreadyStateChange)

OAuth 过程的最后一步是从 Fitbit 请求并接收令牌凭据。返回的内容包括令牌、令牌 secret 和用户的 user-id。有了这些凭据,您的应用程序就可以访问用户的数据了。

参数

signature由 "oauthSignatureString()" 生成的签名字符串
async此请求是否为异步
onreadyStateChange 如果请求是异步的,用于接收 read state change 事件的回调函数。参数将是一个标准的 XMLHttpRequest。

返回: 如果请求是同步的,该函数返回一个标准的 XMLHttpRequest;如果不是,则不返回任何内容。

示例

foauth.accessToken(signature, true, onAccessTokenFinished);

function onAccessTokenFinished(xmlhttp)
{
        if (xmlhttp.readyState===4 && xmlhttp.status===200)
    {
        alert("token:"+foauth.oauth_token+" token secret:"+foauth.oauth_token_secret+" user id: "+foauth.encoded_user_id);    
    }
} 

成员变量 

    url={
        request_token:"http://api.fitbit.com/oauth/request_token",
        access_token:"http://api.fitbit.com/oauth/access_token",        
        authorize:"https://www.fitbit.com/oauth/authenticate",
        verifier:"fitjs/oauthverifier.php",
        signature:'fitjs/oauthsignature.php',
        proxy:"fitjs/proxy.php"        
    } 

FitJS 在内部使用的 URL,用于完成 OAuth 过程的不同部分。

 callbackUrl 

构造 FitJS_OAuth 对象时提供的回调 URL。

 consumerKey 

构造 FitJS_OAuth 对象时提供的 consumer key。

 hashMethod 

构造 FitJS_OAuth 对象时提供的哈希方法。目前支持 HMAC-SHA1。

verifier 

当用户授权访问其数据并重定向 Fitbit.com 到存储了验证器的数据库的回调 URL 后,从 "oauthverifier.php" 收到的验证器。 

Token 

从 Fitbit.com 收到的临时令牌。 

 callbackConfirmed 

在请求令牌时,回调 URL 是否已由 Fitbit.com 确认。

 request_token_timestamp 

请求令牌时的带时间戳字符串。每次调用 base string 函数创建用于请求令牌的基本字符串时,此字符串都会更改。

  request_token_nonce 

请求令牌时的随机字符串。每次调用 base string 函数创建用于请求令牌的基本字符串时,此字符串都会更改。

 access_token_timestamp 

访问令牌时的带时间戳字符串。每次调用 base string 函数创建用于访问令牌的基本字符串时,此字符串都会更改。

 access_token_nonce 

访问令牌时的随机字符串。每次调用 base string 函数创建用于访问令牌的基本字符串时,此字符串都会更改。

 oauth_token_secret 

成功调用 accessToken() 后从 Fitbit 收到的 OAuth 令牌 secret。

 encoded_user_id 

成功调用 accessToken() 后从 Fitbit 收到的用户 ID。 

© . All rights reserved.