Search code examples
facebookfacebook-graph-apifacebook-javascript-sdkfacebook-access-token

How to share with access token?


I have write this code but it does work only if I am already logged in facebook, otherwise appears a popup window that require me email and password to login in facebook.

This is the code:

window.fbAsyncInit = function () {
    FB.init({
        appId: 'xxx',
        frictionlessRequests: true,
        status: true,
        cookie: true,
        xfbml: true,
        oauth: true
    });

    function update(response) {
        if (response.authResponse) {
            FB.api('/me', function (info) {
                login(response, info);
            });

        } else {

        }
    }

    FB.getLoginStatus(update);
};
(function () {
    var e = document.createElement('script');
    e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
}());


function login(response, info) {
    if (response.authResponse) {
        publish();
    }
}

function publish() {
    var publish = {
        method: 'feed',
        access_token: '<?php echo $token; ?>',
        message: 'How are you ?',
        name: 'hi friends',
        caption: 'yuhuuuuuuuu',
        description: (' '),
        link: 'http://www.example.com',
        picture: 'http://cdn1.hark.com/images/000/004/514/4514/original.jpg',
        actions: [{
            name: 'Hello',
            link: 'http://www.example.com/'
        }],
        user_message_prompt: 'Share on facebook'
    };

    FB.ui(
    publish, function (response) {
        if (response && response.post_id) {
            alert('Post was published.');

        } else {
            alert('Post was not published.');
        }
    });
}

Solution

  • In your update method, in the blank else you should call the FB.login method:

    Calling FB.login prompts the user to authenticate your application using the OAuth Dialog.

    However, you can't just do this:

    function update(response) {
        if (response.authResponse) {
            FB.api('/me', function (info) {
            login(response, info);
            });
    
        } else {
            FB.login(function(response) {
                if (response.authResponse) {
                    console.log("user is logged in!", response.authResponse);
                }
            });
        }
    }
    

    Since as it states in the documentation:

    Calling FB.login results in the JS SDK attempting to open a popup window. As such, this method should only be called after a user click event, otherwise the popup window will be blocked by most browsers.

    You'll have to show a user a button or something that tells him to click in order to login, and then you can call the FB.login method.