Snippets

OJ Unity3D - Yelp API and Oauth1a

Created by OJ
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Security.Cryptography;
using SimpleJSON;
using System.IO;
using System.Text;
using System.Globalization;
using SimpleJSON;
//Script was modified/updated by OJ3D - 11/8/2015
//The original script was develolped by Steve Yaus/gambitforhire for twitter API
//https://bitbucket.org/gambitforhire/twitter-search-with-unity/src/bfc5cf8a401f12921c3c4f2355bf3315411d9f13/Assets/Scripts/TwitterAPI.cs?at=master&fileviewer=file-view-default#TwitterAPI.cs-151

public class Yelp_BasicSearch_Oauth1a : MonoBehaviour{

	//Yelp API v.2.0 Access Key and Tokens
	private string oauthConsumerKey = "your consumer key";
	private string oauthConsumerSecret = "your consumer secret";
	private string oauthToken = "your token";
	private string oauthTokenSecret = "your token secret";
	private string oauthNonce = "";
	private string oauthTimeStamp = "";

	//***********URL Request parameters*******
	// Please refer to http://www.yelp.com/developers/documentation for the API documentation.
	//API SEARCH HOST BASE
	private static string YelpAPIHost = "https://api.yelp.com";
	private static string SearchPath = "/v2/search/"; 
	//SEARCH TERM
	public static string searchterm ="food";//*********I/P your term
	//private static string searchtermURL = "term=" + searchterm;
	//SEARCH LOCATION
	public static string State = "ca"; //California
	public static string City = "San francisco"; //Sanfrancisco - no spaces
	private static string searchLocation = City+","+State;//URL friendly Escape//"WWW.EscapeURL ("San Francisoin, CA");*******I/P your location 
	//SEARCH LIMITS
	public static int searchLimit = 3;//*******I/P your search limite here 
	//SEARCH DEALS
	public static string searchDeals = "true";
	

	//***STEP0******
	void Start (){
	//*********Restaurants Search Request
		string FullYelpURL = YelpAPIHost + SearchPath;	
		PrepareOAuthData();
		StartCoroutine (SearchRestaurantsRequest(FullYelpURL));
	}

	//***STEP1******
	private void PrepareOAuthData() {
		oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));
		TimeSpan _timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);		
		oauthTimeStamp = Convert.ToInt64(_timeSpan.TotalSeconds).ToString(CultureInfo.InvariantCulture);		
		// Override the nounce and timestamp here if troubleshooting with Twitter's OAuth Tool
		//oauthNonce = "69db07d069ac50cd673f52ee08678596";
		//oauthTimeStamp = "1442419142";
	}

	//***STEP2****** &***FINAL STEP8 JSON READBACK****** 
	//Restaurants Search Run
    	private IEnumerator SearchRestaurantsRequest (string YelpURL2){

		// Fix up hashes to be webfriendly
		searchLocation = Uri.EscapeDataString(searchLocation);

		SortedDictionary<string, string> YelpParamsDictionary = new SortedDictionary<string, string> ()
		{
			{"term", searchterm},
			{"location",searchLocation} //maybe limit and deals
        	  //Add {"limit",searchLimit},
            	  //Add {"deals_filter",searchDeals}
		};

		WWW query = CreateYelpAPIQuery (YelpURL2,YelpParamsDictionary);
		yield return query;

        //Write request response to Unity Console 
        Debug.Log(query.text);
        Debug.Log(query.error);

        //Convert String into JSON node
        JSONNode JSONText = JSONNode.Parse(query.text);//Send JSONnode
    }

    //***STEP3******
    private WWW CreateYelpAPIQuery(string YelpURL, SortedDictionary<string, string> YelpParamsDictionary){
		//Create Signature
		string signature = CreateSignature (YelpURL,YelpParamsDictionary);
		Debug.Log("OAuth Signature: " + signature);

		//Create Authorization Header
		string authHeaderParam = CreateAuthorizationHeaderParameter(signature, this.oauthTimeStamp);
		Debug.Log("Auth Header: " + authHeaderParam);
		
		Dictionary<string, string> headers = new Dictionary<string, string>();
		//headers["Authorization"] = "Basic " + System.Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes (authHeaderParam));
		headers["Authorization"] = authHeaderParam;

		string YelpParams = ParamDictionaryToString(YelpParamsDictionary);
		
		WWW query = new WWW(YelpURL + "?" + YelpParams, null, headers);		
		return query;

	}

	//***STEP4******
	// Taken from http://www.i-avington.com/Posts/Post/making-a-twitter-oauth-api-call-using-c
	private string CreateSignature(string url, SortedDictionary<string, string> searchParamsDictionary)
	{
		//string builder will be used to append all the key value pairs
		StringBuilder signatureBaseStringBuilder = new StringBuilder();
		signatureBaseStringBuilder.Append("GET&");
		signatureBaseStringBuilder.Append(Uri.EscapeDataString(url));
		signatureBaseStringBuilder.Append("&");
		
		//the key value pairs have to be sorted by encoded key
		SortedDictionary<string, string> urlParamsDictionary = new SortedDictionary<string, string>()
		{
			//******Alphabetically Organize Signature Parameters -Indicated in Section 3 - Create Signature Base String -https://blog.nraboy.com/2014/11/understanding-request-signing-oauth-1-0a-providers/
			{"oauth_consumer_key", this.oauthConsumerKey},
			{"oauth_nonce", this.oauthNonce},
			{"oauth_signature_method", "HMAC-SHA1"},
			{"oauth_timestamp", this.oauthTimeStamp},
			{"oauth_token", this.oauthToken},
			{"oauth_version", "1.0"}
		};
		
		foreach (KeyValuePair<string, string> keyValuePair in searchParamsDictionary)
		{
			urlParamsDictionary.Add(keyValuePair.Key, keyValuePair.Value);
		}    
		
		signatureBaseStringBuilder.Append(Uri.EscapeDataString(ParamDictionaryToString(urlParamsDictionary)));
		string signatureBaseString = signatureBaseStringBuilder.ToString();
		
		Debug.Log("Signature Base String: " + signatureBaseString);
		
		//generation the signature key the hash will use
		string signatureKey = Uri.EscapeDataString(this.oauthConsumerSecret) + "&" + Uri.EscapeDataString(this.oauthTokenSecret);
		
		HMACSHA1 hmacsha1 = new HMACSHA1(new ASCIIEncoding().GetBytes(signatureKey));
		
		//hash the values
		string signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(new ASCIIEncoding().GetBytes(signatureBaseString)));
		
		return signatureString;
	}

	//***STEP5******
	private string CreateAuthorizationHeaderParameter(string signature, string timeStamp)
	{	//******Organize Paramters like how Oauth.net has it ordered in section 7-Accessing Protected Resources //http://oauth.net/core/1.0a/#anchor12
		string authorizationHeaderParams = String.Empty;
		authorizationHeaderParams += "OAuth ";

		authorizationHeaderParams += "oauth_consumer_key="
			+ "\"" + Uri.EscapeDataString(this.oauthConsumerKey) + "\", ";

		authorizationHeaderParams += "oauth_token=" + "\"" +
			Uri.EscapeDataString(this.oauthToken) + "\", ";

		authorizationHeaderParams += "oauth_signature_method=" + "\"" +
			Uri.EscapeDataString("HMAC-SHA1") + "\", ";	

		authorizationHeaderParams += "oauth_signature=" + "\""
			+ Uri.EscapeDataString(signature) + "\", ";

		authorizationHeaderParams += "oauth_timestamp=" + "\"" +
			Uri.EscapeDataString(timeStamp) + "\", ";     

		authorizationHeaderParams += "oauth_nonce=" + "\"" +
			Uri.EscapeDataString(this.oauthNonce) + "\", ";

		authorizationHeaderParams += "oauth_version=" + "\"" +
			Uri.EscapeDataString("1.0") + "\"";

		return authorizationHeaderParams;
	}

	//***STEP6******
	private string ParamDictionaryToString(IDictionary<string, string> paramsDictionary) {
		StringBuilder dictionaryStringBuilder = new StringBuilder();       
		foreach (KeyValuePair<string, string> keyValuePair in paramsDictionary)
		{
			//append a = between the key and the value and a & after the value
			dictionaryStringBuilder.Append(string.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value));
		}		
		// Get rid of the extra & at the end of the string
		string paramString = dictionaryStringBuilder.ToString().Substring(0, dictionaryStringBuilder.Length - 1);
		return paramString;
	}
	
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.