Using Facebook Graph Api in your Ionic 2 apps

Hi friends,

First of all, I would like to thank everyone who have been reading my blog regularly and checking for updates periodically. I am happy about the response I have been getting guys. In this post I will show you how to use Facebook Graph Api in Ionic 2 apps through a cordova plugin. Again this is a response post to several people who have been asking me about this.

Lets get started.

The code for this tutorial is available here.

A screencast video of this tutorial:

 

Now lets divide the tutorial into two segments. The first segment will deal with what you need to do in the facebook developer platform to get your app running. The second segment will deal with the actual ionic app that we will be writing.

First open the facebook developer portal by clicking here.

Then add a new app by clicking on the add new app from the dropdown on the top right corner as shown in the pic below.

Kazam_screenshot_00010

Now in the modal that opens up choose your platform. (I will be choosing Android here as I am using an android phone).

In the next screen give the name of your app and click on the create new facebook App ID button.

Kazam_screenshot_00011

In the subsequent dialog that opens choose App for pages as shown below and click on the Create App ID button as shown below.

Kazam_screenshot_00012

 

In the next screen scroll down and fill the Package Name and default activity name in the Tell us about your Android application section as shown below and click next.

Kazam_screenshot_00013

In the Prompt that appears click on the Use this package name button as shown below.

Kazam_screenshot_00014

Now in the next section that appears we need to generate a key hash and paste it. To do so click on the show how to generate a development key hash link and follow the instructions. Once the key hash is generated copy and paste it here and click on next.

Now the setup is done. Scroll back up and click on the my apps button on the top right corner. You should see your app listed. Click on the app and you will see a dashboard screen. On the left hand side there will be a list of options. Click settings and a screen with all your app settings will be shown (as below).

Kazam_screenshot_00015

(Make a note of the App ID).

Let’s start with our Ionic 2 app now.

Create a blank ionic app using the below command.

Then add the cordova-plugin-facebook4 as shown below

Get the App ID from the facebook dev portal and give it here.

After adding the plugin open up config.xml and change the widget id to the package name you gave previously as shown below.

Kazam_screenshot_00017

Now let’s code our app. Our app will be a very simple one. We will have 3 buttons. One will be login button, a get details button and a logout button.

Open up home.html in the pages, home directory and insert the below code inbetween the <ion-content> tags.

Now open up the home.js file and insert the below code.

Let’s break this down.

  1. The login function helps in logging in to the user account (It would ask for permission when you login the first time).
  2. The getdetails() checks whether the user is logged in and if so, returns the id, name and gender of the user. This is where the Graph Api call is made. If the user is not logged in then it simply returns an alert with the message not logged in.
  3. Logout function is used to logout (Funny, I know. :)).

That’s it. Now run the app in an emulator or android device using the below command.

If everything’s fine you should now see an app using which you could connect to the Facebook platform.

Thanks for reading guys. All comments and suggestions are welcome. Peace.. :)

 

Liked it? Take a second to support admin on Patreon!
  • Do I need to make a separate facebook app for each platform? ie do one for ios and one for android?

    • Nope.. you could simple use the command ionic platform add android/ios while building your app. (Recently windows support has been made available too).

      • I meant during the Facebook App Set up, where you click Android.

        “Now in the modal that opens up choose your platform. (I will be choosing Android here as I am using an android phone).”

        Do i need to make one Facebook App with Android chosen, and one Facebook App with iOs chosen?

    • Ionic Facebook

      how to facebook login userdata store in mysql with ionic v2 ???

  • Nimesh Chathuranga

    can you upload video google authentication

  • Ayadi

    perfect tutorial
    but i new in ionic , i need to view data in html page ,can u help me ?

  • Ionic Facebook

    can’t find facebookconnectplugin in ionic v2 ,it’s not sloved

    • Ionic Facebook

      solution:
      declare const facebookConnectPlugin: any;

      • Sinan Argun

        Are you sure that is solution?

        • HR PATEL

          yes

          • Sinan Argun

            I have tried same solution. But it didn’t work.

          • HR PATEL

            I complete to facebook login and fb login user data store in mysql database with ionic2

          • HR PATEL

            i will send my code=====>

            import {Http, Headers, RequestOptions} from ‘@angular/http’;
            import ‘rxjs/add/operator/map’;

            declare const facebookConnectPlugin: any;
            @Component({
            templateUrl: ‘build/pages/home/home.html’,
            })
            export class HomePage {
            posts:any;
            constructor(public platform: Platform, private navCtrl: NavController,private http: Http)
            { this.platform = platform;
            this.http = http;
            }

            fblogin()
            {
            this.platform.ready().then(() => {
            this.fblogin1().then(success => {
            console.log(“facebook data===” + success);
            alert(“facebook data===” + success);
            this.http.post(‘http://localhost/facebook.php’,success)
            .map( res =>res.json()).subscribe(data => {
            if(data.msg==”fail”)
            {
            console.log(‘Login failed’);
            alert(“Invalid username and password”);
            return;
            }
            else
            {
            console.log(‘ login Sucessfully facebook’);
            }
            });
            }, (error) => {
            alert(error);
            });
            });
            }
            fblogin1(): Promise
            {
            return new Promise(function(resolve,reject)
            {
            facebookConnectPlugin.login([“email”], function(response)
            {
            alert(JSON.stringify(response.authResponse));
            facebookConnectPlugin.api(‘/’ + response.authResponse.userID + ‘?fields=id,name,email,gender’,[],
            function onSuccess(result)
            {
            //alert(JSON.stringify(result));
            //console.log(JSON.stringify(result));
            resolve(JSON.stringify(result));
            },
            function onError(error)
            {
            alert(error);
            }
            );
            },
            function(error)
            {
            alert(error);
            })
            });
            }

            }

          • HR PATEL

            this code run it,
            your login sucess

          • Sinan Argun

            Hello again, have you used any javascript file to reach facebookConnectPlugin’s method?

          • HR PATEL

            no used for javascript file ,
            only for used to facebook plugin

          • Adir Zoari

            hey, i copied your code but it’s not works at all,do you have email to talk with u?

          • HR PATEL

            used for facebookConnectPlugin.login not used to this.facebookConnectPlugin.login

          • HR PATEL

            ionic plugin add cordova-plugin-facebook4 –variable APP_ID=”123456789″ –variable APP_NAME=”myApplication”

          • abhinav

            no but i am getting same error

        • HR PATEL

          yes ,sure

  • Ionic Facebook

    Sorry, something went wrong. We’re working on it and we’ll get it fixed as soon as we can, show my error

    solution ====> plz create new devloper a/c and change the facebook id,we are successfully run for appp….

  • abhinav

    i am also error in face book login
    error is
    browser_adapter.js:84 ORIGINAL EXCEPTION: TypeError: this.facebookConnectPlugin.login is not a functio

  • abhinav

    please provide solution for that

  • Ajay Saini

    good tutorial but i have one question if user registered mobile number with facebook then how to get user mobile number? any graph api is there or not ?

  • Neel Muley

    How do i get user mobile no using facebook graph api

  • César Hergueta

    Hi Raja, great tutorial. In Android all working perfect but in iOS when i clicked in the login button the console from Xcode print this error:

    WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: Permissions should each be specified in separate string values in the array.

    Any idea?

    Thanks.