📜 ⬆️ ⬇️

How to quickly set up autoposting for Facebook and Twitter



Hello dear readers!

The need to perform work with the site as quickly and efficiently as possible is for everyone, both successful and novice entrepreneurs. The desire to automate the process is expressed not only in the easy filling of the site with content, but also in the fastest informing the target audience about the appearance of new content.
')
In this article I want to show you a simple way of posting information (for example, articles or pages of a site) on social networks with a minimum of effort. Imagine that you are adding content to the site, or the users of your site publish ads (just as it was done by our team working on the site carvoy.com ), and information about adding new content appears on your pages on social networks. This method is effective in that it delivers information directly to the target audience.

Facebook autoposting


I propose to start with the practical part of this process. First, let's deal with autoposting on Facebook when adding ads. According to the documentation for Facebook, we need to register the application in order to use it to post messages on the wall. Go to the special developer page https://developers.facebook.com/apps and add the Facebook app.



Everything is very simple here: press the button “Create a New App”, enter information about your application (name, contact email, select the category “Apps for Pages”) and, finally, after clicking on the button “Create App ID” and entering the test captcha an application is created.



For further work, you will need the following parameters:
APP ID and APP SECRET



With this data, we need to get an access token for this application, which will allow us to act on behalf of the page administrator. This token will later be used for publication. How to get access token is described in detail in the facebook for developers documentation. All we need is to open the following link in the browser:

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

This request will return an access token that we can use to publish. Next, set the permission to publish the following request:

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 to your Facebook social wall, we’ll need to send an HTTP POST request to the following URL:
https://graph.facebook.com/<PAGE_ID>/feed

Next, we need to provide a message, a link to the image, a link to the page of the advertisement that we just added, a title, a description, without forgetting to send our access token parameter, which we have just received.

To find out the PAGE_ID of the page, on the wall of which you are going to publish the record, just change to the graph in the full address of the www page and add the get access parameter to get. Here, for example, a link to get the ID of the page I need.

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

In response, we get a JSON object that contains the ID of this page. Like this:

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

Autoposting is implemented as an autoposting module, in which a behavior class is created. I'll use it in the Lease model and then handle the event when adding an ad (listing). Then this module can be reused, supplemented and modified.

Module file structure:

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

In the modules / autoposting / Module.php file, the standard module initialization. And in the modules / autoposting / codes / AutopostingBehavior.php file - the behavior description when adding a new record:

 <?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) { } } 

I will describe the twitterPost method a little later when we finish posting to the Fecebook and go to autoposting on Twitter.

Add an autoposting behavior class to an array with model behaviors
/modules/lease/models/frontend/Lease.php

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

Immediately add the TimestampBehavior behavior. With his help, the fields of the created_at or updated_at model are filled in during the creation or update of the record. Now, when creating a new listing in the class, AutopostingBehavior will work out the postToWall method, in which requests for publishing to social networks will be sent. This is defined by the following line in the AutopostingBehavior class:

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

Twitter autoposting


For posting on Twitter we will use the most popular PHP library for working with Twitter OAuth REST API - twitteroauth .

Install it using composer. We just need to run the following command:

php composer.phar require abraham/twitteroauth

To use the Twitter API, you also need to register your application. To do this, follow the link https://apps.twitter.com/ with your username and password and click on the button "Create New App". Then fill out the form and click “Create your Twitter application”.

We fall into the settings of the newly created application. Here you need to make sure that “Read and write” is selected in the Access level.

Go to the tab "Keys and Access Tokens", and then click on the name of the newly created application. On this tab, we take 4 keys to work with our application:

Consumer Key
Consumer Secret

Scroll the page below and see the button "Create my access token"; after clicking on it we get the missing pair of keys:

Access Token
Access Token Secret


Further steps are very simple. We implement the twitterPost method. To do this, you need to use the TwitterOAuth class with 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; } ... 

So, in just a few steps, we organized autoposting on two popular social networks. Naturally, the integration code is presented for informational purposes for demonstration; it can be improved and integration with each social network into a separate class.

Parameters such as access_token and page_id for Facebook, as well as Consumer Key, Consumer Secret, Access Token, Access Token Secret for Twitter can be transferred to the application configuration file in the common \ config \ params.php file.

 <?php 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' ] ] ]; 

Now you can access these parameters through the params property of the application instance:

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

I will note separately that it is necessary to organize a queue at the working project for sending requests to social networks, and not to make simultaneous requests for publication. This is due to the fact that the user, when publishing an ad on the site with this approach, will wait for the execution of requests for publication on social networks and only after they have been completed will receive feedback about the successful addition of his ad to the site. This may take a long time, although the moment of publication in social networks should not adversely affect usability.

To organize this kind of queue, so that the publication in social networks takes place in the background and does not increase the time the user has added an ad to the site, the best for me will help us, in my opinion, the extension for queuing https://github.com/zhuravljov/yii2- queue

All the code described in this and previous articles is available to you in the repository .

Thanks for attention!

The article was prepared by: greebn9k (Sergey Gribnyak), pavel-berezhnoy (Pavel Berezhnoy), silmarilion (Andrey Khakharev)

Source: https://habr.com/ru/post/329196/


All Articles