如何通过Expo获取FB访问令牌

时间:2019-02-17 17:49:22

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

我正在构建需要在许多地方发出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}`);
}
}

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

1 个答案:

答案 0 :(得分:0)

获取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'
  }
});