简体   繁体   English

调用Facebook PHP SDK 3将用户传递到AS3项目

[英]Calling Facebook PHP SDK 3 to pass user to AS3 Project

I'm having issues with loading the user's information into Flash from a PHP script. 从PHP脚本将用户信息加载到Flash中时遇到问题。

EDIT: index.php is called by Facebook to Authenticate. 编辑:index.php由Facebook调用以进行身份​​验证。 Flash then calls database.php to connect to the database and store/recall the players information and progress. 然后,Flash调用database.php连接到数据库,并存储/调用播放器信息和进度。 Database.php then encodes the array and echos it out to Flash where it is parsed. 然后,Database.php对数组进行编码,并将其回显到要解析的Flash中。

This was working up until last weekend. 这一直持续到上周末。

index.php index.php

<?php
$app_id = "my_id";
$app_secret = "my_secret";
$my_url = "http://apps.facebook.com/my_app";

session_start();
$code = $_REQUEST["code"];

if(empty($code)) 
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
 $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
   . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
   . $_SESSION['state'];

 echo("<script> top.location.href='" . $dialog_url . "'</script>");
 exit;
}

if($_REQUEST['state'] == $_SESSION['state']) {
 $token_url = "https://graph.facebook.com/oauth/access_token?"
   . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
   . "&client_secret=" . $app_secret . "&code=" . $code;

 $response = file_get_contents($token_url);
 $params = null;
 parse_str($response, $params);

 $graph_url = "https://graph.facebook.com/me?access_token=" 
   . $params['access_token'];

 $user = json_decode(file_get_contents($graph_url));
 //echo("Hello " . $user->name);
 include_once 'game.php';
}
else 
{
    echo("The state does not match. Try opening the app from the homepage.");
    include_once 'game.php';
}
?>

database.php database.php

<?php
require 'src/facebook.php';

$facebook = new Facebook(array(
 'appId'  => 'my_id',
 'secret' => 'my_secret',
));

// Get User ID
try 
    {
    $user = $facebook->getUser();

    if ($user) 
        {
            $user_profile = $facebook->api('/me');

            //$friends = $facebook->api('/me/friends');
            //print_r($friends);
            mysql_connect("localhost", "DB_USER", "DB_PASS") or die("Could not connect");
        mysql_select_db("stus_zombies") or die("Could not select database");

        $query = mysql_query("SELECT * FROM users WHERE facebook_id = " . $user_profile[id]);  
        $result = mysql_fetch_array($query);

        if(empty($result))
        { 
            $addInfo = mysql_query("INSERT INTO users (first_name, last_name, facebook_id) 
            VALUES ('{$user_profile['first_name']}','{$user_profile['last_name']}','{$user_profile['id']}')");  
                $addInfo = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());  

            $query = mysql_query("INSERT INTO players (facebook_id, coins, health, stamina, xp)
            VALUES ('{$user_profile['id']}','0','25','25','0')");
        }

        $checkProgress = mysql_query("SELECT * FROM players WHERE facebook_id = " . $user_profile[id]);
        $playerCheck = mysql_fetch_array($checkProgress);

        $playerInfo = array(
        first_name => $user_profile[first_name],
            last_name => $user_profile[last_name],
            facebook_id => $user_profile[id], 
            //facebook_access_token => $_SESSION[fb_165114483572553_access_token],
            coins => $playerCheck[coins],
        health => $playerCheck[health],
        stamina => $playerCheck[stamina],
        xp => $playerCheck[xp],); 
        echo json_encode($playerInfo);
        } 

    else
    {
        echo ("No User");
    }
}

catch (FacebookApiException $e) 
{
    error_log($e);
        $user = null;
    }
?>

I changed to a different authentication method, and that worked for a couple hours before it stopped. 我改为使用其他身份验证方法,该方法在停止之前已经工作了几个小时。

The second index.php I tried: 我尝试的第二个index.php:

 <?php

 $app_id = "165114483572553";

 $canvas_page = "https://apps.facebook.com/MY_APP";

 $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
        . $app_id . "&redirect_uri=" . urlencode($canvas_page);

 $signed_request = $_REQUEST["signed_request"];

 list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

 $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

 if (empty($data["user_id"])) {
        echo("<script> top.location.href='" . $auth_url . "'</script>");
 } else {
 include_once 'game.php';
 } 
 ?>

AS3 Class database.as AS3类数据库

package  
{
import flash.events.IOErrorEvent;
import com.adobe.webapis.URLLoaderBase;
import flash.events.Event;
import flash.net.*;
import com.adobe.serialization.json.JSON;
import org.flashdevelop.utils.FlashConnect;
import HUD.UI;

public class Database
{
    // Page Loader
    private static var loader:URLLoader;
    private static var dataloader:URLLoader;

    // User Info
    private static var playerData:Object;

    //TEST
    // Player Info
    private static var playerLoader:URLLoader = new URLLoader();
    private static var playerRequest:URLRequest = new URLRequest;
    playerRequest.url = "http://MYURL/database.php";

    public function Database() 
    {

    }

    public function getPlayer():void
    {
        playerLoader.load(playerRequest);
        playerLoader.addEventListener(Event.COMPLETE, decodeJSONPlayer);
        playerLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    }
    // Decode JSON (Player Coins, ID, Stamina, Health, XP)
    private function decodeJSONPlayer(e:Event):void
    {
        playerLoader = URLLoader(e.target);
        playerData = JSON.decode(playerLoader.data);
        loadPlayerInfo(playerData);
        // Display stats info
        UI.updateHealth();
        UI.updateMoney();
        UI.updateXP();
        UI.updateStamina();
    }

    // Load database info into player's data
    private function loadPlayerInfo(playerData:Object):void
    {
        Player.first_name = playerData.first_name;
        Player.last_name = playerData.last_name;
        Player.facebook_id = playerData.facebook_id;
        Player.facebook_access_token = playerData.facebook_access_token;
        Player.health = playerData.health;
        Player.stamina = playerData.stamina;
        Player.money = playerData.coins;
        Player.xp = playerData.xp;
        trace(playerData.first_name);
        // Display Facebook info
        UI.txtFacebookInfo.text = playerData.first_name +" " + playerData.last_name +" " + playerData.facebook_id;
    }

    // Save all Progress
    public static function setAll(_money:int, _health:int, _stamina:int, _xp:int):void
    {
        var vars:URLVariables = new URLVariables();
        vars.money = _money;
        vars.health = _health;
        vars.stamina = _stamina;
        vars.xp = _xp;

        var request:URLRequest = new URLRequest("http://MYURL/saveplayer.php");
        request.method = URLRequestMethod.POST;
        request.data = vars;

        if (loader != null)
        {
            loader.removeEventListener(Event.COMPLETE, pageLoaded);
        }

        loader = new URLLoader();
        loader.dataFormat = URLLoaderDataFormat.TEXT;
        loader.load(request);
        loader.addEventListener(Event.COMPLETE, pageLoaded);
    }

    private static function pageLoaded(e:Event):void
    {
        trace("PAGE LOADED\n============================");
        FlashConnect.trace(loader.data);
        trace("============================");
    }

    private static function completeHandler(event:Event):void
    {
        var loader:URLLoader = URLLoader(event.target);
        FlashConnect.trace(loader.data.dayNames);
    }

    // Server info not received
    private function onIOError(e:Event):void
    {
        trace ("Error loading URL");
    }
}

}

Changing it back to the original code worked till the next day before it stopped working. 将其更改回原始代码的工作一直到第二天才停止工作。

I managed to get it working with a temporary fix by including the database script in with the index script and then calling it from Flash. 通过将数据库脚本包含在索引脚本中,然后从Flash调用它,我设法使它可以使用临时修复程序。

That just stopped working. 那只是停止工作。 Obviously this is driving me insane. 显然,这让我发疯。 Including database.php in index.php even now will trace echo out the JSON information correctly, but it isn't loaded into the game. 即使在index.php中包括database.php,现在也可以正确地 跟踪 回显JSON信息,但不会将其加载到游戏中。

On the Flash side, I had it hooked up to a button so I could call it and see the return and it seemed to be working fine. 在Flash方面,我将其连接到一个按钮,以便可以调用它并查看返回值,并且它似乎工作正常。 I am never getting errors returned when it doesn't load the player's information which makes troubleshooting this trial and error and research. 当它不加载播放器的信息时,我再也不会收到返回错误的信息,这使得对这个反复试验和研究进行故障排除。

Any help would be greatly appreciated. 任何帮助将不胜感激。 I have spent way too much of my time adapting scripts and researching at this point when there is someone out there that knows what is going on. 此时,当有人知道发生了什么事情时,我花了太多时间调整脚本并进行研究。

This was a domain issue with Facebook sometimes calling my domain with ssl which was different than the unsecured domain. 这是一个域问题,Facebook有时用ssl调用我的域,该域与不安全域不同。 Solved by forcing it and my app to call the secure domain. 通过强制它和我的应用程序调用安全域来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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