与 Facebook 集成的网络聊天

     2023-03-17     136

关键词:

【中文标题】与 Facebook 集成的网络聊天【英文标题】:Web Chat with Facebook Integration 【发布时间】:2012-05-03 16:34:08 【问题描述】:

我需要你们的帮助,我正在为我的在线广播网站构建自己的网络聊天。我已经有一个来自 Tutorialzine 的 AJAX PHP Web 聊天。我想修改它。但我不知道从哪里开始。我希望它与 Facebook 集成。我想要它而不是询问用户名和电子邮件,会有一个按钮显示“连接到 Facebook”。并且用户的头像和姓名会自动保存到数据库中。我真的需要它。我希望它能够被缓和。谢谢你!上帝保佑大家! :)

ajax.php

<?php

/* Database Configuration. Add your details below */

$dbOptions = array(
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => '',
'db_name' => 'chat'
);

/* Database Config End */


error_reporting(E_ALL ^ E_NOTICE);

require "classes/DB.class.php";
require "classes/Chat.class.php";
require "classes/ChatBase.class.php";
require "classes/ChatLine.class.php";
require "classes/ChatUser.class.php";

session_name('webchat');
session_start();

if(get_magic_quotes_gpc())

// If magic quotes is enabled, strip the extra slashes
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
array_walk_recursive($_POST,create_function('&$v,$k','$v = stripslashes($v);'));


try

// Connecting to the database
DB::init($dbOptions);

$response = array();

// Handling the supported actions:

switch($_GET['action'])

    case 'login':
        $response = Chat::login($_POST['name'],$_POST['email']);
    break;

    case 'checkLogged':
        $response = Chat::checkLogged();
    break;

    case 'logout':
        $response = Chat::logout();
    break;

    case 'submitChat':
        $response = Chat::submitChat($_POST['chatText']);
    break;

    case 'getUsers':
        $response = Chat::getUsers();
    break;

    case 'getChats':
        $response = Chat::getChats($_GET['lastID']);
    break;

    default:
        throw new Exception('Wrong action');


echo json_encode($response);

catch(Exception $e)
die(json_encode(array('error' => $e->getMessage())));


?>

script.js

$(document).ready(function()

// Run the init method on document ready:
chat.init();

);

var chat = 

// data holds variables for use in the class:

data : 
    lastID      : 0,
    noActivity  : 0
,

// Init binds event listeners and sets up timers:

init : function()

    // Using the defaultText jQuery plugin, included at the bottom:
    $('#name').defaultText('Nickname');
    $('#email').defaultText('Email (Gravatars are Enabled)');

    // Converting the #chatLineHolder div into a jScrollPane,
    // and saving the plugin's API in chat.data:

    chat.data.jspAPI = $('#chatLineHolder').jScrollPane(
        verticalDragMinHeight: 12,
        verticalDragMaxHeight: 12
    ).data('jsp');

    // We use the working variable to prevent
    // multiple form submissions:

    var working = false;

    // Logging a person in the chat:

    $('#loginForm').submit(function()

        if(working) return false;
        working = true;

        // Using our tzPOST wrapper function
        // (defined in the bottom):

        $.tzPOST('login',$(this).serialize(),function(r)
            working = false;

            if(r.error)
                chat.displayError(r.error);
            
            else chat.login(r.name,r.gravatar);
        );

        return false;
    );

    // Submitting a new chat entry:

    $('#submitForm').submit(function()

        var text = $('#chatText').val();

        if(text.length == 0)
            return false;
        

        if(working) return false;
        working = true;

        // Assigning a temporary ID to the chat:
        var tempID = 't'+Math.round(Math.random()*1000000),
            params = 
                id          : tempID,
                author      : chat.data.name,
                gravatar    : chat.data.gravatar,
                text        :  text.replace(/</g,'&lt;').replace(/>/g,'&gt;')
            ;

        // Using our addChatLine method to add the chat
        // to the screen immediately, without waiting for
        // the AJAX request to complete:

        chat.addChatLine($.extend(,params));

        // Using our tzPOST wrapper method to send the chat
        // via a POST AJAX request:

        $.tzPOST('submitChat',$(this).serialize(),function(r)
            working = false;

            $('#chatText').val('');
            $('div.chat-'+tempID).remove();

            params['id'] = r.insertID;
            chat.addChatLine($.extend(,params));
        );

        return false;
    );

    // Logging the user out:

    $('a.logoutButton').live('click',function()

        $('#chatTopBar > span').fadeOut(function()
            $(this).remove();
        );

        $('#submitForm').fadeOut(function()
            $('#loginForm').fadeIn();
        );

        $.tzPOST('logout');

        return false;
    );

    // Checking whether the user is already logged (browser refresh)

    $.tzGET('checkLogged',function(r)
        if(r.logged)
            chat.login(r.loggedAs.name,r.loggedAs.gravatar);
        
    );

    // Self executing timeout functions

    (function getChatsTimeoutFunction()
        chat.getChats(getChatsTimeoutFunction);
    )();

    (function getUsersTimeoutFunction()
        chat.getUsers(getUsersTimeoutFunction);
    )();

,

// The login method hides displays the
// user's login data and shows the submit form

login : function(name,gravatar)

    chat.data.name = name;
    chat.data.gravatar = gravatar;
    $('#chatTopBar').html(chat.render('loginTopBar',chat.data));

    $('#loginForm').fadeOut(function()
        $('#submitForm').fadeIn();
        $('#chatText').focus();
    );

,

// The render method generates the HTML markup 
// that is needed by the other methods:

render : function(template,params)

    var arr = [];
    switch(template)
        case 'loginTopBar':
            arr = [
            '<span><img src="',params.gravatar,'"   />',
            '<span class="name">',params.name,
            '</span><a href="" class="logoutButton rounded">Logout</a></span>'];
        break;

        case 'chatLine':
            arr = [
                '<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
                '"   onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
                ':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
        break;

        case 'user':
            arr = [
                '<div class="user" title="',params.name,'"><img src="',
                params.gravatar,'"   onload="this.style.visibility=\'visible\'" /></div>'
            ];
        break;
    

    // A single array join is faster than
    // multiple concatenations

    return arr.join('');

,

// The addChatLine method ads a chat entry to the page

addChatLine : function(params)

    // All times are displayed in the user's timezone

    var d = new Date();
    if(params.time) 

        // PHP returns the time in UTC (GMT). We use it to feed the date
        // object and later output it in the user's timezone. JavaScript
        // internally converts it for us.

        d.setUTCHours(params.time.hours,params.time.minutes);
    

    params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
                  (d.getMinutes() < 10 ? '0':'') + d.getMinutes();

    var markup = chat.render('chatLine',params),
        exists = $('#chatLineHolder .chat-'+params.id);

    if(exists.length)
        exists.remove();
    

    if(!chat.data.lastID)
        // If this is the first chat, remove the
        // paragraph saying there aren't any:

        $('#chatLineHolder p').remove();
    

    // If this isn't a temporary chat:
    if(params.id.toString().charAt(0) != 't')
        var previous = $('#chatLineHolder .chat-'+(+params.id - 1));
        if(previous.length)
            previous.after(markup);
        
        else chat.data.jspAPI.getContentPane().append(markup);
    
    else chat.data.jspAPI.getContentPane().append(markup);

    // As we added new content, we need to
    // reinitialise the jScrollPane plugin:

    chat.data.jspAPI.reinitialise();
    chat.data.jspAPI.scrollToBottom(true);

,

// This method requests the latest chats
// (since lastID), and adds them to the page.

getChats : function(callback)
    $.tzGET('getChats',lastID: chat.data.lastID,function(r)

        for(var i=0;i<r.chats.length;i++)
            chat.addChatLine(r.chats[i]);
        

        if(r.chats.length)
            chat.data.noActivity = 0;
            chat.data.lastID = r.chats[i-1].id;
        
        else
            // If no chats were received, increment
            // the noActivity counter.

            chat.data.noActivity++;
        

        if(!chat.data.lastID)
            chat.data.jspAPI.getContentPane().html('<p class="noChats">No chats yet</p>');
        

        // Setting a timeout for the next request,
        // depending on the chat activity:

        var nextRequest = 1000;

        // 2 seconds
        if(chat.data.noActivity > 3)
            nextRequest = 2000;
        

        if(chat.data.noActivity > 10)
            nextRequest = 5000;
        

        // 15 seconds
        if(chat.data.noActivity > 20)
            nextRequest = 15000;
        

        setTimeout(callback,nextRequest);
    );
,

// Requesting a list with all the users.

getUsers : function(callback)
    $.tzGET('getUsers',function(r)

        var users = [];

        for(var i=0; i< r.users.length;i++)
            if(r.users[i])
                users.push(chat.render('user',r.users[i]));
            
        

        var message = '';

        if(r.total<1)
            message = 'No one is online';
        
        else 
            message = r.total+' '+(r.total == 1 ? 'person':'people')+' online';
        

        users.push('<p class="count">'+message+'</p>');

        $('#chatUsers').html(users.join(''));

        setTimeout(callback,15000);
    );
,

// This method displays an error message on the top of the page:

displayError : function(msg)
    var elem = $('<div>',
        id      : 'chatErrorMessage',
        html    : msg
    );

    elem.click(function()
        $(this).fadeOut(function()
            $(this).remove();
        );
    );

    setTimeout(function()
        elem.click();
    ,5000);

    elem.hide().appendTo('body').slideDown();

;

// Custom GET & POST wrappers:

$.tzPOST = function(action,data,callback)
$.post('php/ajax.php?action='+action,data,callback,'json');


$.tzGET = function(action,data,callback)
$.get('php/ajax.php?action='+action,data,callback,'json');


// A custom jQuery method for placeholder text:

$.fn.defaultText = function(value)

var element = this.eq(0);
element.data('defaultText',value);

element.focus(function()
    if(element.val() == value)
        element.val('').removeClass('defaultText');
    
).blur(function()
    if(element.val() == '' || element.val() == value)
        element.addClass('defaultText').val(value);
    
);

return element.blur();

【问题讨论】:

【参考方案1】:

如果您只想通过用户名和图片与 facebook 连接,那么您只需添加 Facebook Javascript SDK,然后使用 Login Button plugin 或使用 Client-Side authentication。

如果你想连接Facebook内部聊天,那么你可以使用Chat API,它有两种认证方式:Facebook Platform和Username/Password。 如果您想要第一种方法(听起来像您想要的那样),那么您需要使用客户端流程或server side flow 对用户进行身份验证,并要求提供"xmpp_login" permission。

聊天 API 文档中有 php 示例。

【讨论】:

现在,我可以获取 Facebook 信息了。但我的问题是我将如何编辑 PHP、AJAX 和 JAVASCRIPTS。我真的很困惑。 :( 你需要更具体。 我现在可以从 facebook 获取信息。但是,我还需要修改我的 PHP 脚本。但我不知道要修改什么。我可以将数据存储到我的数据库中。但它只是存储到数据库。我的聊天框没有任何反应。 :( 我不知道你在做什么,我什至不是 php 程序员。你需要自己弄清楚。如果您有更具体的问题问他们,请添加代码。 您发布了代码,但您没有具体问题,除此之外,我不喜欢 php。你有 facebook 给出的 php 代码作为示例,自己尝试一下,然后提出具体问题。

Facebook 应用程序集成聊天

】Facebook应用程序集成聊天【英文标题】:FacebookApplicationintegratingChat【发布时间】:2010-08-0312:16:36【问题描述】:如何将phpweb应用程序与facebook聊天集成?我已经集成了facebook应用程序并成功编码了xmpp-login权限的授予。但现在我... 查看详情

在 Flutter 中,如何将 facebook 受众作为中介网络与 Admob 集成?

】在Flutter中,如何将facebook受众作为中介网络与Admob集成?【英文标题】:Influtter,howtointegratefacebookaudienceasmediationnetworkwithAdmob?【发布时间】:2020-08-0903:37:50【问题描述】:我是广告中介的新手。我有一个颤振应用程序,我使用... 查看详情

php 站点中类似 facebook 的聊天 freichat 集成代码

】php站点中类似facebook的聊天freichat集成代码【英文标题】:facebook-likechatfreichatintegrationcodeinphpsite【发布时间】:2011-12-2507:41:56【问题描述】:Freichat是一个非常有名的facebook脚本,就像在任何php网站上聊天一样。我认为在SOF中而... 查看详情

XMPP 与 Facebook Chat 集成,使用 Python

】XMPP与FacebookChat集成,使用Python【英文标题】:XMPPintregrationwithFacebookChat,usingPython【发布时间】:2011-02-2805:41:58【问题描述】:我正在使用XMPP协议开始一个项目,但到目前为止还没有做任何事情。我想就以下问题获得一些建议/... 查看详情

将 facebook 弹出式聊天集成到网站中

】将facebook弹出式聊天集成到网站中【英文标题】:integratingfacebookpopoutchatintowebsite【发布时间】:2011-09-2106:18:37【问题描述】:我想将facebook弹出式聊天集成到我网站的聊天栏中,以便用户可以从我的网站查看他们的facebook聊天... 查看详情

集成 Facebook 聊天

】集成Facebook聊天【英文标题】:IntegratingFacebookChat【发布时间】:2011-02-1918:45:22【问题描述】:我被要求仅使用JavaScript将FacebookChat集成到我的应用程序中。我不能使用XFacebook平台身份验证,因为它需要域URL。所以我的选择是通... 查看详情

构建一个集成了 facebook 聊天的 web 客户端?

】构建一个集成了facebook聊天的web客户端?【英文标题】:Buildawebclientintegratedfacebookchat?【发布时间】:2010-11-1809:23:10【问题描述】:我正在使用GoogleAppEngine,我有兴趣创建一个集成了facebook聊天的网站。我阅读了IntegratingwithFacebo... 查看详情

Android 分享意图与实际 Facebook 集成

】Android分享意图与实际Facebook集成【英文标题】:AndroidshareintentvsactualFacebookintegration【发布时间】:2013-04-2419:45:50【问题描述】:我打算将“facebook分享”集成到一个应用程序中。基本上是一个带有链接、图像和文本的时间轴帖... 查看详情

Facebook 与 Asp .Net 的集成

】Facebook与Asp.Net的集成【英文标题】:FacebookintegrationwithAsp.Net【发布时间】:2011-09-1511:57:47【问题描述】:我需要将facebook与我的asp.net应用程序集成。这是我为它遵循的步骤。我已经从Facebook创建了Facebook应用程序,并获得了应... 查看详情

使用图形 api 集成 facebook 聊天

】使用图形api集成facebook聊天【英文标题】:integratingfacebookchatusinggraphapi【发布时间】:2011-02-1817:09:57【问题描述】:有人要求我使用javascript在我的应用程序中集成facebook聊天。我浏览了聊天api,但这需要一个域url。我必须在没... 查看详情

将 Facebook 登录与 Parse 集成

】将Facebook登录与Parse集成【英文标题】:IntegrateFacebookLoginwithParse【发布时间】:2017-08-1022:41:50【问题描述】:在我的Xcode项目中,我已经有了一个使用他们创建的用户用户名和密码的登录功能。现在我想在项目中集成一个Facebook... 查看详情

将 Facebook 的 Account Kit 与 Parse 集成

】将Facebook的AccountKit与Parse集成【英文标题】:IntegrateFacebook’sAccountKitwithParse【发布时间】:2016-12-0122:06:08【问题描述】:我想将来自Facebook的新登录框架AccountKit(其中包括提供电话登录)集成到使用Parse的iOS应用程序中。我能... 查看详情

asmack 中的 MessageListener 以集成无法绑定到任何小部件的 facebook 聊天

】asmack中的MessageListener以集成无法绑定到任何小部件的facebook聊天【英文标题】:MessageListenerinasmacktointegratefacebookchatnotabletobindtoanywidget【发布时间】:2013-02-1311:21:40【问题描述】:我在一个android应用程序中工作,我想在其中集... 查看详情

Facebook SDK 与 Android Studio 的集成

】FacebookSDK与AndroidStudio的集成【英文标题】:FacebookSDKintegrationwithAndroidStudio【发布时间】:2014-08-2722:21:05【问题描述】:我正在尝试将FacebookSDK集成到我的android项目中,但无法这样做。我已按照facebook文档中提到的步骤进行操作... 查看详情

Salesforce 与 facebook messenger 的集成

】Salesforce与facebookmessenger的集成【英文标题】:SalesforceIntegrationWithfacebookmessanger【发布时间】:2020-02-2618:11:24【问题描述】:我想将SalesForce与FacebookMessenger集成。为此,我检索了访问令牌、应用程序ID、应用程序密码。当我在开... 查看详情

更改 PFUser 用户名,解析与 Facebook 集成

】更改PFUser用户名,解析与Facebook集成【英文标题】:ChangePFUserusername,ParseIntegrationwithFacebook【发布时间】:2014-10-3005:08:39【问题描述】:我正在编写一个支持IOSParse的应用程序,您可以在其中使用facebook登录。我已经解析以创建... 查看详情

将 Spring Security 与 Facebook 登录集成

】将SpringSecurity与Facebook登录集成【英文标题】:IntegrateSpringSecuritywithFacebookLogin【发布时间】:2014-06-1920:18:47【问题描述】:我在我的项目中使用SpringMVC和SpringSecurity。这使用我自己的用户数据进行身份验证。但现在我试图与Faceb... 查看详情

Wit.ai 与 Facebook Messenger 的集成

】Wit.ai与FacebookMessenger的集成【英文标题】:Wit.aiIntegrationwithFacebookMessenger【发布时间】:2016-12-0216:04:16【问题描述】:您好,我正在尝试将使用Node.js创建的MessengerBot与基于https://github.com/wit-ai/node-wit的Wit.ai集成,因此我的代码与... 查看详情