Yelp API and AngularJS

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

I'm trying to call the Yelp API using AngularJS, but I'm having trouble. I keep getting a 400 bad request and I don't know why.

Yelp API documentation:

http://www.yelp.com/developers/documentation/v2/authentication http://www.yelp.com/developers/documentation/v2/search_api

Page containing Yelp API generated keys:

http://gyazo.com/fa918329eb0cde18a5db242d1d0b0b0e

This is the snippet of my code doing the call:

function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; }  app.factory("MyYelpAPI", function($http) { return {     "retrieveYelp": function(name, callback) {         $http.jsonp("http://api.yelp.com/v2/search?term=food&location=San+Francisco&callback=JSON_CALLBACK",             {                 params: {                     oauth_consumer_key: /* Consumer Key */,                     oauth_token: /* Token */,                     oauth_signature_method: "hmac-sha1",                     oauth_signature: /* Token Secret */,                     oauth_timestamp: new Date().getTime(),                     oauth_nonce: randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')                 }             }         ).success(callback);     } } }); 

回答1:

Yelp API returns very informative error message you can find in response body. I have made 3 steps to make request work:

  1. Changed "hmac-sha1" to "HMAC-SHA1". Documentation says hmac-sha1 but it's wrong.

  2. oauth_signature is not the same as Token Secret. You need to generate oauth_signature for each request separately. I used this library https://github.com/bettiolo/oauth-signature-js

  3. AngularJS sends hardcoded callback parameter to server so we need to hardcode it in parameters list too. Otherwise our signature is incorrect.

My code:

               

  • {{business.name}}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!