I can get account details so my authentication appears correct but in trying to modify that code to create an order it returns a code 401 "msg":"Invalid KC-API-SIGN". The modification involved adding in the method and payload and changing endpoint (/api/vi/accounts) to endpoint2 (/api/v1/orders)
function kucoinTest5()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("xxxxx");
var key = sheet.getRange("xx").getValue()
var secret = sheet.getRange("xx").getValue();
var passphrase = sheet.getRange("xx").getValue();
var host = 'https://openapi-sandbox.kucoin.com';
//var endpoint ='/api/v1/accounts';
var endpoint2 ='/api/v1/orders';
var timestamp = ''+ new Date().getTime();
var strForSign = timestamp + 'GET' + endpoint2;
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, strForSign, secret);
var encodedPass = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, passphrase, secret);
var url= host + endpoint2
var requestOptions = {
'method': "POST",
'headers': {
'KC-API-KEY': key,
'KC-API-TIMESTAMP': timestamp,
'KC-API-SIGN': Utilities.base64Encode(signature),
'KC-API-KEY-VERSION': '2',
'KC-API-PASSPHRASE': Utilities.base64Encode(encodedPass),
},
'payload': {
'clientOid': 'test1',
'side': 'buy',
'symbol': 'BTC-USDT',
'type': 'market',
'tradeType': 'TRADE',
'funds': 100
},
muteHTTPExceptions: true,
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
//var getContext= httpRequest.getContentText();
Logger.log(httpRequest);
}
Solved above problem here is the code to post a buy order on KuCoin:
function kuCoinTest5()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("xxxx");
var key = sheet.getRange("xx").getValue()
var secret = sheet.getRange("xx").getValue();
var passphrase = sheet.getRange("xx").getValue();
var payload = {
'clientOid':"UUID",
'side':"buy",
'symbol':"BTC-USDT",
'type':"market",
'tradeType':"TRADE",
'funds':"100"
};
var data = JSON.stringify(payload);
//Logger.log(data);
var host = 'https://openapi-sandbox.kucoin.com';
var timeStamp = ''+ new Date().getTime();
//var nowStr = "" + nowDate;
var endpoint ='/api/v1/accounts';
var endpoint2 ='/api/v1/orders';
var strForSign = timeStamp + "POST" + endpoint2 + data;
//Logger.log(strForSign);
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, strForSign, secret);
var encodedPass = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, passphrase, secret);
var url= host + endpoint2;
//Logger.log(url);
var options = {
"method":"POST",
'headers' : {
'KC-API-KEY': key,
'KC-API-TIMESTAMP': timeStamp,
'KC-API-SIGN': Utilities.base64Encode(signature),
'KC-API-KEY-VERSION': '2',
'KC-API-PASSPHRASE': Utilities.base64Encode(encodedPass)
},
"contentType":"application/json",
"payload":data,
//'payload' : {'clientOid':"45234524625",
//'side':"buy",
//'symbol':"BTC-USDT",
//'type':"market",
//'tradeType':"TRADE",
//'funds':"100"},
"muteHttpExceptions":true,
}
var result = UrlFetchApp.getRequest(url, options);
Logger.log(result) // a better way to debug
var result = UrlFetchApp.fetch(url, options); // works perfectly in my case
Logger.log(result)
}
I had the same problem with a GET request, and finally solved thanks to the above code. Here is my code:
function KuCoinRequest(){
var key ='xx'
var secret = 'xx'
var passphrase = 'xx'
var url = "https://api-futures.kucoin.com/"; //endpoint
var timestamp = '' + Number(new Date().getTime()).toFixed(0);
var command = "GET";
var endpoint = "api/v1/fills"
var str_to_sign = timestamp + command +"/" + endpoint;
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, str_to_sign, secret)
var encodedPass = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, passphrase, secret);
var params = {
'method': "GET",
'headers' : {
'KC-API-SIGN': Utilities.base64Encode(signature),
'KC-API-KEY': key,
'KC-API-TIMESTAMP': timestamp,
'KC-API-PASSPHRASE': Utilities.base64Encode(encodedPass),
'KC-API-KEY-VERSION': '2',
'muteHttpExceptions': true
}
};
query = url + endpoint;
var data = UrlFetchApp.fetch(query, params);
Logger.log(data.getContentText());
printJsonKucoin(data, endpoint);
return data;
}
Related
I am new here, I am able to find how to update jira summary from google script as below :
function jiraupdate() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://{jira_host}/rest/api/2/issue/{jiraidorkey}";
var data = {"update":{"summary":[{"set":"test google script"}]}};
var payload = JSON.stringify(data);
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Basic " + encCred,
};
var options = {
"method":"PUT",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
thanks to this post here
can anyone show me example how do i update jira status for example from todo to in-progress using google script?
i found it.
function jiraupdate() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://{jirahost}/rest/api/2/issue/{jiraidorkey}/transitions";
var data ={"transition":{"id":"221"}};
var payload = JSON.stringify(data);
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Basic " + encCred,
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I am stucked. I can log in to the website and now after i logged in, i want to get the source code of the url2. Any ideas how i can continue here?
function login() {
var url = "https://www.erevollution.com/en/login";
var payload = {
"email":"test#gmail.com",
"password":"testpassword",
"remember":"on"
};
var options = {
"payload":payload,
"method":"post",
"followRedirects" : false
};
var response = UrlFetchApp.fetch(url, options);
if ( response.getResponseCode() == 200 ) { //could not log in.
var result = "Couldn't login. Username/password is incorrect.";
}
else if ( response.getResponseCode() == 302 ) { //login was successful
var result = "Logged in successfully";
var cookie = response.getAllHeaders()['Set-Cookie'];
var header = { "Cookie":cookie[0] };
var options2 = { "headers": header };
var url2 = "https://www.erevollution.com/tr/market/1/1/1/1";
var response2 = UrlFetchApp.fetch(url2, options2);
}
Logger.log(result);
Logger.log(response2);
}
Issue:
You should be including the cookie in the property headers of the object you are passing as parameter of your call, as you can see in the docs.
Code sample:
var header = { "Cookie": cookie[1] };
var options = { "headers": header };
var url = "https://www.erevollution.com/tr/market/1/1/1/1";
var response = UrlFetchApp.fetch(url, options);
Reference:
UrlFetchApp.fetch(url, params)
I solved the problem by taking my response headers cookies and sorting them as the request headers cookies of the next page (url2) wanted. So i got the right order of cookie (newcookie) for the next page.
function Price() {
var url = "https://www.erevollution.com/en/login";
var payload = {
"email":"test#gmail.com",
"password":"testpassword",
"remember":"on"
};
var options = {
"payload":payload,
"method":"post",
"followRedirects" : false
};
var response = UrlFetchApp.fetch(url, options);
if ( response.getResponseCode() == 200 ) { //could not log in.
var result = "Couldn't login. Username/password is incorrect.";
}
else if ( response.getResponseCode() == 302 ) { //login was successful
var result = "Logged in successfully";
var cookie = response.getAllHeaders()['Set-Cookie'];
for(m=0;m<5;m++){
cookie[m]=cookie[m].substring(0,cookie[m].indexOf(";"));
}
var newcookie=cookie[4]+"; "+cookie[1]+"; "+cookie[2]+";"+cookie[3]+"; "+cookie[0];
var header = { "Cookie":newcookie };
var options2 = { "headers": header };
var url2 = "https://www.erevollution.com/tr/market/1/1/1/1";
var response2 = UrlFetchApp.fetch(url2, options2);
var content = response2.getContentText();
I am fairly new to Google App Scripts. I need to build report inside Spreadsheet using Google-app-script functionality. I know how to download from DCM/DFM reporting excisting report to spreadsheet.
But I've failed to create new inside spreadsheet without downloading existing report from DCM/DFM. Is it possible? May be somebody has a sample (I hadn't found)? Or I've missed the concept and the only way to pull data into Spreadsheet is to create the report in DCM/DCF Report Builder first?
Here is the code i'm using.
function generateReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Reports');
var profileId = 2623334
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var resource = {
'kind': 'dfareporting#report',
'accountId': '34405',
'type': 'STANDARD',
'name': 'Simple Report',
'criteria': {
'dateRange': {
'kind': 'dfareporting#dateRange',
'startDate': '2016-09-01',
'endDate': '2017-01-22',
},
'dimensions': [
{
'kind': 'dfareporting#sortedDimension',
'name': 'dfa:date',
}
],
'metricNames': [
'dfa:clicks', 'dfa:impressions'
],
}
}
var url = DoubleClickCampaigns.Reports.insert(resource, profileId);
var report = UrlFetchApp.fetch(url.urls.apiUrl, httpOptions);
for (var i=0; i<report.length; i++) {
var row = report[i];
sheet.getRange('A' + String(i+2)).setValue(row[0]);
sheet.getRange('B' + String(i+2)).setValue(row[1]);
sheet.getRange('C' + String(i+2)).setValue(row[2]);
}
}
The error appears here:
var report = UrlFetchApp.fetch(url.urls.apiUrl, httpOptions);
Error Messsage:
Can not read property "apiUrl" of undefined object.
My final script is:
function generateReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Reports');
var startDate = Browser.inputBox("Enter a start date (format: 'yyyy-mm-dd')");
var endDate = Browser.inputBox("Enter an end date (format: 'yyyy-mm-dd')");
var ReportName = Browser.inputBox("Enter your future report name");
var profileId = 2623334;
var resource = {
'kind': 'dfareporting#report',
'accountId': '34405',
'type': 'STANDARD',
'name': ReportName,
'criteria': {
'dateRange': {
'kind': 'dfareporting#dateRange',
'startDate': startDate,
'endDate': endDate,
},
'dimensions': [
{
'kind': 'fareporting#sortedDimension',
'name': 'dfa:date'
}
],
'metricNames': [
'dfa:clicks', 'dfa:impressions'
],
},
};
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var url = DoubleClickCampaigns.Reports.insert(resource, profileId); //create Report inside DCM
var newReportId = Number(url.id); //get id of new Report
var additionalParameters = {
'synchronous': 'true'
};
var newReportRun = DoubleClickCampaigns.Reports.run(profileId, newReportId, additionalParameters); // run new Report in DCM
var newReportFileId = Number(newReportRun.id); //get id of New File
var newReportFile = DoubleClickCampaigns.Files.get(newReportId, newReportFileId);
if(newReportFile.urls) {
var httpOptions = {
'headers': {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()}
}
var contents = UrlFetchApp.fetch(newReportFile.urls.apiUrl, httpOptions); //Makes a request to fetch (получать) a URL using optional advanced parameters
if(newReportFile.format == 'CSV') {
var rows = Utilities.parseCsv(contents.getContentText());
if(rows && rows.length) {
var fileName = "DCM_test_work5";
var spreadSheet = SpreadsheetApp.create(fileName);
var sheet = spreadSheet.getActiveSheet();
rows.map(function(r) { sheet.appendRow(r); });
}
} else {
// Store the Excel file directly
Logger.log('not CSV!');
DocsList.createFile(contents.getBlob()).rename(newReportFile.fileName)
}
}
}
Trying to get data from Saleforce Analytics API into Google spreadsheet based on this handy script on Github. Except, instead of running entire report, I am trying to pass email filter based on the email list column on a different sheet of the same doc.
// Use the Analytics API to get report data
function runContactsReport() {
var reportId = '';
var sheetName = 'Report';
var sfService = getSfService();
var userProps = PropertiesService.getUserProperties();
var props = userProps.getProperties();
var name = getSfService().serviceName_;
var obj = JSON.parse(props['oauth2.' + name]);
var instanceUrl = obj.instance_url;
var queryUrl = instanceUrl + "/services/data/v29.0/analytics/reports/" + reportId + "?includeDetails=true"; // Actual request for report Data
var response = UrlFetchApp.fetch(queryUrl, { method : "GET", headers : { "Authorization" : "OAuth "+sfService.getAccessToken() } });
var queryResult = JSON.parse(response.getContentText());
// sheet to insert reports
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(sheetName);
//emails to filter on
var dataSheet = ss1.getSheetByName('DATA');
var emails = getColumnNrByName(dataSheet, 'Email')
var emailFilters = dataSheet.getRange(2, emailds, dataSheet.getLastRow() -1).getValues();
var answer = queryResult.factMap["T!T"].rows; // assumes tabular report
var headers = queryResult.reportExtendedMetadata.detailColumnInfo;
var headname = queryResult.reportMetadata.detailColumns;
var filters = queryResult.reportMetadata.reportFilters; //get filters
var myArray = [];
var tempArray = [];
for (i = 0 ; i < headname.length ; i++) {
tempArray.push(headers[headname[i]].label);
}
myArray.push(tempArray);
for (i = 0 ; i < answer.length ; i++ ) {
var tempArray = [];
function getData(element,index,array) {
tempArray.push(array[index].label)
}
answer[i].dataCells.forEach(getData);
myArray.push(tempArray);
}
var lastRow = sheet.getLastRow();
if (lastRow < 1) lastRow = 1;
sheet.getRange(1,1,lastRow, myArray[0].length).clearContent();
sheet.getRange(1,1, myArray.length, myArray[0].length).setValues(myArray);
}
To do this, I need to send back the report metadata object with edited filters.
Here’s some typical metadata that is returned per Salesforce API:
'{reportMetadata":{"name":"MerchandiseReport","id":"00OD0000001ZbP7MAK","developerName":"MerchandiseReport","reportType":{"type":"MerchandiseList","label":"Merchandise"},"reportFormat":"MATRIX","reportBooleanFilter":null,"reportFilters":[{"column": "QUANTITY", "operator":"greaterThan", "value":"12"}],"detailColumns":["MERCHANDISE.NAME","CREATED_DATE","QUANTITY"],"currency":null,"aggregates":["RowCount"],"groupingsDown":[{"name":"CONTACT2.COUNTRY_CODE","sortOrder":"Asc","dateGranularity":"None"}],"groupingsAcross":[{"name":"OWNER","sortOrder":"Asc","dateGranularity":"None"}]}}'
Unfortunately, I don't know how to pass it in Apps Script. Any help is appreciated!
UPDATE: After battling with this code, here are the latest results. Per API instructions, I needed to pass POST request to pass filter parameters. Send a POST request to the Execute Async resource. If you’re passing filters, include them in the POST request metadata. The request returns the instance ID where results of the run are stored.
So here is what I have:
function filterReport(){
var reportId = '00O33000004Dels';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName('DATA');
var emailds = getColumnNrByName(dataSheet, 'Email');
var emailFilters = dataSheet.getRange(2, emailds, dataSheet.getLastRow() -1).getValues();
for (var i = 0; i < emailFilters.length; i++) {
var payload = JSON.stringify({
'reportMetadata': {
'reportFilters': [{
'value' : emailFilters[i][0],
'column': 'EMAIL',
'operator': 'equals'
}]
}
});
filter(reportId, payload);
}
}
function filter(reportId, payload) {
var sfService = getSfService();
var userProps = PropertiesService.getUserProperties();
var props = userProps.getProperties();
var name = getSfService().serviceName_;
var obj = JSON.parse(props['oauth2.' + name]);
var instanceUrl = obj.instance_url;
var queryUrl = instanceUrl + "/services/data/v35.0/analytics/reports/" + reportId + "/instances";
var options = {
'headers': {
'Authorization' : 'Bearer ' + sfService.getAccessToken()
},
'contentType' : 'application/json',
'method' : 'POST',
'payload' : payload
};
var response = UrlFetchApp.fetch(queryUrl, options);
if (response.getResponseCode() == 200) {
var params = JSON.parse(response.getContentText());
//Logger.log(response.getContentText());
var filterId = params.id;
//Logger.log(filterId);
Logger.log(response.getContentText())
}
}
This returns not one instance ID but 4, as I have in my sample spreadsheet... and I need one ID to pass 4 results (per this example).
After that, I need to send GET request with this instance ID, so I can get the data with filters into the spreadsheet.
I have this function, and it sort of works, but I don't know how to pass that Instance id into it from my POST request automatically...
// Use the Analytics API to get report data
// The try-catch can be removed if you do not need to track errors
function runContactsReport() {
var reportId = '00O33000004Dels';
var sheetName = 'Contact Email Validation Report';
var sfService = getSfService();
var userProps = PropertiesService.getUserProperties();
var props = userProps.getProperties();
var name = getSfService().serviceName_;
var obj = JSON.parse(props['oauth2.' + name]);
var instanceUrl = obj.instance_url;
var queryUrl = instanceUrl + "/services/data/v35.0/analytics/reports/" + reportId + "/instances/0LG33000005ZJdqGAG"; // Actual request for report Data
var response = UrlFetchApp.fetch(queryUrl, { method : "GET", headers : { "Authorization" : "OAuth "+sfService.getAccessToken() } });
var queryResult = JSON.parse(response.getContentText());
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(sheetName);
var answer = queryResult.factMap["T!T"].rows; // assumes tabular report
var headers = queryResult.reportExtendedMetadata.detailColumnInfo;
var headname = queryResult.reportMetadata.detailColumns;
var myArray = [];
var tempArray = [];
for (i = 0 ; i < headname.length ; i++) {
tempArray.push(headers[headname[i]].label);
}
myArray.push(tempArray);
for (i = 0 ; i < answer.length ; i++ ) {
var tempArray = [];
function getData(element,index,array) {
tempArray.push(array[index].label)
}
answer[i].dataCells.forEach(getData);
myArray.push(tempArray);
}
var lastRow = sheet.getLastRow();
if (lastRow < 1) lastRow = 1;
sheet.getRange(1,1,lastRow, myArray[0].length).clearContent();
sheet.getRange(1,1, myArray.length, myArray[0].length).setValues(myArray);
}
So, I am stuck again.. Please help!
I got it to work at last. Hopefully it will helpful for someone. The only issue I am having is that occasionally when I run runContactsReport(), it comes back with error -" TypeError: Cannot read property "T!T" from null." but then it runs fine - quite puzzling... here is what I got:
//this is POST request to pass filters based on email column into report
function filterContacts() {
var reportId = 'YOUR REPORT ID'; //SF Contacts Report ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName('DATA');
var emailds = getColumnNrByName(dataSheet, 'Email'); //custom function that finds header name and returns column umber
var emailFilters = dataSheet.getRange(2, emailds, dataSheet.getLastRow() -1).getValues(); //column with emails
//put all emails in one comma separated string, so we get one instance ID
var emails = emailFilters.toString().split(",").join();
var payload = JSON.stringify({
'reportMetadata': {
'reportFilters': [{
'value' : emails,
'column': 'EMAIL',
'operator': 'equals'
}]
}
});
var sfService = getSfService();
var userProps = PropertiesService.getUserProperties();
var props = userProps.getProperties();
var name = getSfService().serviceName_;
var obj = JSON.parse(props['oauth2.' + name]);
var instanceUrl = obj.instance_url;
var queryUrl = instanceUrl + "/services/data/v35.0/analytics/reports/" + reportId + "/instances";
var options = {
'headers': {
'Authorization' : 'Bearer ' + sfService.getAccessToken()
},
'contentType' : 'application/json',
'method' : 'POST',
'payload': payload
};
//Logger.log(options)
var response = UrlFetchApp.fetch(queryUrl, options);
if (response.getResponseCode() == 200) {
var params = JSON.parse(response.getContentText());
}
//Logger.log("my id is:" + params.id);
return params.id; //return instance ID
}
// use returned instance ID to run report based on email filter
function runContactsReport() {
filterContacts();
var reportId = 'YOUR REPORT ID'; //SF Contact Email Validation Report
Utilities.sleep(200);// pause in the loop for 200 milliseconds
var instanceId = filterContacts();
// Logger.log("And my id is:" + instanceId);
var sheetName = 'Contact Email Validation Report';
var sfService = getSfService();
var userProps = PropertiesService.getUserProperties();
var props = userProps.getProperties();
var name = getSfService().serviceName_;
var obj = JSON.parse(props['oauth2.' + name]);
var instanceUrl = obj.instance_url;
var queryUrl = instanceUrl + "/services/data/v35.0/analytics/reports/" + reportId + "/instances/" + instanceId; // Actual request for report Data
var response = UrlFetchApp.fetch(queryUrl, { method : "GET", headers : { "Authorization" : "OAuth "+sfService.getAccessToken() } });
var queryResult = JSON.parse(response.getContentText());
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(sheetName);
var answer = queryResult.factMap["T!T"].rows; // assumes tabular report
var headers = queryResult.reportExtendedMetadata.detailColumnInfo;
var headname = queryResult.reportMetadata.detailColumns;
var filters = queryResult.reportMetadata.reportFilters;
//Logger.log(filters)
var myArray = [];
var tempArray = [];
for (i = 0 ; i < headname.length ; i++) {
tempArray.push(headers[headname[i]].label);
}
myArray.push(tempArray);
for (i = 0 ; i < answer.length ; i++ ) {
var tempArray = [];
function getData(element,index,array) {
tempArray.push(array[index].label)
}
answer[i].dataCells.forEach(getData);
myArray.push(tempArray);
}
var lastRow = sheet.getLastRow();
if (lastRow < 1) lastRow = 1;
sheet.getRange(1,1,lastRow, myArray[0].length).clearContent();
sheet.getRange(1,1, myArray.length, myArray[0].length).setValues(myArray);
}
I wanted to get the title page of the head unit
I expect to get
Страховые компании Уфы. Адреса отделений в Уфе
And get
��������� �������� ���. ������ ��������� � ���
sample script:
function doGet() {
var options1 = {
contentType: "text/html; charset=windows-1251",
muteHttpExceptions: true
};
var url_catalog = 'http://ufa.insure-company.ru/';
var response = UrlFetchApp.fetch(url_catalog, options1);
var txt = response.getContentText();
doc = Xml.parse(txt, true);
var tbody = doc.html.head;
var title = tbody.getElements("title");
var t = title[0].getText();
return HtmlService.createHtmlOutput(t);
}
function doGet() {
var options1 = {
contentType: "text/html ",
muteHttpExceptions: true
};
var url_catalog = 'http://ufa.insure-company.ru/';
var response = UrlFetchApp.fetch(url_catalog, options1).getContentText("windows-1251");
doc = Xml.parse(response, true);
var tbody = doc.html.head;
var title = tbody.getElements("title");
var t = title[0].getText();
return HtmlService.createHtmlOutput(t);
}
It actually was answered in the old product forum see the answer here
You get the context in the UrlFetchApp class with getContentText().
Working example