Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/9097007 to your computer and use it in GitHub Desktop.
Save Noitidart/9097007 to your computer and use it in GitHub Desktop.
_twiitter-oauth\request_token-POST - example
//https://api.twitter.com/oauth/request_token
//requestURL: "https://api.twitter.com/oauth/request_token"
var param = {
oauth_callback: 'http://www.floppers.comyr',
oauth_signature_method: 'PLAINTEXT',
oauth_timestamp: '', ////running setTimestampNonceSignature() will update this
oauth_version: '1.0',
oauth_consumer_key: ' jrcJKxvJ92NeeV48RL1lotN9PigbxCCbqUkKj237yio', //api key u get from ur app page on twiitter
oauth_signature: '', //running setTimestampNonceSignature() will update this //to make the function i followed steps here to create my gen function: https://dev.twitter.com/docs/auth/creating-signature
oauth_nonce: '' //running setTimestampNonceSignature() will update this
}
//then first run this func
setTimestampNonceSignature();
//then can run post
var labelHTTP = 'twit api requesting token';
HTTP('POST', 'https://api.twitter.com/oauth/request_token', {
headers: param,
returnHeaders: true,
//timeout: 30000,
//onTimeout: function() {
//Cu.reportError('TIMEOUT: ' + labelHTTP);
//},
onSuccess: function(status, responseXML, responseText, headers, statusText) {
var respDataStr = [];respDataStr.push('status:"' + status + '"');respDataStr.push('statusText:"' + statusText + '"');respDataStr.push('responseText:"' + responseText + '"');respDataStr.push('headers:"' + uneval(headers) + '"');respDataStr = respDataStr.join('<br><br>');
//Logs.push('SUCCESS loaded loadLike' + '|' + new Date().toLocaleString().replace(/^.*?, /m,'') + '|' + respDataStr);
Cu.reportError('SUCCESS: ' + labelHTTP + '\n\nstatusText:' + statusText + '\nresponseText:' + responseText + '\nheaders:' + uneval(headers));
},
onFailure: function(status, responseXML, responseText, headers, statusText) {
Cu.reportError('FAIL: ' + labelHTTP + '\n\nstatusText:' + statusText + '\nresponseText:' + responseText + '\nheaders:' + uneval(headers));
var respDataStr = [];respDataStr.push('status:"' + status + '"');respDataStr.push('statusText:"' + statusText + '"');respDataStr.push('responseText:"' + responseText + '"');respDataStr.push('headers:"' + uneval(headers) + '"');respDataStr = respDataStr.join('<br><br>');
Cu.reportError('FAILED loading ' + labelHTTP + '|' + new Date().toLocaleString().replace(/^.*?, /m,'') + '|' + respDataStr);
//var response = JSON.parse(responseText);
}
});
//standard functions
function setTimestampNonceSignature() {
param.oauth_timestamp = new Date().getTime();
param.oauth_nonce = _nonce();
//start gen signature
//param.oauth_signature = ''; //no need for thsi line as we overwrite sig val
var combine = [];
var keys = [];
for (var p in param) {
if (p == 'oauth_signature') {
continue;
}
keys.push(p);
}
keys.sort(); //sorts it lexographically
//NOTE: important: values in param must not be urlencoded
for (var i=0; i<keys.length; i++) {
combine.push(keys[i] + '=' + param[keys[i]]);
}
combine.splice(0, 0,'POST','https://api.twitter.com/oauth/request_token');
param.oauth_signature = combine.join('&');
console.log(param.oauth_signature);
param.oauth_signature = rawurlencode(param.oauth_signature);
console.log(param.oauth_signature);
//signature done
}
//https://gist.github.com/Noitidart/9087938
function _nonce(length) {
if (typeof length === "undefined") {
length = 8;
}
if (length < 1) {
console.warn("Invalid nonce length.");
}
var nonce = "";
for (var i = 0; i < length; i++) {
var character = Math.floor(Math.random() * 61);
nonce += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".substring(character, character + 1);
}
return nonce;
};
//from: https://github.com/kvz/phpjs/blob/master/functions/url/rawurlencode.js
//also found at: http://phpjs.org/functions/rawurlencode/
function rawurlencode(str) {
// discuss at: http://phpjs.org/functions/rawurlencode/
// original by: Brett Zamir (http://brett-zamir.me)
// input by: travc
// input by: Brett Zamir (http://brett-zamir.me)
// input by: Michael Grier
// input by: Ratheous
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Joris
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// note: This reflects PHP 5.3/6.0+ behavior
// note: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
// note: pages served as UTF-8
// example 1: rawurlencode('Kevin van Zonneveld!');
// returns 1: 'Kevin%20van%20Zonneveld%21'
// example 2: rawurlencode('http://kevin.vanzonneveld.net/');
// returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
// example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
// returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
str = (str + '')
.toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.
replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
}
//HTTPWRapper from https://gist.github.com/Noitidart/9088113
/**
* The following keys can be sent:
* onSuccess (required) a function called when the response is 2xx
* onFailure a function called when the response is not 2xx
* username The username for basic auth
* password The password for basic auth
* overrideMimeType The mime type to use for non-XML response mime types
* timeout A timeout value in milliseconds for the response
* onTimeout A function to call if the request times out.
* body A string containing the entity body of the request
* contentType The content type of the entity body of the request
* headers A hash of optional headers
* returnHeaders Set to true if want headers returned in the "headers" var of the onSuccess etc
*/
function HTTP(method,url,options)
{
var requester = new XMLHttpRequest();
var timeout = null;
if (!options.synchronizedRequest) {
requester.onreadystatechange = function() {
switch (requester.readyState) {
case 0:
if (options.onUnsent) {
options.onUnsent(requester);
}
break;
case 1:
if (options.onOpened) {
options.onOpened(requester);
}
break;
case 2:
if (options.onHeaders) {
options.onHeaders(requester);
}
break;
case 3:
if (options.onLoading) {
options.onLoading(requester);
}
break;
case 4:
if (timeout) {
clearTimeout(timeout);
}
if (requester.status==0 || (requester.status>=200 && requester.status<300)) {
options.onSuccess(
requester.status,
requester.responseXML,
requester.responseText,
options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
requester.statusText
);
} else {
if (options.onFailure) {
options.onFailure(
requester.status,
requester.responseXML,
requester.responseText,
options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
requester.statusText
);
}
}
break;
}
}
}
if (options.overrideMimeType) {
requester.overrideMimeType(options.overrideMimeType);
}
if (options.username) {
requester.open(method,url,!options.synchronizedRequest,options.username,options.password);
} else {
requester.open(method,url,!options.synchronizedRequest);
}
if (options.timeout && !options.synchronizedRequest) {
timeout = setTimeout(
function() {
var callback = options.onTimeout ? options.onTimeout : options.onFailure;
callback(0,"Operation timeout.");
},
options.timeout
);
}
if (options.headers) {
for (var name in options.headers) {
requester.setRequestHeader(name,options.headers[name]);
}
}
if (options.sendAsBinary) {
Cu.reportError('sending as binary');
requester.sendAsBinary(options.body);
} else if (options.body) {
requester.setRequestHeader("Content-Type",options.contentType);
requester.send(options.body);
} else {
requester.send(null);
}
if (options.synchronizedRequest) {
if (requester.status==0 || (requester.status>=200 && requester.status<300)) {
options.onSuccess(
requester.status,
requester.responseXML,
requester.responseText,
options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
requester.statusText
);
} else {
if (options.onFailure) {
options.onFailure(
requester.status,
requester.responseXML,
requester.responseText,
options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
requester.statusText
);
}
}
return {
abort: function() {
}
};
} else {
return {
abort: function() {
clearTimeout(timeout);
requester.abort();
}
};
}
}
var _HTTP_HEADER_NAME = new RegExp("^([a-zA-Z0-9_-]+):");
function _HTTP_parseHeaders(headerText)
{
var headers = {};
if (headerText) {
var eol = headerText.indexOf("\n");
while (eol>=0) {
var line = headerText.substring(0,eol);
headerText = headerText.substring(eol+1);
while (headerText.length>0 && !headerText.match(_HTTP_HEADER_NAME)) {
eol = headerText.indexOf("\n");
var nextLine = eol<0 ? headerText : headerText.substring(0,eol);
line = line+' '+nextLine;
headerText = eol<0 ? "" : headerText.substring(eol+1);
}
// Parse the name value pair
var colon = line.indexOf(':');
var name = line.substring(0,colon);
var value = line.substring(colon+1);
headers[name] = value;
eol = headerText.indexOf("\n");
}
if (headerText.length>0) {
var colon = headerText.indexOf(':');
var name = headerText.substring(0,colon);
var value = headerText.substring(colon+1);
headers[name] = value;
}
}
return headers;
}
@Noitidart
Copy link
Author

Rev5 prepares the parameters

Rev6 actually posts it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment