Technetium 101(React Native): Facebook social login


Version

  • react-native: 0.63.4
  • react-native-fbsdk: ^3.0.0

Step 1 : Create App On Facebook Developers And Add Basic App Info



  • After success, notice the App ID at top, this will be use later in application.
  • Go to settings -> basic located at left drawer
  • Fill in Contact Email, Privacy Policy Url, Category, App Icon, Business use and save Go to bottom of Basic Settings and add platform Android/Ios

Ios


Android

  • Check applicationId from android/app/build.gradle
  • Copy applicationId from application and paste in Google Play Package Name. eg. “com.appdevtrend2021
  • Fill in Class Name with applicationId with added .MainActivity. eg”com. appdevtrend2021.MainActivity”
  • If popup comes for package name verification select “Use this package name”
  • Key Hashes need to fill in if only for release, if debug not needed (https://aboutreact.com/getting-key-hash-for-facebook-console/)
    • You will need to provide a development key hash for the development environment of each person who works on your app.
    • Download OpenSSL then extract at C:\
    • Step to produce debug development Key Hashes
      • open cmd
      • C:\Program Files\Java\jdk1.8.0_261\bin>keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | C:\openssl\bin\openssl.exe sha1 -binary | C:\openssl\bin\openssl.exe base64
      • password: android
    • Step to produce release development Key Hashes
      • locate jks file location
      • password: password for the jks file that you had created.
      • open cmd
      • C:\Program Files\Java\jdk1.8.0_261\bin>keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | PATH_TO_OPENSSL_LIBRARY\bin\openssl sha1 -binary | PATH_TO_OPENSSL_LIBRARY\bin\openssl base64
      • eg. C:\Program Files\Java\jdk1.8.0_261\bin>keytool -exportcert -alias appdevtrend2021-key -keystore C:\Users\xx\Desktop\appdevtrend2021.jks | C:\openssl\bin\openssl sha1 -binary | C:\openssl\bin\openssl base64
  • Privacy policy URL and User Data Deletion needed to Make Facebook App Live

Step 2: Add react-native-fbsdk library and link library

Add library

  • yarn add react-native-fbsdk

Additional step for IOS

  • cd ios && pod install

Step 3 : Configuration ANDROID/IOS Projects

Ios


Android

Add Facebook App Id
  • Open your /app/res/values/strings.xml file.
  • Add a string element with the name attribute facebook_app_id and value as your Facebook App ID (Replace it with your App Id)to the file. For example
    • <string name="facebook_app_id">Facebook App ID</string>


  • Add uses-permission @AndroidMAnifest
  • <uses-permission android:name="android.permission.INTERNET"/>
  • Add a meta-data element to the application element:
  • <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>


Step 4: Add code in react native project for Login

Login Button + Access Token+ Get User Info

import React, {Component} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import {
  AccessToken,
  GraphRequest,
  GraphRequestManager,
  LoginManager,
} from 'react-native-fbsdk';
export default class App extends Component {
  state = {userInfo: {}};
  logoutWithFacebook = () => {
    LoginManager.logOut();
    this.setState({userInfo: {}});
  };
  getInfoFromToken = token => {
    const PROFILE_REQUEST_PARAMS = {
      fields: {
        string: 'id,name,first_name,last_name',
      },
    };
    const profileRequest = new GraphRequest(
      '/me',
      {token, parameters: PROFILE_REQUEST_PARAMS},
      (error, user) => {
        if (error) {
          console.log('login info has error: ' + error);
        } else {
          this.setState({userInfo: user});
          console.log('result:', user);
        }
      },
    );
    new GraphRequestManager().addRequest(profileRequest).start();
  };
  loginWithFacebook = () => {
    // Attempt a login using the Facebook login dialog asking for default permissions.
    LoginManager.logInWithPermissions(['public_profile']).then(
      login => {
        if (login.isCancelled) {
          console.log('Login cancelled');
        } else {
          AccessToken.getCurrentAccessToken().then(data => {
            const accessToken = data.accessToken.toString();
            this.getInfoFromToken(accessToken);
          });
        }
      },
      error => {
        console.log('Login fail with error: ' + error);
      },
    );
  };
  state = {userInfo: {}};
  render() {
    const isLogin = this.state.userInfo.name;
    const buttonText = isLogin ? 'Logout With Facebook' : 'Login From Facebook';
    const onPressButton = isLogin
      ? this.logoutWithFacebook
      : this.loginWithFacebook;
    return (
      <View style={{flex: 1, margin: 50}}>
        <TouchableOpacity
          onPress={onPressButton}
          style={{
            backgroundColor: 'blue',
            padding: 16,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text>{buttonText}</Text>
        </TouchableOpacity>
        {this.state.userInfo.name && (
          <Text style={{fontSize: 16, marginVertical: 16}}>
            Logged in As {this.state.userInfo.name}
          </Text>
        )}
      </View>
    );
  }

}

Comments

Popular posts from this blog

Build App Insights: Mobile app development trends 2021

Build App Insights: Skeleton Screens Benefits

Technetium 101(React Native): Performance Optimization