Goal
Provide the easiest way (less than 15 lines of code) to use OAuth to share a post or link on a LinkedIn account on behalf of a LinkedIn user using Javascript.
Code Example
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/fyLc6kj8/2/
Code Explanation:
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('HwAr2OtSxRgEEnO2-JnYjsuA3tc');
// Use popup for OAuth
OAuth.popup('twitter').then(twitter => {
//Twitter provider object
alert('You can check Twitter provider object in the console!');
console.log('twitter:', twitter);
twitter.post({
url:"/1.1/statuses/update.jsonstatus=Some%20random%20Tweet"
}).then(tweet => {
alert('You can find created Tweet in both console and your Twitter account!');
console.log('Created Tweet:', tweet);
});
});
})
External Requirements
This Javascript code has external requirements:
- jQuery - HTML element manipulation
- bootstrap, font-awesome - Look-and-feel of social buttons and icons
- oauth-io javascript library - Simplifies OAuth usage by hiding the nuances in the OAuth implementation of various OAuth providers, e.g., LinkedIn, Twitter, etc. behind the ratified standard OAuth2 interface
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:
- Create a Twitter account, if you do not have one
- Create an app on Twitter using this simple step-by-step guide
- Copy your Twitter app client id and client secret
- Signup for OAuth.io account
- Link your Twitter app with OAuth.io by pasting your Twitter app client id and client secret into OAuth.io
- Copy the OAuth javascript snippet (https://jsfiddle.net/fyLc6kj8/2/) on to your web page