Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用reactjs实现Facebook API登录_Javascript_Facebook_Facebook Javascript Sdk_Reactjs - Fatal编程技术网

Javascript 使用reactjs实现Facebook API登录

Javascript 使用reactjs实现Facebook API登录,javascript,facebook,facebook-javascript-sdk,reactjs,Javascript,Facebook,Facebook Javascript Sdk,Reactjs,我正在使用Facebook的Javascript SDK进行身份验证。我已经能够正确导入SDK,并在我的页面上放置一个Like按钮。但是,facebook登录按钮必须包装在标签中: <fb:login-button/> 如何让登录按钮进入react?我已经找到了如何使用react JS修改Facebook登录API教程的方法。我希望这有助于其他正在努力解决这一问题的人 首先,在需要登录链接的react组件中,包含以下代码: componentDidMount: function()

我正在使用Facebook的Javascript SDK进行身份验证。我已经能够正确导入SDK,并在我的页面上放置一个Like按钮。但是,facebook登录按钮必须包装在标签中:

<fb:login-button/>

如何让登录按钮进入react?

我已经找到了如何使用react JS修改Facebook登录API教程的方法。我希望这有助于其他正在努力解决这一问题的人

首先,在需要登录链接的react组件中,包含以下代码:

componentDidMount: function() {
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '<YOUR_APP_ID>',
      cookie     : true,  // enable cookies to allow the server to access
                        // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.1' // use version 2.1
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.
    FB.getLoginStatus(function(response) {
      this.statusChangeCallback(response);
    }.bind(this));
  }.bind(this);

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
},

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
testAPI: function() {
  console.log('Welcome!  Fetching your information.... ');
  FB.api('/me', function(response) {
  console.log('Successful login for: ' + response.name);
  document.getElementById('status').innerHTML =
    'Thanks for logging in, ' + response.name + '!';
  });
},

// This is called with the results from from FB.getLoginStatus().
statusChangeCallback: function(response) {
  console.log('statusChangeCallback');
  console.log(response);
  // The response object is returned with a status field that lets the
  // app know the current login status of the person.
  // Full docs on the response object can be found in the documentation
  // for FB.getLoginStatus().
  if (response.status === 'connected') {
    // Logged into your app and Facebook.
    this.testAPI();
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    document.getElementById('status').innerHTML = 'Please log ' +
      'into this app.';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not.
    document.getElementById('status').innerHTML = 'Please log ' +
    'into Facebook.';
  }
},

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
checkLoginState: function() {
  FB.getLoginStatus(function(response) {
    this.statusChangeCallback(response);
  }.bind(this));
},

handleClick: function() {
  FB.login(this.checkLoginState());
},
componentDidMount:function(){
window.fbAsyninit=函数(){
FB.init({
appId:“”,
cookie:true,//启用cookie以允许服务器访问
//会议
xfbml:true,//解析此页面上的社交插件
版本:“v2.1”//使用版本2.1
});
//现在我们已经初始化了JavaScript SDK,我们调用
//getLoginStatus()。此函数用于获取
//访问此页面的人,可以将三种状态之一返回到
//您提供的回调。它们可以是:
//
//1.登录到您的应用程序(“已连接”)
//2.登录Facebook,但不登录你的应用程序(“未授权”)
//3.未登录Facebook,无法判断是否已登录
//你的应用与否。
//
//这三种情况在回调函数中处理。
FB.getLoginStatus(函数(响应){
此.statusChangeCallback(响应);
}.约束(这个);
}.约束(本);
//异步加载SDK
(功能(d、s、id){
var js,fjs=d.getElementsByTagName[0];
if(d.getElementById(id))返回;
js=d.createElement;js.id=id;
js.src=“//connect.facebook.net/en_US/sdk.js”;
fjs.parentNode.insertBefore(js,fjs);
}(文档“脚本”、“facebook jssdk”);
},
//在这里,我们在登录完成后运行一个非常简单的Graph API测试
//成功。请参阅statusChangeCallback()了解何时进行此调用。
testAPI:function(){
log('欢迎!获取您的信息…);
FB.api('/me',函数(响应){
console.log('successfulllogin for:'+response.name);
document.getElementById('status').innerHTML=
'感谢您登录,'+response.name+'!';
});
},
//使用来自FB.getLoginStatus()的结果调用此函数。
statusChangeCallback:函数(响应){
log('statusChangeCallback');
控制台日志(响应);
//响应对象返回的状态字段允许
//应用程序知道此人的当前登录状态。
//响应对象的完整文档可以在文档中找到
//对于FB.getLoginStatus()。
如果(response.status===“已连接”){
//登录你的应用程序和Facebook。
这是testAPI();
}else if(response.status===“未授权”){
//此人已登录Facebook,但未登录您的应用程序。
document.getElementById('status')。innerHTML='Please log'+
“进入此应用程序。”;
}否则{
//此人未登录Facebook,因此我们不确定是否
//他们是否登录到此应用程序。
document.getElementById('status')。innerHTML='Please log'+
“进入Facebook。”;
}
},
//当某人完成登录时调用此函数
//按钮。请参见示例中附加到它的onlogin处理程序
//代码如下。
checkLoginState:function(){
FB.getLoginStatus(函数(响应){
此.statusChangeCallback(响应);
}.约束(这个);
},
handleClick:function(){
FB.login(this.checkLoginState());
},
然后,在渲染方法中,确保有一些HTML将调用该handleClick:

<a href="#" onClick={this.handleClick}>Login</a>


注意,这与教程中的代码相同,但放在ReactJS组件中。唯一的区别是,您必须战略性地绑定它,使Facebook API函数成为react组件的一部分。此登录将以从FB.getLoginStatus()给出的响应解析的响应消息结束。您还可以将令牌从响应对象中取出,并将其发送到后端进行身份验证,例如。

Rittle给出了一个很好的答案,但我将展示我是如何以稍微不同的方式进行验证的。我想使用Facebook的登录按钮而不是我自己的按钮来触发检查登录状态的回调。登录按钮可能如下所示:

<div class="fb-login-button" onlogin="checkLoginState" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>

该按钮有一个onlogin属性,jsx解析器不支持该属性。以react方式使用data onlogin不起作用,因此我只是在componentDidMount中添加了按钮:

        componentWillMount: function () {
                window['statusChangeCallback'] = this.statusChangeCallback;
                window['checkLoginState'] = this.checkLoginState;
        },
        componentDidMount: function () {
            var s = '<div class="fb-login-button" ' +
                'data-scope="public_profile,email" data-size="large" ' +
                'data-show-faces="false" data-auto-logout-link="true" ' +
                'onlogin="checkLoginState"></div>';

            var div = document.getElementById('social-login-button-facebook')
            div.innerHTML = s;
        },
        componentWillUnmount: function () {
            delete window['statusChangeCallback'];
            delete window['checkLoginState'];
        },
        statusChangeCallback: function(response) {
           console.log(response);
        },
        // Callback for Facebook login button
        checkLoginState: function() {
            console.log('checking login state...');
            FB.getLoginStatus(function(response) {
               statusChangeCallback(response);
            });
        },
        render: function() {

            return (
                <div id='social-login-button-facebook'>

                </div>
            );
        }
componentWillMount:function(){
窗口['statusChangeCallback']=this.statusChangeCallback;
窗口['checkLoginState']=this.checkLoginState;
},
componentDidMount:函数(){
var s='';
var div=document.getElementById('social-login-button-facebook')
div.innerHTML=s;
},
componentWillUnmount:函数(){
删除窗口['statusChangeCallback'];
删除窗口['checkLoginState'];
},
statusChangeCallback:函数(响应){
控制台日志(响应);
},
//Facebook登录按钮的回调
checkLoginState:function(){
log('检查登录状态…');
FB.getLoginStatus(函数(响应){
状态更改回调(响应);
});
},
render:function(){
返回(
);
}

如果要自动调用checkLoginState,只需在安装组件时触发按钮。

我编写了一个mixin类来解决这个问题

尝试使用此库:

工作非常简单:

import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';

const responseFacebook = (response) => {
  console.log(response);
}

ReactDOM.render(
  <FacebookLogin
    appId="1088597931155576"
    autoLoad={true}
    callback={responseFacebook} />,
  document.getElementById('demo')
);
从“React”导入React;
从“react dom”导入react dom;
从“反应facebook登录”导入FacebookLogin;
const responseFacebook=(response)=>{
控制台日志(响应
import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';

const responseFacebook = (response) => {
  console.log(response);
}

ReactDOM.render(
  <FacebookLogin
    appId="1088597931155576"
    autoLoad={true}
    callback={responseFacebook} />,
  document.getElementById('demo')
);
const promises = {
    init: () => {
        return new Promise((resolve, reject) => {
            if (typeof FB !== 'undefined') {
                resolve();
            } else {
                window.fbAsyncInit = () => {
                    FB.init({
                        appId      : '<app_id>',
                        cookie     : true, 
                        xfbml      : true,  
                        version    : 'v2.5'
                    });
                    resolve();
                };
                (function(d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id)) return;
                    js = d.createElement(s); js.id = id;
                    js.src = "//connect.facebook.net/en_US/sdk.js";
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));
            }
        });
    },
    checkLoginState: () => {
        return new Promise((resolve, reject) => {
            FB.getLoginStatus((response) => {
                response.status === 'connected' ? resolve(response) : reject(response);
            });
        });
    },
    login: () => {
        return new Promise((resolve, reject) => {
            FB.login((response) => {
                response.status === 'connected' ? resolve(response) : reject(response);
            });
        });
    },
    logout: () => {
        return new Promise((resolve, reject) => {
            FB.logout((response) => {
                response.authResponse ? resolve(response) : reject(response);
            });
        });
    },
    fetch: () => {
        return new Promise((resolve, reject) => {
            FB.api(
                '/me', 
                {fields: 'first_name, last_name, gender'},
                response => response.error ? reject(response) : resolve(response)
            );
        });
    }
}

export const Facebook = {
    doLogin() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({status: response.status}); },
                    promises.login
                )
                .then(
                    promises.fetch,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({loading: false, data: response, status: 'connected'}); },
                    error => { throw error; }
                )
                .catch((error) => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    },
    doLogout() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    promises.logout,
                    error => { this.setState({data: {}, status: 'unknown'}); }
                )
                .then(
                    response => { this.setState({loading: false, data: {}, status: 'unknown'}); },
                    error => { throw error; }
                )
                .catch(error => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    },
    checkStatus() {
        this.setState({
            loading: true
        }, () => {
            promises.init()
                .then(
                    promises.checkLoginState,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({status: response.status}); },
                    error => { throw error; }
                )
                .then(
                    promises.fetchUser,
                    error => { throw error; }
                )
                .then(
                    response => { this.setState({loading: false, data: response, status: 'connected'}); },
                    error => { throw error; }
                )
                .catch((error) => { 
                    this.setState({loading: false, data: {}, status: 'unknown'});
                    console.warn(error); 
                });
        });
    }
};
import {Facebook} from './mixins/Facebook.js';
import {Button} from 'react-bootstrap';

const ProfileHandler = React.createClass({
    mixins: [Facebook],
    componentDidMount() {
        this.checkStatus();
    },
    getInitialState() {
        return {
            status: 'unknown',
            loading: false,
            data: {}
        };
    },
    render() {
        const loading = this.state.loading ? <p>Please wait, profile is loading ...</p> : null;
        const message = this.state.status === 'connected'
            ? (<div>
                Hi {data.name}!
                <Button onClick={this.doLogout}>Logout</Button>
              </div>)
            : (<Button onClick={this.doLogin}>Login</Button>);
        return (
            <div>
                {message}
                {loading}
            </div>
        );
    }
});
<div className="fb-login-button" data-max-row="5" 
     data-size="large" 
     data-show-faces="false" 
     data-auto-logout-link="false" 
     href="javascript:void(0)">Login</div>
componentDidMount: function() {
    // facebook signin  button render
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'replace with your app id here',
        cookie     : true,  // enable cookies to allow the server to access
        // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.1' // use version 2.1
      });

      // login callback implementation goes inside the function() { ... } block
      FB.Event.subscribe('auth.statusChange', function(response) {
        // example implementation
        if (response.authResponse) {
          console.log('Welcome!  Fetching your information.... ');
          FB.api('/me', function(response) {
            console.log('Good to see you, ' + response.name + '.');
          });
        } else {
          console.log('User cancelled login or did not fully authorize.');
        }
      });
    }.bind(this);

    // Load the SDK asynchronously
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }
}
<FbLoginBtn
  width="250"
  dataScope="public_profile,email"
  onSuccess={callback}
  onFailure={optionalCallback}
  afterLogin={optionalCallback}
/>
import React, { Component } from 'react';

class FbLoginBtn extends Component {
  constructor(props) {
    super(props);

    // post login behavior should be defined at a higher level
    this.onSuccess = this.props.onSuccess || (() => {});
    this.onFailure = this.props.onFailure || (() => {});
    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
  }

  componentDidMount() {
    // This is the meat of the component
    // create a script tag, load FB SDK
    // then after script is loaded, set related behavior
    // If you have other components that rely on the FB SDK
    // I recommend extracting this into its own module
    let self = this;
    let scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.src = "http://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4&appId=xxxxx";
    scriptTag.addEventListener('load', function (e) {
      self.FB = window.FB;
      // I don't like exposing the SDK to global scope
      window.FB = null;

      // This subscribe the callback when login status change
      // Full list of events is here
      // https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.9
      self.FB.Event.subscribe('auth.statusChange', self.onStatusChange.bind(self));
    });
    document.body.appendChild(scriptTag);
  }

  onStatusChange(response) {
    if (response.status === 'connected') {
      const { accessToken } = response.authResponse;
      // I have a afterLogin optional callback
      // which takes care of ads landing, invitation or any other custom behavior
      this.onSuccess(accessToken, this.props.afterLogin);
    } else {
      this.onFailure();
    }
  }

  render() {
    return (
      <div 
        className="fb-login-button" 
        data-width={this.props.width}
        data-max-rows="1"
        data-size="large"
        data-button-type="login_with"
        data-show-faces="false"
        data-auto-logout-link="true"
        data-use-continue-as="false"
        data-scope={this.props.dataScope}
      >
      </div>
    );
  }
}

export default FbLoginBtn;
FB.Event.subscribe('auth.statusChange', function(response)
/* global FB*/
import React, { Component } from 'react';
import { Grid, Row, Col } from 'react-bootstrap';

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.checkLoginState = this.checkLoginState.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.testAPI = this.testAPI.bind(this);
    this.statusChangeCallback = this.statusChangeCallback.bind(this);
  }

  componentDidMount() {
    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'YOURAPIKEYHERE',
        cookie     : true,
        xfbml      : true,
        version    : 'v2.8'
      });
      FB.AppEvents.logPageView();
      FB.Event.subscribe('auth.statusChange', function(response) {
        if (response.authResponse) {
          this.checkLoginState();
        } else {
          console.log('---->User cancelled login or did not fully authorize.');
        }
      }.bind(this));
    }.bind(this);

    // Load the SDK asynchronously
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/sdk.js';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  testAPI() {
    console.log('Welcome! Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

  // This is called with the results from from FB.getLoginStatus().
  statusChangeCallback(response) {
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      this.testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
      'into Facebook.';
    }
  }

  checkLoginState() {
    FB.getLoginStatus(function(response) {
      this.statusChangeCallback(response);
    }.bind(this));
  }

  handleClick() {
    FB.login(this.checkLoginState());
  }

  render() {
    return (
      <main>
        <Grid fluid>
            <h1>
              Facebook Login
            </h1>
        </Grid>
        <Grid>
          <Row>
            <Col xs={12}>
              <a href="#" onClick={this.handleClick} onlogin={this.checkLoginState}>Login</a>
              <div id="status"></div>
            </Col>
          </Row>
        </Grid>
      </main>
    );
  }
}
import React, { Component } from 'react';
import './App.css';

import FacebookLogin from 'react-facebook-login';

import GoogleLogin from 'react-google-login';

class App extends Component {

render() {

const responseFacebook = (response) => {
console.log(response);
}

const responseGoogle = (response) => {
console.log(response);
}

return (
<div className="App">
<h1>LOGIN WITH FACEBOOK AND GOOGLE</h1>

<FacebookLogin
appId="" //APP ID NOT CREATED YET
fields="name,email,picture"
callback={responseFacebook}
/>
<br />
<br />

<GoogleLogin
clientId="" //CLIENTID NOT CREATED YET
buttonText="LOGIN WITH GOOGLE"
onSuccess={responseGoogle}
onFailure={responseGoogle}
/>

</div>
);
}
}

export default App;
import { useState, useEffect, useCallback } from 'react';

const initializeFb = () =>
  // eslint-disable-next-line no-unused-vars
  new Promise((resolve, _reject) => {
    if (typeof FB !== 'undefined') {
      resolve();
    } else {
      // eslint-disable-next-line func-names
      window.fbAsyncInit = function() {
        // eslint-disable-next-line no-undef
        FB.init({
          appId: 'APP ID HERE',
          cookie: true,
          xfbml: true,
          version: 'v2.8',
        });
        // eslint-disable-next-line no-undef
        FB.AppEvents.logPageView();
        resolve();
      };

      // eslint-disable-next-line func-names
      (function(d, s, id) {
        let js;
        const fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
          return;
        }
        // eslint-disable-next-line prefer-const
        js = d.createElement(s);
        js.id = id;
        js.src = 'https://connect.facebook.net/en_US/sdk.js';
        fjs.parentNode.insertBefore(js, fjs);
      })(document, 'script', 'facebook-jssdk');
    }
  });

const useFacebook = () => {
  const [fb, setFB] = useState([]);
  const [isReady, setReady] = useState(false);

  const initFacebook = useCallback(async () => {
    await initializeFb();
    // eslint-disable-next-line no-undef
    if (typeof FB !== 'undefined') {
      // eslint-disable-next-line no-undef
      setFB(FB);
      setReady(true);
    }
  });

  useEffect(() => {
    initFacebook();
  }, [initFacebook]);

  return [fb, isReady];
};

export default useFacebook;
const Login= ()=>{
    const [FBInstance, isReady] = useFacebook();
    return (<Button onClick()=>{
      FBInstance.getLoginStatus(resp=>{  console.log(resp) })
   }></Button>)
}