導入範例

如要從舊版 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 驗證
範圍 活動 https://www.googleapis.com/auth/googlehealth.activity_and_fitness
使用者 ID /oauth2/token 回應中傳回的 Fitbit 編碼 ID 從 users.getIdentity 端點傳回的使用者 ID

4. 保留檢查清單

  • 工作階段持續性:請勿清除使用者的舊 Fitbit Web API 工作階段,直到 Google Health API access_token 成功驗證並儲存至資料庫為止。
  • 自動撤銷:Google Health API 遷移完成後,請使用 POST 要求傳送至舊版 Fitbit 撤銷端點:https://api.fitbit.com/oauth2/revoke。這樣一來,使用者就不會在 Fitbit 設定中看到「重複」的應用程式權限。
  • 錯誤處理:如果 Fitbit 呼叫傳回 401 Unauthorized,請自動重新導向至 Google OAuth 流程,而非顯示錯誤訊息。