How to login through api from Google Script? - javascript

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
}
};

Related

How to perform call signing in Java scripts with scripting apps?

I Have the following problem, any help is welcome, I am trying to get result of a function and make a call, but the process is happening as it should, when I step the result in a variable The result is this:
Result URL var parameter
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, async_percent_completion = 0, Async_status = Job Not Started, date_stop = 2019-04-08, id = 2299845083590625}
Passing direct the value in the URL The result is this:
Manual
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, time_completed = 1554817907, async_percent_completion = 100, Async_status = Job Completed, date_stop = 2019-04-08, id = 2299845083590625}
What am I doing wrong that I can't get the second call I need to finalize my lawsuit?
Documentation :
https://developers.facebook.com/docs/marketing-api/insights/best-practices/?hc_location=ufi#asynchronous
function solicitacaoAssicrona(){
var service = getService()
var metricas = [
'impressions',
'reach',
'unique_clicks',
'account_currency',
'account_id',
'account_name',
'ad_id',
'ad_name',
'adset_id',
'adset_name',
'buying_type',
'campaign_id',
'campaign_name',
]
var parameters = metricas.join(',');
var url = 'https://graph.facebook.com/v3.2/act_xxxxxxxxxx/insights?fields=' + parameters + '&level=ad';
//Logger.log(url);
var report_run_id = UrlFetchApp.fetch(url, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(report_run_id.getContentText());
return result;
}
result= [19-04-09 12:28:34:334 BRT] {report_run_id=1283453988472584}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/' + report;
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
return result;
}
[19-04-09 12:30:38:457 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxxx, async_percent_completion=0, async_status=Job Not Started, date_stop=2019-04-08, id=806453509753109}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/806453509753109';
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(result)
return result;
}
[19-04-09 12:31:26:785 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxx, time_completed=1554823839, async_percent_completion=100, async_status=Job Completed, date_stop=2019-04-08, id=xxxxxxx}
Solved with caching, I stored the report ID in cache there worked well! Follow Documentation! https://developers.google.com/apps-script/reference/cache/cache

Node.JS and Object.Keys with json

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.

How to create a valid signature for the mws amazon (javascript)?

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

Undefined Error when parsing JSON in google apps script

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);
}

Microsoft OAuth does not return refresh_token

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"

Categories

Resources