You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native接入Fitbit API重定向后如何获取localhost的access token?

你当前使用http://localhost作为重定向地址无法回传参数到应用的原因是,该地址指向浏览器本地环境,不会触发应用唤起逻辑,需要改用React Native支持的深度链接(Deep Link)作为重定向方案。

第一步:配置应用深度链接

安卓端配置

打开安卓项目的android/app/src/main/AndroidManifest.xml,找到主Activity的声明节点,添加如下intent-filter配置,用来监听自定义的重定向地址:

<activity
  ... <!-- 原有配置保留 -->
>
  <!-- 原有intent-filter保留 -->
  <intent-filter>
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <!-- 自定义你的应用专属schema,路径可自定义 -->
      <data android:scheme="myfitbitapp" android:host="oauth_callback" />
  </intent-filter>
</activity>
第二步:修改OAuth相关配置
  • 登录Fitbit开发者后台,在你的应用配置页的重定向地址列表中,添加你刚才定义的深度链接地址:myfitbitapp://oauth_callback
  • 修改你代码中的重定向地址参数:
function OAuth(client_id, cb) {
    const oauthurl = `https://www.fitbit.com/oauth2/authorize?${qs.stringify({
        client_id,
        response_type: "token",
        scope: "heartrate activity activity profile sleep",
        redirect_uri: "myfitbitapp://oauth_callback", // 替换为自定义的深度链接
        expires_in: "31536000",
    })}`;
    Linking.openURL(oauthurl).catch((err) =>
     console.error("打开授权页失败", err)
    );
}
第三步:监听重定向回应用的事件,解析access token

在调用OAuth函数的页面,添加Linking的url事件监听,拿到重定向回来的完整地址后解析hash段的参数:

import { useEffect } from 'react';
import { Linking } from 'react-native';
import qs from 'qs';

// 在页面组件内添加监听
useEffect(() => {
  // 处理应用在后台被唤起的情况
  const handleUrl = async (event) => {
    const fullUrl = event.url;
    // 判断是Fitbit授权回调的地址
    if (fullUrl.startsWith('myfitbitapp://oauth_callback')) {
      // 隐式流的参数在#后面,先拆分出hash部分
      const hashPart = fullUrl.split('#')[1];
      if (hashPart) {
        // 解析hash里的参数
        const params = qs.parse(hashPart);
        const accessToken = params.access_token;
        const userId = params.user_id;
        // 拿到token后可直接调用Fitbit接口,也可存储到本地持久化使用
        console.log('获取到access token:', accessToken);
      }
    }
  };

  // 添加监听
  const linkingListener = Linking.addEventListener('url', handleUrl);

  // 处理应用完全关闭时,通过深度链接打开的情况
  Linking.getInitialURL().then(url => {
    if (url) {
      handleUrl({ url });
    }
  });

  // 页面卸载时移除监听,避免内存泄漏
  return () => {
    linkingListener.remove();
  };
}, []);
注意事项
  • 如果应用目标SDK版本是安卓12及以上,Fitbit后台配置的重定向地址必须和代码内的地址完全一致,不能携带额外参数,否则会重定向失败
  • 隐式流返回的token存在有效期,过期后需要引导用户重新授权获取新token

内容的提问来源于stack exchange,提问作者Abdul Abbou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:15:03