is there any way how to get and parse signed_request in Node.js Facebook page tab app? I need to know page id and if user liked the page...
I did this a little while ago, and ended up writing a small library to do it. The original CoffeeScript can be found at https://gist.github.com/fbef51815ab6f062b51a#file_signed_request.coffee, here is a JavaScript translation:
var crypto = require('crypto');
SignedRequest = (function() {
function SignedRequest(secret, request) {
this.secret = secret;
this.request = request;
this.verify = this.verify.bind(this);
var parts = this.request.split('.');
this.encodedSignature = parts[0];
this.encoded = parts[1];
this.signature = this.base64decode(this.encodedSignature);
this.decoded = this.base64decode(this.encoded);
this.data = JSON.parse(this.decoded);
}
SignedRequest.prototype.verify = function() {
if (this.data.algorithm !== 'HMAC-SHA256') {
return false;
}
var hmac = crypto.createHmac('SHA256', this.secret);
hmac.update(this.encoded);
var result = hmac.digest('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
return result === this.encodedSignature;
};
SignedRequest.prototype.base64encode = function(data) {
return new Buffer(data, 'utf8').toString('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
};
SignedRequest.prototype.base64decode = function(data) {
while (data.length % 4 !== 0) {
data += '=';
}
data = data.replace(/-/g, '+').replace(/_/g, '/');
return new Buffer(data, 'base64').toString('utf-8');
};
return SignedRequest;
})();
module.exports = SignedRequest;
Which you can use like this:
var verifier = new SignedRequest(clientSecret, signedRequest);
verifier.verify() // whether or not the signed request verifies
verifier.data // the data from the signed request
Related
I'm making a node app that writes contracts with the Arbitrum api, I have successfully accessed the api, I'm new to node and basically I need to access the Arbitrum website with code and write some contracts, if there's anything unclear ask me to edit the post.
my current code:
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider());
var version = web3.version.api;
var getJSON = require('get-json');
getJSON(
'https://api.arbiscan.io/api?module=contract&action=getabi&address=0x0000000000000000000000000000000000001004&apikey=YourApiKeyToken',
function (error, data) {
var contractABI = '';
contractABI = JSON.parse(data);
if (contractABI != '') {
var MyContract = web3.eth.contract(contractABI);
var myContractInstance = MyContract.at(
'0x604cd9df9e73a792feef9877aa53fc25d1b9baa5'
);
var result = myContractInstance.memberId(
'0xfe8ad7dd2f564a877cc23feea6c0a9cc2e783715'
);
console.log('result1 : ' + result);
var result = myContractInstance.members(1);
console.log('result2 : ' + result);
} else {
console.log('Error');
}
}
);
i'm very new to Javascript and i just want to login into website from NodeJS request. This website need information from the first time visited to login.
Here is my code.
var cheerio = require('cheerio');
var loginLink = 'link';
var loginJar = request.jar();
var ltValue = '';
request.get({url: loginLink, jar: loginJar}, function(err, httpResponse, html)
{
var dat = cheerio.load(html);
var arr = dat('input[name="lt"]');
ltValue = arr.attr('value');
arr = dat('input[name="execution"]');
executionValue = arr.attr('value');
/*Post body*/
var loginBody = 'username=' + usn + '&password=' + pwd + '<=' + ltValue + '&execution=' + executionValue
request.post({url: loginLink, jar: loginJar, method: 'post', json: true, body: loginBody, }}, function(err, res, b)
{
if (b.indexOf('errors') != -1)
console.log("Success");
else console.log("Fail");
});
});
I have write try it in C# and it work correctly but in my NodeJs code it always return fail. I have tried everytime but i couldn't do it. Please help me with this problem.
byte[] binData = Encoding.ASCII.GetBytes(loginBody)
string loginFile = "loginInfo.txt";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("link");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = binData.Length;
request.CookieContainer = cookieContainer;
using (Stream stream = request.GetRequestStream())
{
stream.Write(binData, 0, binData.Length);
}
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
File.WriteAllText(loginFile, reader.ReadToEnd());
}
string loginData = userID + " " + password;
File.WriteAllText("login.txt", loginData);
How can I get a specific GET Request and the information in this request like https://example.de/ca.aspx?campaign=123456&pitype=Content via PhantomJS or another headless browser?
var Url = "http://www.google.de";
var params = new Array();
var webPage = require('webpage');
var page = webPage.create();
var targetJSON = {};
page.open(Url);
// the request url you want to catch
page.onResourceRequested = function(requestData, networkRequest) {
var match = requestData.url.match(/google.com\/test.aspx/g);
if (match != null) {
var targetString = decodeURI(JSON.stringify(requestData.url));
var klammerauf = targetString.indexOf("{");
var jsonobjekt = targetString.substr(klammerauf, (targetString.indexOf("}") - klammerauf) + 1);
// request contains some JSON stuff in my case, so I decode it as a JSON object
targetJSON = (decodeURIComponent(jsonobjekt));
console.log(targetJSON);
phantom.exit();
}
};
I use this fusionRequest function but I can not save accented characters.
I think we have to use UTF-8 encryption, but something is wrong in my code.
Here it is :
function fusionRequest(method, sql) {
var url = "https://www.google.com/fusiontables/api/query";
if (USE_OAUTH) {
var fetchArgs = googleOAuth_();
}
else {
var fetchArgs = new Object();
fetchArgs.headers = {
"Authorization": "GoogleLogin auth=" + getAuthToken_()
};
}
fetchArgs.method = method;
if (method == 'get') {
url += '?sql=' + sql;
fetchArgs.payload = null;
}
else {
fetchArgs.payload = 'sql=' + sql;
}
fetchArgs.charset = '"UTF-8"';
var response = UrlFetchApp.fetch(url, fetchArgs);
var responseText = response.getContentText();
return response.getContentText();
}
thanks in advance for your precious help...
BR
Patrick
For POST, you could try:
fetchArgs.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
Haven't tested it, but let me know if it works. Otherwise, you could try:
fetchArgs.headers["Accept-Charset"] = "UTF-8";
I'm trying to send HTTP requests via StreamSocket, but response is truncated with
"failedWinRTError: The object has been closed."
Here is my code:
var count, hostName, raw_request, raw_response, reader, socketProtection, startReader, streamSocket, writer;
streamSocket = new Windows.Networking.Sockets.StreamSocket();
hostName = new Windows.Networking.HostName("www.reddit.com", "80");
raw_response = "";
count = 0;
startReader = function() {
return reader.loadAsync(8 * 1000).done(function(bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (raw_response.indexOf("</html>") > 0) {
return;
} else {
startReader();
}
}, function(error) {
raw_response += reader.readString(reader.unconsumedBufferLength);
window.raw_response = raw_response;
return;
});
};
streamSocket.connectAsync(hostName, "80", 0).done(function(response) {
var string;
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = 1;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
string = "Hello world";
writer.writeString(raw_request);
return writer.storeAsync().done(function() {
writer.flushAsync();
writer.detachStream();
return startReader();
});
});
I noticed that the beginning of the response is truncated as well.
This is what I get at the beginning of HTTP responses.
/1.1 200 OK
Also strangely... HTTPS requests work perfectly.
Any idea what I'm doing wrong? Thanks :)
Remove http:// from the host name and the second parameter is not needed:
var hostName = new Windows.Networking.HostName("www.reddit.com");
Use this object in ConnectAsync, just hostname and service name parameters are needed:
streamSocket.connectAsync(hostName, "80").done(function (response) {
// ....
}, function (error) {
console.log(error);
});
UPDATE: Ok, if the connection is being closed, probably the server closes it. Are you sending a well formed request? Here is an example:
var raw_request, raw_response, reader, writer;
var streamSocket = new Windows.Networking.Sockets.StreamSocket();
function doRequest() {
var hostName = new Windows.Networking.HostName("www.reddit.com");
streamSocket.connectAsync(hostName, "808").then(function () {
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = Windows.Storage.Streams.InputStreamOptions.partial;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
raw_request = "GET / HTTP/1.1\r\nHost: www.reddit.com/\r\nConnection: close\r\n\r\n";
writer.writeString(raw_request);
return writer.storeAsync();
}).then(function () {
raw_response = "";
return startReader();
}, function (error) {
console.log(error);
});
}
function startReader() {
return reader.loadAsync(99999999).then(function (bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (bytesRead === 0) {
window.raw_response.value = raw_response;
return;
}
return startReader();
});
};