简体   繁体   中英

How to Insert User Data from Facebook Canvas using PHP SDK to a Database using SQL

I'm really hoping someone here will be able to help me as I've been stuck on this for 3 days and can not seem to get it to work no matter what I try. :(

I'm making a Facebook canvas game, and I'm trying to write a PHP script that when run, will insert the player's Facebook User ID into my database, along with a timestamp of when the event took place. I want this to happen every time the script is run, so ideally, if a player activated this script say 5 times, then the database table will record their ID 5 times along with 5 different timestamps.

I've tried following the instructions on the Facebook developers site in relation to the PHP SDK, and the Graph API, and I've found the answers on here great, I've tried every one I've seen that relates to my problem but I still haven't been able to get it to work. I think I'm missing something really simple as I'm a beginner at the Facebook SDK and PHP in general.

If I understand correctly, I need to create a GraphAPI session within the PHP code, create a variable linked to $facebook->api('/me'), then request whichever user data I need, and then use an SQL INSERT statement to put the data into the database?

The code I have right now will post the current time into the database, so the connection is working fine, however my attempt at connecting to Facebook is the result of a lot of searching online and doesn't currently work (not to mention it's really messy!). I really need step by step instructions on what PHP code to put where in order to connect to the GraphAPI, get and post the player's details to the database.

PHP code (updated since I first asked the question):

<?php

session_start();

require_once '/facebook-php-sdk-v4-4.0-dev/autoload.php';

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookStream;
use Facebook\HttpClients\FacebookStreamHttpClient;

use Facebook\FacebookAuthorizationException;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookClientException;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\FacebookOtherException;
use Facebook\FacebookPageTabHelper;
use Facebook\FacebookPermissionException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookServerException;
use Facebook\FacebookSession;
use Facebook\FacebookSignedRequestFromInputHelper;
use Facebook\FacebookThrottleException;

use Facebook\GraphAlbum;
use Facebook\GraphLocation;
use Facebook\GraphObject;
use Facebook\GraphPage;
use Facebook\GraphSessionInfo;
use Facebook\GraphUser;
use Facebook\GraphUserPage;

FacebookSession::setDefaultApplication('MYAPPID','MYAPPSECRET');

$helper=new FacebookCanvasLoginHelper();

try
{
$session=$helper->getSession();
} 
catch(FacebookRequestException $ex) 
{
  //Handle Error
}
catch(\Exception $ex)
{
  //Handle Error
}

if(!isset($session)) //Redirect to Login Dialog
{ ?>
  <script>
    top.location.href="https://www.facebook.com/dialog/oauth?client_id=<?php echo 'MYAPPID'; ?>&redirect_uri=<?php echo 'https://apps.facebook.com/MYAPPADDRESS'; ?>";
  </script> <?php

 exit();
}

$facebook_data=(new FacebookRequest($session,'GET','/me'))->execute()->getGraphObject(GraphUser::className());

$user_info['AccessToken']=$session->getToken();
$user_info['UserID']=$facebook_data->getId();

//Database:
$servername = "localhost";
$username = "MYUSERNAME";
$password = "MYPASSWORD";
$dbname = "MYDATABASE";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO table1 (facebook_id, entry_timestamp) VALUES ({$user_info['UserID']}, '".date("Y-m-d H:i:s")."')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

I'm using phpMyAdmin (WAMP) on localhost, my php version is 5.6.5, MySQL 5.6.12, and Apache 2.4.12.

I should mention, I have "FacebookCanvasLoginHelper();" included in that code, however this PHP script would only be run at a point late in the game when the player has already been logged in and has given all required permissions, so I'm not sure if it's necessary to perform this check here?

Any help on this would be hugely appreciated! :)


Update:

Hi @Phillip thanks again for your reply, I've been trying to work with the code you gave me but it's still giving me an error, I'm hoping you can help again.

I entered my AppID and Secret next to FacebookSession::setDefaultApplication. And entered my AppID again and my game's Facebook URL in the script for “if(!isset($session)) //Redirect to Login Dialog”.

After you defined $user_info['AccessToken'] and $user_info['UserID] I wrote an SQL Insert statement to put UserID into my database because getting a $ variable for “UserID” is what I need, however when I run the PHP page, it just redirects to my game's home page (to the URL I entered above).

If I understand the code correctly, it's doing this because it hasn't got a $session/is not connected to the user's info on the GraphAPI and thinks that the user is not signed in, so it's redirecting them to my home page to sign in? Is that correct?

It's probably best practice but I was wondering is including the redirect necessary, as I'm looking for a PHP script that I can call on to perform the get user's info + insert it into my database actions at a point in the game when the user will definitely be logged in (ie, the page I'll be calling this script from is a page that the user will only be able to access after they have signed in and granted permissions, so is it necessary to perform the login check/initiate the FacebookCanvasLoginHelper?) In any case, does the fact that it's currently redirecting me to my game's homepage mean that the connection to get the user's data isn't successful?

What's really confusing me is that I've been working from Facebook's FriendSmash example, and they've made a GraphAPI connection in that (I think using the Javascript SDK), with that, if I include the .js file at the top of the page, I'm able to write something in HTML like:

 <div id="welcome"><p>Player's address: <span class="link"></p> 

And that will give me an output of “Player's address: (url to my (currently signed in) facebook account)”. But I can't use a PHP Insert statement to put the “link” into my database, maybe I'm expecting the variables from the connection made by the Javascript SDK to be used by the PHP SDK too and this isn't possible, maybe I need to initiate a whole new connection using the PHP SDK to be able to perform an Insert statement with PHP?

I don't understand why the code you gave me keeps redirecting me to my game's page and doesn't seem to be making the connection, when I'm already signed in. I'm sure I'm missing something very basic here. :s I really appreciate your help on this! :)

Since you're close, I'll just post what I use. Make sure you read the docs to make sure you know what's going on. Also, utilize the autoloader that Facebook provides.

<?php

session_start();

require_once '/facebook-php-sdk-v4-4.0-dev/autoload.php';

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookStream;
use Facebook\HttpClients\FacebookStreamHttpClient;

use Facebook\FacebookAuthorizationException;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookClientException;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\FacebookOtherException;
use Facebook\FacebookPageTabHelper;
use Facebook\FacebookPermissionException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookServerException;
use Facebook\FacebookSession;
use Facebook\FacebookSignedRequestFromInputHelper;
use Facebook\FacebookThrottleException;

use Facebook\GraphAlbum;
use Facebook\GraphLocation;
use Facebook\GraphObject;
use Facebook\GraphPage;
use Facebook\GraphSessionInfo;
use Facebook\GraphUser;
use Facebook\GraphUserPage;

FacebookSession::setDefaultApplication('APP_ID','APP_SECRET');

$helper=new FacebookCanvasLoginHelper();

try
{
  $session=$helper->getSession();
} 
catch(FacebookRequestException $ex) 
{
  //Handle Error
}
catch(\Exception $ex)
{
  //Handle Error
}

if(!isset($session)) //Redirect to Login Dialog
{ ?>
  <script>
    top.location.href="https://www.facebook.com/dialog/oauth?client_id=<?php echo 'APP_ID'; ?>&redirect_uri=<?php echo 'https://apps.facebook.com/my_app/'; ?>";
  </script> <?php

  exit();
}

$facebook_data=(new FacebookRequest($session,'GET','/me'))->execute()->getGraphObject(GraphUser::className());

$user_info['AccessToken']=$session->getToken();
$user_info['UserID']=$facebook_data->getId();

?>

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