AngularJS + OAuth 1.0


OAuth callout is very simple and easy with AngularJS.
Here i just used a simple Yelp Api integration example . You can change this as per your requirment.

We need to construct a signature "base string", which consists of a concatenation of three request elements:
1. The HTTP request method.
2. The base URL the request is being sent to.
3. A normalized string of the parameters in the request.

and generate an oauth_signature using HMAC-SHA1 method.


Js code:
var app = angular.module('MyApp', []);

app.controller('MainCtrl', ['$scope', 'MyYelpAPI', function($scope, MyYelpAPI) {
$scope.businesses = [];
MyYelpAPI.retrieveYelp('', function(data) {
$scope.businesses = data.businesses;
    });

}]).factory("MyYelpAPI", function($http) {
return {
"retrieveYelp": function(name, callback) {
var method = 'GET';
var url = 'http://api.yelp.com/v2/search';
var params = {
callback: 'angular.callbacks._0',
location: 'San+Francisco',
oauth_consumer_key: 'xxxxxxxxxxxxxxxx', //Consumer Key
oauth_token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', //Token
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: new Date().getTime(),
oauth_nonce: randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
term: 'Restaurants'
};
var consumerSecret = '_wkOfBWAlsQK6kUPcDw_MXC8sMM'; //Consumer Secret
var tokenSecret = 'uEqyN4F3GLKEOTAEgNAlyugh1iI'; //Token Secret
var signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, { encodeSignature: false});
params['oauth_signature'] = signature;
$http.jsonp(url, {params: params}).success(callback);
}
}
});

function randomString(length, chars) {
     var result = '';
     for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
                return result;
}



Html code:
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
        <script type="text/javascript"  src="oauth-signature.min.js"></script>
    </head>
    <body ng-app="plunker">
        <div  ng-controller="MainCtrl">
            <ul>
                <li data-ng-repeat="business in businesses">
                    {{business.name}}
                </li>
            </ul>
        </div>
    </body>
</html>

No comments:

Post a Comment