Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Set Up Efficient Autoposting to Facebook and Twitter

DZone's Guide to

How to Set Up Efficient Autoposting to Facebook and Twitter

Read on to learn how to use Facebook and Twitter's developer tools and APIs to create your own user friendly, autoposting functionality.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Image title

Both beginner and time-hardened entrepreneurs understand the importance of efficient website management. They expect their sites to be powerful tools that attract, convert, close, and delight customers. On top of this, they don’t want to spend tons of their precious time on such routine tasks as content posting and sharing and seek to automate website management processes as much as possible.

In this article, I would like to share a step-by-step process for setting up autoposting to Facebook and Twitter using carvoy.com as an example. The process I describe allows business owners to automatically share a site’s content to social pages and display it directly to a business’ targeted audiences.

Autoposting to Facebook

Your first step will be to register your app. We need the app to publish posts from your website straight into the page’s feed. To do that, access https://developers.facebook.com/apps and add the Facebook application. Here is how:

Carvoy App ID

The process is fairly simple: Press ”Create a New App,” fill in all the necessary data (e.g. name, email, category) and select category “Apps for Pages.” Then, click on the “Create App ID” button and solve the captcha. This is it — your Facebook app is up and running.

Image title

To proceed, we have to receive the following parameters:

  1. APP ID

  2. APP SECRET

The screenshot below demonstrates where you can find these parameters:

Image titleHaving this data on your hands, you should get an access token for the app. It will allow you to become the admin of the page. This token will also be used to publish content from your website. Check out the Facebook for developers page to learn how to get an access token for your app.

After that, all you need to do is to open this URL in the browser:

https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=<APP_ID>&client_secret=<APP_SECRET>

This query will return the access token we are going to use to post content. Following that, you need to enable content republishing on your Facebook page. Use the query below:

https://www.facebook.com/dialog/oauth?client_id=<APP_ID>&client_secret=<APP_SECRET>&redirect_uri=https://carvoy.com&scope=publish_actions&response_type=token   

To post content on your Facebook page, send HTTP request POST to the following URL:

https://graph.facebook.com/<PAGE_ID>/feed

Here you will have to provide a post’s message link, an image’s link, and a post’s link, its headline, and description. Keep in mind that you need to send parameters of your access token as well.

To learn PAGE_ID of a particular page you are going to post content to, you should tweak its URL a bit: Just replace www with graph and add your access token using the get parameter. The example below demonstrates the URL that is used to receive ID:

https://graph.facebook.com/Carvoy/?access_token=326799827727254|aRtZuU48IqeJ0s8SY6sVOIfPAiA

In return, you are going to receive a JSON object that contains ID of that page, like this:

{
   "name": "Carvoy",
   "id": "1629966630552080"
}

In our case, the autoposting feature is developed as a module - autoposting - in which an individual behavior class is created. I will use it in the Lease model and then run the event when posts are added (listed). When the module is on, you can reuse, supply, and tweak it.

The files featured in the module have the following structure:

…
autoposting
-- behaviors
-- -- AutopostingBehavior.php
-- Module.php
…

The modules/autoposting/Module.php file is a standard initialization of the module. Meanwhile, modules/autoposting/behaviors/AutopostingBehavior.php is a description of the behavior used when a new post is added to the site. The code looks like this:

<?php

namespace modules\autoposting\behaviors;

use Yii;
use yii\base\Behavior;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\helpers\Url;
use Abraham\TwitterOAuth\TwitterOAuth;

/**
 * Class AutopostingBehavior
 * @package modules\autoposting\behaviors
 */
class AutopostingBehavior extends Behavior {

    /**
     * @return array
     */
    public function events() {

        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'postToWall',
        ];
    }

    /**
     * @param \yii\base\Event $event
     *
     * @throws Exception
     */
   public function postToWall( $event ) {

        $model    = $event->sender;

        if ($model) {
            $link = Url::to(['/lease/lease/view', 'state'=>$model->state, 'node'=>$model->url ], true);
            $message = "New listing available on our site - $model->make $model->model $model->year in $model->location. \n" . $link;
            $this->facebookPost([
                'message'     => $message,
                'link'        => $link,
                // 'picture'     => 'http://thepicturetoinclude.jpg', // link to vehicle picture
                // 'name'        => 'Name of the picture, shown just above it',
                // 'description' => 'Full description explaining whether the header or the picture'
            ]);
            $this->twitterPost($message);
        }

    }

    private function facebookPost ($data)
    {
        // need token
        $data['access_token'] = '326799827727254|aRtZuU48IqeJ0s8SY6sVOIfPAiA';

        $page_id = ‘1629966630552080’;
        $post_url = 'https://graph.facebook.com/'.$page_id.'/feed';

        // init
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $post_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // execute and close
        $return = curl_exec($ch);
        curl_close($ch);
        // end
        return $return;
    }

    private function twitterPost ($message)
    {

    }

}

Your next step is to introduce the class that regulates autoposting behavior into the array featuring behavior of the following model:

/modules/lease/models/frontend/Lease.php

...
   /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestampBehavior' => [
                'class' => yii\behaviors\TimestampBehavior::className(),
            ],
            \modules\autoposting\behaviors\AutopostingBehavior::className(),  // Autoposting behavior
        ];
    }
...

To begin with, let’s add TimestampBehavior. Using this behavior, you will be able to fill out the fields of created_at  or updated_at models when a new post is created or updated. Now, when a new listing in AutopostingBehavior class is created, the postToWall method will be activated. It will send requests to publish content into social networks, which can be seen in the AutopostingBehavior class in the code below:

...
ActiveRecord::EVENT_AFTER_INSERT => 'postToWall',
...

Autoposting to Twitter

Now that we are done with Facebook, let’s talk a bit about autoposting to Twitter. I strongly advise you to utilize the power of the most popular PHP library to work with Twitter — Twitter OAuth REST API (here twitteroauth).

To begin with, you need to install the library with a composer, like this:

php composer.phar require abraham/twitteroauth 

To use the Twitter API, you need to register your application: Click https://apps.twitter.com/, log in using your login and password, and press  "Create New App" button. Then, fill out the form and click on the “Create your Twitter application” button.

Now, you can tweak the settings of your newly created app. Pay specific attention to Access level — you should select “Read and write.”

After that, access the "Keys and Access Tokens" tab and press on the app. Your job is to find the following keys:

  • Consumer Key

  • Consumer Secret

Scroll down the page and click the "Create my access token" button. This will help you get access to two additional keys:

  • Access Token

  • Access Token Secret

Now that you have all the keys, everything is pretty simple. You need to develop the twitterPost method using the TwitterOAuth class with the keys to access Twitter.

...
private function twitterPost ($message)
    {

        $CONSUMER_KEY    = 'XYNpO5yj0shMgH43j4lYKMDfH';
        $CONSUMER_SECRET = 'VevyEwrhHxabcQgN2S0KuL1i9Gx9CnPXyM2yVLfQ0LlJSZ7BmF';
        $OAUTH_TOKEN     = '3432829204-6IS6o3hGW3xouvgCso279o4ODU15grLLUy0iWPX';
        $OAUTH_SECRET    = 'vGzYOtJkcx8PK96YcyUdXM6PtqmhGiVLmHOqCDHM2lkIq';


        $connection = new \Abraham\TwitterOAuth\TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $OAUTH_TOKEN, $OAUTH_SECRET);

        $statues = $connection->post("statuses/update", array("status" => $message));

        return $connection->getLastHttpCode() == 200;

    }
...

As you see, setting up the autoposting process to Facebook and Twitter is fairly easy. The integration code samples are displayed below, and you can do everything you want with them: refine them or move the integration with every social network into a separate class.

Such parameters as access_token and page_id for Facebook, as well as Consumer Key, Consumer Secret, Access Token, and Access Token Secret for Twitter can be easily moved to the configuration file of the application in common\config\params.php file.

return [
    'adminEmail' => 'admin@example.com',
    'supportEmail' => 'support@example.com',
    'user.passwordResetTokenExpire' => 3600,
    'autoposting' => [
        'twitter' => [
            'consumer_key'    => "XYNpO5yj0shMgH43j4lYKMDfH",
            'consumer_secret' => "VevyEwrhHxabcQgN2S0KuL1i9Gx9CnPXyM2yVLfQ0LlJSZ7BmF",
            'oauth_token'     => "3432829204-6IS6o3hGW3xouvgCso279o4ODU15grLLUy0iWPX",
            'oauth_secret'    => "vGzYOtJkcx8PK96YcyUdXM6PtqmhGiVLmHOqCDHM2lkIq",
        ],
        'facebook' => [
            'page_id' => '1629966630552080',
            'page_access_token' => '326799827727254|aRtZuU48IqeJ0s8SY6sVOIfPAiA'
        ]
    ]
];

Applying the line of code below, you can get easy access to these parameters using params property of your application:

$data['access_token'] = Yii::$app->params['autoposting']['facebook']['page_access_token'];

I would like to point out these: (a) create request queues to send requests to social networks; (b) avoid generating synchronous requests to publish content.

I don’t recommend working with synchronous requests because users will have to wait while requests are processed and publication to social networks is completed. Only after that users will receive feedback that posting is successfully completed. This can take a lot of time, which is bad from a usability perspective. Request queues are more efficient.

To put that request queue in place, rely on the following extension: https://github.com/zhuravljov/yii2-queue.

It will allow you to publish content to social networks in the background, making sure that your usability is impeccable.

Please, check out the code in this GitHub repository

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
web dev ,facebook api ,twitter api ,web application development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}