var protocol = "https";
var method = "POST";
var host = "mws.amazonservices.com";
var uri = "/Products/2011-10-01";
var marketPlaceId = "ATVPDKIKX0DER";
function generateRequest(asin, action){
var today = new Date();
time = today.toISOString();
var parameters = {
// "ASINList.ASIN.1":asin,
"Query":asin,
"AWSAccessKeyId":AWSAccessKeyId,
"Action": action,
"MarketplaceId":marketPlaceId,
"SellerId": SellerId,
"SignatureMethod":"HmacSHA256",
"SignatureVersion":"2",
"Timestamp":time,
"Version":"2011-10-01"
};
parameters = $.param( parameters );
var messageToEncrypt = method+"\n"+host+"\n"+uri+"\n"+parameters;
var sig = CryptoJS.HmacSHA256(messageToEncrypt, SecretKey);
sig = sig.toString(CryptoJS.enc.Base64);
sig = encodeURIComponent(sig);
parameters = parameters+"&Signature="+sig;
var mwsRequest = protocol+"://"+host+uri+"?"+parameters;
return mwsRequest;
}
// var asaUrl = generateRequest('B01I94N9TC','GetMatchingProduct');
var asaUrl = generateRequest('B01I94N9TC','ListMatchingProducts');
$.ajax({
url:asaUrl,
method: "POST",
success: function(data){
console.log(data)
}
});
It gives an error
"Check your AWS Secret Access Key and signing method. Consult the service documentation for details"
but if you send to Get Matching Product is operating normally
Related
I'm now working on the api of Gatecoin and want to get my open order on Google Sheet. I'm trying this:
function GetOrder() {
var method = "GET"
var URL = "https://api.gatecoin.com/Trade/Orders"
var contentType = "application/json"
var d = new Date()
var now = d.getTime()
var msg = method + URL + contentType + now
var publicKey = :Public_key
var privateKey = :Private_key
var hash = Utilities.computeHmacSha256Signature(msg, privateKey, Utilities.Charset.US_ASCII);
var hashInBase64 = Utilities.base64Encode(hash);
var options ={
'contentType': 'application/json',
'method': method,
'API_PUBLIC_KEY': publicKey,
'API_REQUEST_SIGNATURE': hashInBase64,
'API_REQUEST_DATE': now
};
var rdata = UrlFetchApp.fetch("https://api.gatecoin.com/Trade/Orders", options)
}
But the response mentions I was not logged in. What am I doing wrong?
I believe your options should have headers defined in an object as such:
var options ={
“contentType”: “application/json”,
“method”: method,
“headers”: {
“API_PUBLIC_KEY”: publicKey,
“API_REQUEST_SIGNATURE”: hashInBase64,
“API_REQUEST_DATE”: now
}
};
The Code:
(URL is a working rest api that passes json data)
var request = require('request');
var username = "user";
var password = "pass";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var url = "URL";
request(
{
method: "GET",
url : url
},
function (error, response, data) {
console.log(data);
var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];
var order_id = data.purchase_id;
var title = data.sites[initial_index].products[product_index].title;
var content = data.sites[initial_index].products[product_index].description;
var image = data.sites[initial_index].products[product_index].image;
var total_price = data.sites[initial_index].prices.final_price;
var quantity = data.sites[initial_index].products[product_index].input_fields.quantity;
var sold_by = data.sites[initial_index].info.name;
var order_status = data.sites[initial_index].status;
var datatwo = {
"status": "published",
"order_id": order_id,
"title": title,
"content": content,
"image": image,
"final_price": total_price,
"quantity": quantity,
"sold_by": sold_by,
"order_status": order_status
};
}
);
I receive this error when running the code. How can it be resolved?
var initial_index = Object.keys(data.sites)[0];
^
TypeError: Cannot convert undefined or null to object
You're not parsing the JSON (which is text) you get back. Add this at the top of your request callback:
data = JSON.parse(data);
E.g.:
request(
{
method: "GET",
url : url
},
function (error, response, data) {
data = JSON.parse(data);
var initial_index = Object.keys(data.sites)[0];
// ...
One you've parsed it, you'll have an object tree you can traverse.
I'm trying to parse JSON I recieved from an API call, but I keep running into the error "TypeError: Cannot read property "id" from undefined. (line 42, file "")" I'm relatively new to Apps Script. Any ideas on what's going on? I can get the payload back in JSON, but can't seem to parse it.
function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var id = data.subscription; // kicks back an error
// var id = data; works and returns the whole JSON payload
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A1");
targetCell.setValue(id);
}
According to the documentation here
https://docs.chargify.com/api-subscriptions#api-usage-json-subscriptions-list
it returns an array of subscriptions when you call the /subscriptions.json endpoint. So probably your data object should be handled like:
for (var i=0;i<data.length;i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
}
function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
for (var i = 0; i < data.length; i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
var subscriptionid = item.subscription.id;
}
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A2");
targetCell.setValue(subscriptionid);
}
33I issued the following request to Microsoft to get the AuthCode,
public ActionResult ConnectMicrosoft()
{
var ClientId = "xxxxxxxxx";
// var ClientSecret = "xxxxxxxxxxxxxxx";
var RedirectUri = "http://www.domain.com:50952/Settings/MicrosoftAuthCallback";
var MsUrl = String.Format("https://login.live.com/oauth20_authorize.srf?client_id={0}&scope=wl.basic&response_type=code&redirect_uri={1}", ClientId, RedirectUri);
return Redirect(MsUrl);
}
and this during the callback,
public ActionResult MicrosoftAuthCallback(string code)
{
string result = null;
var ClientId = "xxxxxxxxxxxx";
var ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxx";
var RedirectUri = "http://www.domain.com:50952/Settings/MicrosoftAuthCallback";
var FinalUri = String.Format("https://login.live.com/oauth20_token.srf?client_id={0}&client_secret={1}&code={2}&grant_type=authorization_code&redirect_uri={3}", ClientId, ClientSecret, code, RedirectUri);
HttpWebRequest _Request = HttpWebRequest.Create(FinalUri) as HttpWebRequest;
_Request.Method = "GET";
using (WebResponse _Response = _Request.GetResponse())
{
var sr = new StreamReader(_Response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
var _Serializer = new JavaScriptSerializer();
var TokenData = _Serializer.Deserialize<MicrosoftToken>(result);
return View();
}
The callback method successfully returns the access_token, tokentype and expires_in and authentication_token, but refresh token is missing. Could you give me a clue on what i'm doing wrong?
huh, forgot to include the scope, wl.offline_access, also request must b POST with ContentType = "application/x-www-form-urlencoded"
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