react-native - 如何使用 Expo 获取 FB Access Token

标签 react-native facebook-graph-api access-token expo

我正在构建需要在许多地方发出 Facebook Graph API 请求的应用程序。但我不知道如何检索访问 token ,然后发出 Graph API 请求。

我正在使用 Expo、React Native 和 Firebase。我想在不安装 Xcode 和/或 Android Studio 的情况下执行此操作。

登录正常。我的代码如下:

async loginWithFacebook() {
try {
  const {
    type,
    token,
    expires,
    permissions,
    declinedPermissions,
  } = await Expo.Facebook.logInWithReadPermissionsAsync('<APP_ID', {
    permissions: ['email', 'public_profile'],
  });
  if (type === 'success') {
    const credential = f.auth.FacebookAuthProvider.credential(token)
    f.auth().signInAndRetrieveDataWithCredential(credential).catch((error) => {
      console.log(error)
    })
    var that = this;
    const response = await fetch(`https://graph.facebook.com/me/?fields=id,name&access_token=${token}`);
    const userInfo = await response.json();
    this.setState({userInfo});
    this.setState({
    dataSource: userInfo.data,
    isLoading: false,
    });
  } else {
    // type === 'cancel'
  }
} catch ({ message }) {
  alert(`Facebook Login Error: ${message}`);
}
}

有人可以帮助我并给我一些提示,告诉我如何在我的应用程序中的任何地方使用访问 token 吗? 提前谢谢你

最佳答案

获取token并将其保存到AsyncStorage

那么你写的代码基本上是正确的。您已成功获得访问 token 。当您发出 Expo.Facebook.logInWithReadPermissionsAsync 请求时,它会返回给您。一旦你拥有它,你就可以将它存储在 Redux 或 AsyncStorage 中以备日后使用。

logIn = async () => {
  let appID = '123456789012345' // <- you'll need to add your own appID here

  try {
    const {
      type,
      token, // <- this is your access token
      expires,
      permissions,
      declinedPermissions,
    } = await Expo.Facebook.logInWithReadPermissionsAsync(appID, { permissions: ['public_profile', 'email'], });

    if (type === 'success') {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(`https://graph.facebook.com/me/?fields=id,name&access_token=${token}`); //<- use the token you got in your request
      const userInfo = await response.json();
      alert(userInfo.name);

      // you could now save the token in AsyncStorage, Redux or leave it in state
      await AsyncStorage.setItem('token', token); // <- save the token in AsyncStorage for later use
    } else {
      // type === 'cancel'
    }

  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

app.json

还记得将以下内容添加到您的 app.json 中,显然用您自己的值替换这些值。你可以通过在 Facebook 上注册你的应用程序来获得这些,你可以在这里看到更多相关信息 https://docs.expo.io/versions/latest/sdk/facebook/#registering-your-app-with-facebook

{ 
  "expo": {
    "facebookScheme": "fb123456789012345",
    "facebookAppId": "123456789012345",  // <- this is the same appID that you require above when making your initial request. 
    "facebookDisplayName": "you_re_facebook_app_name",
    ...
    }
}

AsyncStorage获取token

然后如果你想在以后发出另一个请求,你可以有一个类似于这个的函数,你从 AsyncStorage 中获取 token 然后用它来提出您的要求。

makeGraphRequest = async () => {
  try {
    let token = await AsyncStorage.getItem('token'); // <- get the token from AsyncStorage
    const response = await fetch(`https://graph.facebook.com/me/?fields=id,name&access_token=${token}`); // <- use the token for making the graphQL request
    const userInfo = await response.json();
    alert(userInfo.name)
  } catch (err) {
    alert(err.message)
  }
}

小吃

我会做点心来向您展示这个工作原理,但是,点心不允许编辑 app.json 文件(据我所知)。所以这里有一些你可以替换你的 App.js 的东西,然后如果你将你的 appIDs 等添加到 app.json 它应该可以工作。

import React from 'react';
import { AsyncStorage, Text, View, StyleSheet, SafeAreaView, Button } from 'react-native';


export default class App extends React.Component {

  logIn = async () => {
    let appID = '123456789012345' // <- you'll need to add your own appID here
    try {
      const {
        type,
        token, // <- this is your access token
        expires,
        permissions,
        declinedPermissions,
      } = await Expo.Facebook.logInWithReadPermissionsAsync(appID, {
        permissions: ['public_profile', 'email'],
      });
      if (type === 'success') {
        // Get the user's name using Facebook's Graph API
        const response = await fetch(`https://graph.facebook.com/me/?fields=id,name&access_token=${token}`); //<- use the token you got in your request
        const userInfo = await response.json();
        console.log(userInfo);
        alert(userInfo.name);
        // you could now save the token in AsyncStorage, Redux or leave it in state
        await AsyncStorage.setItem('token', token); // <- save the token in AsyncStorage for later use
      } else {
        // type === 'cancel'
      }
    } catch ({ message }) {
      alert(`Facebook Login Error: ${message}`);
    }
  }

    makeGraphRequest = async () => {
      try {
        let token = await AsyncStorage.getItem('token');
        // Get the user's name using Facebook's Graph API
        const response = await fetch(`https://graph.facebook.com/me/?fields=id,name&access_token=${token}`);
        const userInfo = await response.json();
        alert(userInfo.name)
      } catch (err) {
        alert(err.message)
      }
    }


  render() {
    return (
      <View style={styles.container}>
        <Button title={'Sign in to Facebook'} onPress={this.logIn} />
        <Button  title={'Make GraphQL Request'} onPress={this.makeGraphRequest} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white'
  }
});

关于react-native - 如何使用 Expo 获取 FB Access Token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735944/

相关文章:

reactjs - 如何在 Text ReactNative 中包含 TouchableOpacity

facebook-graph-api - Facebook应用程序(非用户)访问 token 到期

javascript - 单独 react native onPress TouchableHighlights 吗?

android - 在react-native中从TypeScript调用 native 函数

ios - 找不到 Facebook sdk 3.9 文件

facebook - 使用 Graph API v.2.0 获取 facebook 好友

ios - 我想使用我的 iOS 应用程序在 Facebook 墙上发布带有自定义文本的视频

php - 如何知道访问 token 是否在 Google Api PHP 中过期

azure - 具有旧访问 token ADAL 的 AcquireTokenAsync

react-native - 无法读取 React Navigation 中未定义的属性 'navigate'