php facebook sdk不会在wordpress中创建用户 [英] php facebook sdk doesn't create the user in wordpress

查看:57
本文介绍了php facebook sdk不会在wordpress中创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑问题:

我试图使用这个sdk

当我点击facebook按钮登录或注册时,它会通过facebook打开一个小窗口,显示继续但是之后它不会在wordpress数据库中创建用户并打破wordpress页脚,因此它显示必须使用活动访问令牌来查询有关当前用户的信息。页面刷新后登录表单下的消息。

When I click on the facebook button to login or register it opens a small window via facebook that says continue but after than it doesnt create the user in wordpress database and breaking the wordpress footer, so it shows An active access token must be used to query information about the current user. messagge under the login form after the page refresh.

我的完整facebook登录php代码是这一个:

My full facebook login php code is this one:

    <?php 
    include 'facebook/facebook.php';
    function gazi_fb_loginForm(){

            gazi_fb_error_message();

            gazi_fb_LoadScript();

            if(is_user_logged_in()==false){

            ?>

                <div class="facebook_wrapper">
                <img src="<?php echo plugin_dir_url(__FILE__).'images/facebook_or.png';?>" style="border:none; box-shadow:none;">
                <br>
                <a href="javascript:void(0)" onClick="FBLogin();">

                <img src="<?php echo plugin_dir_url(__FILE__).'images/facebook_button.png';?>" alt="Fb Connect" title="Login with facebook" /></a></div>

            <?php 

            } 

        }



    function gazi_fb_LoadScript(){

         global $wpdb;

         $gazi_option=$wpdb->prefix."gazi_option";

         $path =  plugin_dir_url(__FILE__);  // define path to link and scripts

        $pageURL = get_permalink();

        $sign = strpos($pageURL,'?')?'&':'?';

         //facebook app secret

    $qry1="SELECT value FROM $gazi_option WHERE fieldname='gazi_facebook_app_secret'";

    $facebook_app_secret = $wpdb->get_var($qry1);

    $qry2="SELECT value FROM $gazi_option WHERE fieldname='gazi_facebook_app_id'";

    $facebook_app_id = $wpdb->get_var($qry2);



         $facebook = new Facebook(array(

            'appId'     =>  $facebook_app_id,

            'secret'    => $facebook_app_secret,

            ));

        ?>

        <script type="text/javascript">
window.fbAsyncInit = function() {
 FB.init({
      appId      : '<?php echo $facebook_app_id; ?>',
      xfbml      : true,
        status     : true, 
       cookie     : true,
      version    : 'v2.1'
 });


FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            console.log('Logged in.');
}
          else {
            console.log('initiate FB login...');
            FB.login();
          }
});

FB.api('/me/feed',function(response){
           var idDiv=document.getElementById('result');
           idDiv.textContent=JSON.stringify(response);
  }); 
};

(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

function FBLogin(){
    FB.login(function(response){
        if(response.authResponse){
            window.location.href = "<?php echo $pageURL.$sign;?>option=fblogin";
        }
    }, {scope: 'email'});
}

    </script>

        <?php

        }



    function gazi_fb_error_message(){

            if(isset($_SESSION['msg'])){

                echo '<div class="'.$_SESSION['msg_class'].'">'.$_SESSION['msg'].'</div>';

                unset($_SESSION['msg']);

                unset($_SESSION['msg_class']);

            }

        }



    function gazi_fb_login_validate(){



        $path =  plugin_dir_url(__FILE__);  // define path to link and scripts

        $pageURL = get_permalink();

        $sign = strpos($pageURL,'?')?'&':'?';



        if(isset($_REQUEST['option']) && $_REQUEST['option']  == "fblogin"){

         global $wpdb;

         $gazi_option=$wpdb->prefix."gazi_option";

         //facebook app secret

          $qry1="SELECT value FROM $gazi_option WHERE fieldname='gazi_facebook_app_secret'";

          $facebook_app_secret = $wpdb->get_var($qry1);

          $qry2="SELECT value FROM $gazi_option WHERE fieldname='gazi_facebook_app_id'";

          $facebook_app_id = $wpdb->get_var($qry2);

            $facebook   = new Facebook(array(

                'appId' => $facebook_app_id,

                'secret' => $facebook_app_secret,

                'cookie' => TRUE,

            ));

            $fbuser = $facebook->getUser();

            if ($fbuser) {

                try {

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

                }

                catch (Exception $e) {

                    echo $e->getMessage();

                    exit();

                }

                if (!isset($user_profile['email'])) $user_profile['email'] = $user_profile['id'] . '@facebook.com';

                $user_fbid  = $fbuser;

                $user_email = $user_profile["email"];

                $user_fnmae = $user_profile["first_name"];



              if( email_exists( $user_email )) { // user is a member 

                  $user = get_user_by('login', $user_email );

                  $user_id = $user->ID;


                  wp_set_auth_cookie( $user_id, true );

               } else { // this user is a guest

                  $random_password = wp_generate_password( 10, false );

                  $user_id = wp_create_user( $user_email, $random_password, $user_email );

                  update_user_meta($user_id, 'avtar_image', 'https://graph.facebook.com/' . $user_profile['id'] . '/picture?type=large');

                  wp_update_user(array(

                              'ID' => $user_id,

                              'display_name' => $user_profile['name'],

                              'first_name' => $user_profile['first_name'],

                              'last_name' => $user_profile['last_name']

                            ));

                  wp_set_auth_cookie( $user_id, true );

               }



                wp_redirect( $pageURL.$sign.'login4=1');

                exit;



            }       

        }

    }

    ?>

这是上面代码中的javascript。

here is the javascript in above code.

    <script type="text/javascript">

window.fbAsyncInit = function() {
 FB.init({
      appId      : '<?php echo $facebook_app_id; ?>',
      xfbml      : true,
        status     : true, 
       cookie     : true,
      version    : 'v2.1'
 });


FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            console.log('Logged in.');
}
          else {
            console.log('initiate FB login...');
            FB.login();
          }
});

FB.api('/me/feed',function(response){
           var idDiv=document.getElementById('result');
           idDiv.textContent=JSON.stringify(response);
  }); 
};

(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

function FBLogin(){
    FB.login(function(response){
        if(response.authResponse){
            window.location.href = "<?php echo $pageURL.$sign;?>option=fblogin";
        }
    }, {scope: 'email'});
}

        </script>

有没有人知道如何使它工作?我做错了什么?非常感谢任何帮助。

Does any one know how ti make it working? What Im doing wrong?Any help is very appreciated.

谢谢你。

更新:

我使用此答案更改了文件中的一些行 here

I have changed some lines in my file using this answer here

改变了这个:
$ fbuser = $ facebook-> getUser();

Changed this: $fbuser = $facebook->getUser();

            if ($fbuser) {

                try {

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

                }

                catch (Exception $e) {

                    echo $e->getMessage();

                    exit();

                }

到这一个:

$fbuser = $facebook->getUser();

$photo_details = array('message' => 'my place');
$file='photos/my.jpg'; //Example image file
$photo_details['image'] = '@' . realpath($file);

if ($fbuser) {
  try {
    // We have a valid FB session, so we can use 'me'
    $upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
  } catch (FacebookApiException $e) {
    error_log($e);
  }

我现在注册了,但很奇怪

I got registered now but its very strange

wordpress的用户名和昵称是allways @facebook:D

the username and nick name of wordpress is allways @facebook :D

所以我认为它没有得到变量:

So I think its not getting the variables here:

if (!isset($user_profile['email'])) $user_profile['email'] = $user_profile['id'] . '@facebook.com'; and just keeping @facebook instead without the `$user_profile['id']`


推荐答案

请在下面找到示例代码。我已经使用JavaScript SDK进行登录,并使用PHP SDK生成访问令牌。我希望它适合你。

Please find the sample code below. I have made the use of JavaScript SDK for the login and PHP SDK for generating access-token. I hope it will work for you.

** HTML Code :: **

** HTML Code:: **

    <html>

    <body>

  <p><a href="#" onClick="logInWithFacebook()">Log In with the JavaScript SDK</a></p>

  <script>
    logInWithFacebook = function() {
      FB.login(function(response) {
        if (response.authResponse) {
          alert('You are logged in &amp; cookie set!');
          location.href = "//localhost/facebook/testfb.php"
            // Now you can redirect the user or do an AJAX request to
            // a PHP script that grabs the signed request from the cookie.
        } else {
          alert('User cancelled login or did not fully authorize.');
        }
      });
      return false;
    };
    window.fbAsyncInit = function() {
      FB.init({
        appId: 'app-id',
        cookie: true, // This is important, it's not enabled by default
        version: 'v2.9'
      });
    };

    (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'));
  </script>
</body>

</html>

** PHP代码**

** PHP Code **

<?php
require_once('Facebook/autoload.php');
# /js-login.php
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.9',
]);

$helper = $fb->getJavaScriptHelper();


try {
    $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}


if (!isset($accessToken)) {
    echo 'No cookie set or no OAuth data could be obtained from cookie.';
    exit;
}



// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);


// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId('{app-id}'); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
    exit;
  }

  echo '<h3>Long-lived</h3>';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name,email', $accessToken->getValue());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];
echo 'Email: ' . $user['email'];

?>

这篇关于php facebook sdk不会在wordpress中创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆