Get Facebook access_token

2Nov11

I’m going to try to document the experience of creating an access_token so my app. can post messages on my Facebook Page. As a summary, I have the following elements:

1) Facebook Page

This is the Doonish Facebook Page. It’s a page that describes the project and that try to get as many fans as possible.

2) Facebook Application

In the other side I’ve created an application for allowing the remote post to my page. This is application that will do that.

What I want to do is promote each day a new question from doonish into my Doonish Facebook Page.

 

How to automatically post in a Facebook Page?

1) Get application “access_token”

The first step is to get application “token_id” so we can post to the Facebook Page.

https://www.facebook.com/dialog/oauth?
    client_id={facebook-app-id}&
    redirect_uri={your-url}&
    scope=manage_pages&
    response_type=token

That will return with something like the following:

access_token={your-access-token}

2) Find the page “access_token”

Then, using the above token, you can go to the following location:

https://graph.facebook.com/me/accounts?
    access_token={your-access-token}

And you will see something like the following:

{
    "data": [
    {
        "name": "{your-page}",
        "access_token": "{page-token-id}",
        "category": "Website",
        "id": "{page-id}"
    },
    ...
    ]
}

3) Write the actual script

Whith the above “page-token-id” you can then write a PHP snippet that can do something like the following:

/**
 * Promote
 *
 * This method will automatically post a message on the facebook wall.
 *
 * @param integer $questionId The id of the question that we want to 
 *     promte.
 */
public function promote($questionId)
{
    $message = $this->generateMessage($questionId);
 
    $facebook = new Facebook(
        array(
            'appId'  => $this->facebookConfig['app_id'],
            'secret' => $this->facebookConfig['secret'],
            'scope'  => $this->facebookConfig['scope'],
            'cookie' => $this->facebookConfig['cookie'],
            'acceptUrl' => $this->facebookConfig['acceptUrl']
        )
    );
 
    $status = $facebook->api(
        '/' . $this->facebookConfig['page_id'] .'/feed',
        'post',
        array(
            'access_token' => $this->facebookConfig['token_id'],
            'message' => $message,
            'cb' => ','
        )
    );
}

Hope this code is useful for someone, it took me a while to figure out the right way to do it. I’ve used Facebook PHP SDK and I’ve got all the information from the Authentication page from Facebook Developers.

No comments yet.

Write a comment: