2jq4ua
Last Updated: October 10, 2018
·
278
· Khor

Using OAuth to Post A Tweet on Twitter

Purpose

The simplest Javascript step-by-step guide with full working code (< 15 lines) to use OAuth to post a tweet on behalf of a Twitter user through OAuth.io

Full Code to Use OAuth to Post Tweet on Twitter

Here is the final code - a Javascript snippet that you can tweak, and play around with instantly without any coding, configuration, etc.

https://jsfiddle.net/L6t27c94

Details of each part of the code:

HTML

<a id="twitter-button" class="btn btn-block btn-social btn-twitter">
  <i class="fa fa-twitter"></i> Post a Tweet on Twitter
</a>

CSS

None

Javascript

$('#twitter-button').on('click', function() {
  // Initialize with your OAuth.io app public key
  OAuth.initialize({Your OAuth.io App Key});
  // Use popup for OAuth
  OAuth.popup('twitter').then(twitter => {
    // OAuth.io Twitter object
    console.log('twitter:', twitter);

    // Use OAuth.io Twitter object to post a tweet
    twitter.post({
      url: "/1.1/statuses/update.json?status=Some%20random%20Tweet"
    }).then(tweet => {
      console.log('Created Tweet:', tweet);
    }); 
  });
})

External Requirements

This Javascript snippet relies on a few libraries:

Step-by-step Guide

Here is a summary of the steps to create this social button to post a Tweet on Twitter on a user's behalf using OAuth2.

  1. Create a Twitter account, if you do not have one
  2. Create an app on Twitter using this simple step-by-step guide
  3. Copy your Twitter app client id and client secret
  4. Signup for OAuth.io account
  5. Link your Twitter app with OAuth.io by pasting your Twitter app client id and client secret into OAuth.io
  6. Copy the OAuth javascript snippet (https://jsfiddle.net/L6t27c94) on to your web page

References

Use OAuth to Post Tweet on Twitter - https://tome.oauth.io/providers/twitter/post-a-tweet