实现示例

如需从旧版 Fitbit Web API 迁移到 Google Health API,您需要从通用 OAuth2 库迁移到 Google Auth 库。以下是架构建议和用 JavaScript 编写的伪代码实现,用于处理这种“双库”状态。

1. “中间件开关”

由于您无法一次性迁移所有用户,因此您的后端需要根据存储在数据库中的用户当前 apiVersion 来确定要使用的库。

实现

const { OAuth2Client } = require('google-auth-library');
const FitbitV1Strategy = require('fitbit-oauth2-library').Strategy;

// 1. Initialize the Google Health API Client
const GHAClient = new OAuth2Client(
  process.env.GOOGLE_CLIENT_ID,
  process.env.GOOGLE_CLIENT_SECRET,
  process.env.REDIRECT_URI
);

// 2. Create a Unified Fetcher
async function fetchSteps(user) {
  if (user.apiVersion === 4) {
    // ---- GOOGLE OAUTH LIBRARY LOGIC ----
    GHAClient.setCredentials({ refresh_token: user.refreshToken });
    const url = 'GET https://health.googleapis.com/v4/users/me/dataTypes/steps/dataPoints';
    const res = await GHAClient.request({ url });
    return res.data;
  } else {
    // ---- FITBIT WEB API LEGACY LOGIC ----
    // Use your existing Fitbit open-source library logic here
    return callLegacyV1Api(user.accessToken);
  }
}

2. 迁移用户体验流程

为了最大限度地提高用户留存率,请使用“中断并升级” 模式。这样可以确保用户在与应用互动之前不会被迫重新登录。

重定向逻辑

当 Fitbit Web API 用户点击特定功能时,触发迁移:

app.get('/dashboard', async (req, res) => {
  const user = await db.users.find(req.user.id);

  if (user.apiVersion === 1) {
    // Render a "soft" migration page explaining the Google transition
    return res.render('migrate-to-google', {
      title: "Keep your data syncing",
      message: "Fitbit is moving to Google accounts. Re-connect now to stay updated."
    });
  }

  const data = await fetchSteps(user);
  res.render('dashboard', { data });
});

3. 关键技术转换

编写 JavaScript 迁移脚本时,请注意以下差异:

功能 Fitbit Web API(旧版) Google Health API (Google-Identity)
令牌端点 https://api.fitbit.com/oauth2/token https://oauth2.googleapis.com/token
身份验证库 标准开源 Google Auth
范围 活动 https://www.googleapis.com/auth/googlehealth.activity_and_fitness
用户 ID 在 /oauth2/token 响应中返回的 Fitbit 编码 ID 从 users.getIdentity 端点返回的用户 ID

4. 留存率核对清单

  • 会话持久性:在成功验证 Google Health API access_token 并将其保存到数据库之前,请勿清除用户的旧 Fitbit Web API 会话 。
  • 自动撤消:Google Health API 迁移完成后,请使用 POST 请求向旧版 Fitbit 撤消端点发送请求: https://api.fitbit.com/oauth2/revoke。这样可以确保用户不会在其 Fitbit 设置中看到“重复”的应用权限。
  • 错误处理:如果 Fitbit 调用返回 401 Unauthorized, 请自动重定向到 Google OAuth 流程,而不是显示 错误消息。