简体   繁体   中英

How to save Facebook user data to MySql database with Angular and Ionic

I am working an an Ionic app where I implement native Facebook login (followed this tutorial -> https://ionicthemes.com/tutorials/about/native-facebook-login-with-ionic-framework ). As you can see the Facebook data now gets stored in local storage. I need to save this data in my MySql database.

I got this to work without any issues. Now I want to store the Facebook user data to my MySql database.

Basically I am not sure where to place my http request to pass the data along to my database or how to even do it code wise.

I should mention that I have a backend already setup (which is coded with bootstrap, html, css, js php and mysql).

So the url for my users would be this: http://www.xxxxx.com/user.php

Part of my controller code:

app.controller('LoginCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
  // This is the success callback from the login method
  var fbLoginSuccess = function(response) {
    if (!response.authResponse){
      fbLoginError("Cannot find the authResponse");
      return;
    }

    var authResponse = response.authResponse;

    getFacebookProfileInfo(authResponse)
    .then(function(profileInfo) {
      // For the purpose of this example I will store user data on local storage
      UserService.setUser({
        authResponse: authResponse,
                userID: profileInfo.id,
                name: profileInfo.name,
                email: profileInfo.email,
        picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
      });
      $ionicLoading.hide();
      $state.go('app.dashboard');
    }, function(fail){
      // Fail get profile info
      console.log('profile info fail', fail);
    });
  };

  // This is the fail callback from the login method
  var fbLoginError = function(error){
    console.log('fbLoginError', error);
    $ionicLoading.hide();
  };

  // This method is to get the user profile info from the facebook api
  var getFacebookProfileInfo = function (authResponse) {
    var info = $q.defer();

    facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
      function (response) {
                console.log('logging facebook response',response);
        info.resolve(response);
      },
      function (response) {
                console.log(response);
        info.reject(response);
      }
    );
    return info.promise;
  };

  //This method is executed when the user press the "Login with facebook" button
  $scope.facebookSignIn = function() {
    facebookConnectPlugin.getLoginStatus(function(success){
      if(success.status === 'connected'){
        // The user is logged in and has authenticated your app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed request, and the time the access token
        // and signed request each expire
        console.log('getLoginStatus', success.status);

            // Check if we have our user saved
            var user = UserService.getUser('facebook');

            if(!user.userID){
                    getFacebookProfileInfo(success.authResponse)
                    .then(function(profileInfo) {
                        // For the purpose of this example I will store user data on local storage
                        UserService.setUser({
                            authResponse: success.authResponse,
                            userID: profileInfo.id,
                            name: profileInfo.name,
                            email: profileInfo.email,
                            picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
                        });
                        $state.go('app.dashboard');
                    }, function(fail){
                        // Fail get profile info
                        console.log('profile info fail', fail);
                    });
                }else{
                    $state.go('app.dashboard');
                }
      } else {
        // If (success.status === 'not_authorized') the user is logged in to Facebook,
                // but has not authenticated your app
        // Else the person is not logged into Facebook,
                // so we're not sure if they are logged into this app or not.

                console.log('getLoginStatus', success.status);

                $ionicLoading.show({
          template: 'Logging in...'
        });

                // Ask the permissions you need. You can learn more about
                // FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
        facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
      }
    });
  };
})

My service.js code (local storage)

angular.module('Challenger.services', [])

.service('UserService', function() {
  // For the purpose of this example I will store user data on ionic local storage but you should save it on a database
  var setUser = function(user_data) {
    window.localStorage.starter_facebook_user = JSON.stringify(user_data);
  };

  var getUser = function(){
    return JSON.parse(window.localStorage.starter_facebook_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };
});

My recommendation is to simply use a JSON ajax PUT or POST from JavaScript. For example, assuming a backend host of example.com

Add a CSP to the Ionic HTML such as:

<meta http-equiv="Content-Security-Policy" content="default-src http://example.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

Add the domain to the whitelist in the Cordova config.xml:

<access origin="http://example.com" />

Then you can call PHP from JavaScript with ajax in your angular controller (I used jQuery here but you can use any JavaScript ajax library):

var data = {
        authResponse: authResponse,
                userID: profileInfo.id,
                name: profileInfo.name,
                email: profileInfo.email,
        picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
      };

$.post( "http://example.com/login.php", data, function(returnData, status) {
   console.log('PHP returned HTTP status code', status);
});

Finally, on the PHP side — eg login.php — access the post data with $_POST['userId'] , $_POST['email'] , etc.

I guess that you have all your codes ready, but just not sure where is the best place to locate your codes. There is nice linker where has clear instruction about how to layout your php project structure: http://davidshariff.com/blog/php-project-structure/ , hope this can give a kind of help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM