首页 > 解决方案 > 如何通过 Expo 获取 FB Access Token

问题描述

我正在构建需要在许多地方发出 Facebook Graph API 请求的应用程序。但我不知道如何检索访问令牌然后发出 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}`);
}
}

有人可以帮助我并给我一些提示,我可以在我的应用程序中的任何地方使用访问令牌吗?先感谢您

标签: react-nativefacebook-graph-apiaccess-tokenexpo

解决方案


获取token并将其保存到AsyncStorage

那么您编写的代码基本上是正确的。您已成功获得访问令牌。当您提出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",
    ...
    }
}

token_AsyncStorage

然后,如果您想稍后提出另一个请求,您可以使用与此类似的功能,然后从中token取出,AsyncStorage然后使用它来提出您的请求。

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然后如果你将你的 appID 等添加到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'
  }
});

推荐阅读