定制 jmitchell38488/oauth2-fitbit 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jmitchell38488/oauth2-fitbit

Composer 安装命令:

composer require jmitchell38488/oauth2-fitbit

包简介

OAuth 2.0 wrapper for the FitBit API using thephpleague OAuth 2.0 client

README 文档

README

Source Code Latest Version Software License Total Downloads

This package makes it simple to integrate your application with the FitBit OAuth 2.0 service provider.

Installation

composer require jmitchell38488/oauth2-fitbit

Usage

The FitBit provides two different methods for authenticating with the OAuth 2.0 service, an authorization grant flow and an implicit grant flow. Both require different configuration when instantiating the provider and the implicit grant flow will require once less step.

FitBit also uses a different Authorization header than is provided by the parent library. When a user authenticates with the FitBit 2.0 API, they need to set Authorization: Basic to generate the access token, and provide the Authorization header with each subsequent request, however using Bearer instead of Basic.

Included in the package are three concrete provider classes and an abstract provider class. The abstract provider class provides shared functionality for the Authorization and Implicit implementations. The FitBit class extends the Authorization class, so you can use that instead of the Authorization class if you prefer. It is there for clarity when making authenticated requests. In any case, if you are supporting either Implicit or Authorization grant flows, you will need to keep track of which one you've used to authenticate a session, since one will timeout and you can refresh it, whereas the other will require a user to re-authorize once it has timed out.

Authorization Grant Flow

Authenticate session

session_start();
use Jmitchell38488\OAuth2\Client\Provider\FitBitAuthorization;
require_once __DIR__ . '/vendor/autoload.php';

$provider = new FitBitAuthorization([
    'clientId'      => $my_client_id_from_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

// 1st step: Has the user authorised yet?
if (!isset($_SESSION['oauth2state'])) {
    $authorizationUrl = $provider->getAuthorizationUrl([
        'prompt' => FitBitAuthorization::PROMPT_CONSENT,
        'response_type' => FitBitAuthorization::RESPONSETYPE_CODE,
        'scope' => $provider->getAllScope(),
    ]);
    
    // Set the session state to validate in the callback
    $_SESSION['oauth2state'] = $provider->getState();
    
    header('Location: ' . $authorizationUrl);
    exit;
    
// 2nd step: User has authorised, now lets get the refresh & access tokens
} else if (isset($_GET['state']) && $_GET['state'] == $_SESSION['oauth2state'] && isset($_GET['code']) && !isset($_SESSION['fitbit']['oauth'])) {
    try {
        $token = base64_encode(sprintf('%s:%s', $my_client_id_from_fitbit, $my_client_secret_from_fitbit));
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code'  => $_GET['code'],
            'access_token' => $_GET['code'],
            'token' => $token,
        ]);
        
        unset($_SESSION['oauth2state']);
        $_SESSION['fitbit']['oauth2'] = array(
            'accessToken' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refreshToken' => $accessToken->getRefreshToken(),
        );
    } catch (Exception $ex) {
        print $ex->getMessage();
    }

// 3rd step: Authorised, have tokens, but session needs to be refreshed
} else if (time() > $_SESSION['fitbit']['oauth2']['expires']) {
    try {
        $token = base64_encode(sprintf('%s:%s', $my_client_id_from_fitbit, $my_client_secret_from_fitbit));
        $accessToken = $provider->getAccessToken('refresh_token', [
            'grant_type'    => FitBitAuthorization::GRANTTYPE_REFRESH,
            'access_token'  => $_SESSION['fitbit']['oauth2']['accessToken'],
            'refresh_token'  => $_SESSION['fitbit']['oauth2']['refreshToken'],
            'token'         => $token,
        ]);

        unset($_SESSION['oauth2state']);
        $_SESSION['fitbit']['oauth2'] = array(
            'accessToken' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refreshToken' => $accessToken->getRefreshToken(),
        );
    } catch (Exception $ex) {
        print $ex->getMessage();
    }
}

Implicit Grant Flow

Authenticate session

session_start();
use Jmitchell38488\OAuth2\Client\Provider\FitBitImplicit;
require_once __DIR__ . '/vendor/autoload.php';

$provider = new FitBitImplicit([
    'clientId'      => $my_client_id_from_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

// 1st step: Has the user authorised yet? Or do we need to refresh?
if (!isset($_SESSION['oauth2state'])) {
    $authorizationUrl = $provider->getAuthorizationUrl([
        'prompt' => FitBitImplicit::PROMPT_CONSENT,
        'response_type' => FitBitImplicit::RESPONSETYPE_TOKEN,
        'scope' => $provider->getAllScope(),
        'expires_in' => FitBitImplicit::EXPIRES_IN_DAY // This can be set to 1, 7 or 30 days
    ]);
    
    // Set the session state to validate in the callback
    $_SESSION['oauth2state'] = $provider->getState();
    
    header('Location: ' . $authorizationUrl);
    exit;
    
// 2nd step: User has authorised, now lets get the refresh & access tokens
// The return URL uses fragments, so you will need to implement front-end logic to redirect the 
// user back to the server with the relevant information, since the URL will look like:
// my_callback_uri#scope=nutrition+weight+location+social+heartrate+settings+sleep+activity+profile&state=abcdef1234567890&user_id=ABC123&token_type=Bearer&expires_in=86400&access_token=abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890
} else if (isset($_GET['state']) && $_GET['state'] == $_SESSION['oauth2state'] && isset($_GET['access_token']) && !isset($_SESSION['fitbit']['oauth'])) {
    unset($_SESSION['oauth2state']);
    $_SESSION['fitbit']['oauth2'] = array(
        'accessToken' => $_GET['access_token'],
        'expires' => $_GET['expires_in'],
        'refreshToken' => null,
    );
} 

Making requests

The API endpoints can be found in either the official API docs or the API explorer.

It's important to use the FitBit class intead of the grant flow classes, because FitBit API requires that you use the Bearer token in the Authorization header, rather than the Basic token. If you don't use the FitBit class, the API will return a 401 unauthorized error.

To make a request

$endpoint = $provider->getBaseApiUrl() . "user/-/profile." . FitBit::FORMAT_JSON;
$provider = new FitBit([
    'clientId'      => $my_client_id_from_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

$request = $provider->getAuthenticatedRequest(
    FitBit::METHOD_GET,
    $endpoint,
    $_SESSION['fitbit']['oauth2']['accessToken']
);

$response = $provider->getResponse($request);

jmitchell38488/oauth2-fitbit 适用场景与选型建议

jmitchell38488/oauth2-fitbit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 786 次下载、GitHub Stars 达 5, 最近一次更新时间为 2015 年 11 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「oauth」 「oauth2」 「fitbit」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jmitchell38488/oauth2-fitbit 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jmitchell38488/oauth2-fitbit 我们能提供哪些服务?
定制开发 / 二次开发

基于 jmitchell38488/oauth2-fitbit 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 786
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-11-12