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);
}
Related
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;
}
I have a script that will post available stock adjust to Shopify but I don't know how to extend that and get the payload from cells in the sheet and ideally loop the payload so I can update more than one item at a time.
REF: https://shopify.dev/docs/admin-api/rest/reference/inventory/inventorylevel#adjust-2021-01
I want to have cells in the sheet for "location_id", "inventory_item_id", "available_adjustment" and loop these so I could have below for example.
"location_id"
"inventory_item_id"
"available_adjustment"
11594563
34516664746035
1
11595526
34516664746851
-1
11215528
34516664567861
5
11595574
34516664745685
6
This is the current script that is working but I need to manually change the payload and run one at a time where I want to be able to adjust a lot more in one hit.
var url = "https://**********.myshopify.com/admin/api/2021-01/inventory_levels/adjust.json";
var payloaddata = {
"location_id": "11594563",
"inventory_item_id": "34516664746035",
"available_adjustment": "-1"
};
var payload = JSON.stringify(payloaddata);
var username = "*********";
var password = "*********";
var response = UrlFetchApp.fetch(url, {
method: "POST",
payload: payload,
contentType: "application/json",
headers: { "Authorization": "Basic " + Utilities.base64Encode(username + ":" + password) }
});
Logger.log(response.getContentText());
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
} ```
Assuming that your code is working then try this:
I also assume that you spreadsheet looks like your table with same headers and same order of columns
function shopifyPost() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet Name');
const [hA, ...rows] = sh.getDataRange().getValues();
const url = "https://**********.myshopify.com/admin/api/2021-01/inventory_levels/adjust.json";
rows.forEach((r, i) => {
let pld = {};
pld[hA[0]] = r[0];
pld[hA[1]] = r[1];
pld[hA[2]] = r[2];
let payload = JSON.stringify(pld);
let username = "*********";
let password = "*********";
let response = UrlFetchApp.fetch(url, {
method: "POST",
payload: payload,
contentType: "application/json",
headers: { "Authorization": "Basic " + Utilities.base64Encode(username + ":" + password) }
});
});
Logger.log(response.getContentText());
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
The first line looked like this: (after stringifying it)
{"location_id":11594563,"inventory_item_id":34516664746035,"available_adjustment":1}
This is what my data sheet looked like:
location_id
inventory_item_id
available_adjustment
11594563
34516664746035
1
11595526
34516664746851
-1
11215528
34516664567861
5
11595574
34516664745685
6
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 using POST https://www.googleapis.com/gmail/v1/users/userId/settings/sendAs and able to add alias id with a signature in Gsuite account however with same code I am trying to update the signature for primary Gsuite account but it's not updating.
Please guide how to apply a logic to update the primary Gsuite account signature using a service account
https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs
var service_account = {
"private_key":"-----BEGIN PRIVATE KEY-----VE=\n-----END PRIVATE KEY-----\n",
"client_email":"xxxxxx",
"client_id": "xxxxxxx",
"userEmail" = 'admin#demo.in';
};
function getOAuthService(user) {
return OAuth2.createService("Service Account")
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(service_account.private_key)
.setIssuer(service_account.client_email)
.setSubject(userEmail)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setScope('https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.settings.basic');
}
function createAlias() {
var userEmail = 'admin#demo.in';
//var alias = 'Testing#demo.in';
//var alias_name = ' User';
var signature = 'Testing';
var service = getOAuthService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs'
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken(),
"Accept":"application/json",
"Content-Type":"application/json",
};
var resource ={
sendAsEmail: alias,
signature: signature,
replyToAddress : alias,
treatAsAlias: true,
verificationStatus: 'accepted',
isPrimary:true,
isDefault:true
};
var options = {
'headers': headers,
'method': 'POST',
'payload':JSON.stringify(resource),
'muteHttpExceptions': true
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
}
function reset() {
var service = getOAuthService();
service.reset();
}
You need to use the method Users.settings.sendAs: patch
In Apps Script, you can it as following:
function changeSignature() {
var userId = 'your primary email';
var sendAsEmail = userId;
var signature = 'Testing';
var service = getService();
service.reset();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/gmail/v1/users/'+userId+'/settings/sendAs/'+sendAsEmail
var headers ={
"Authorization": 'Bearer ' + service.getAccessToken(),
"Accept":"application/json",
"Content-Type":"application/json",
};
var resource ={
"signature": signature,
};
var options = {
'headers': headers,
'method': 'PATCH',
'payload':JSON.stringify(resource),
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
}
You seem to already do it correctly, but just to point it out:
When you build your service account, it is important to specify the scope https://www.googleapis.com/auth/gmail.settings.basic' and to include .setSubject(userEmail)
I have successfully authenticated Google apps script to salesforce and can query records in Salesforce from Google apps script with the following from gsuitedevs:
function run() {
var service = getService();
if (service.hasAccess()) {
Logger.log("Success.");
var url = service.getToken().instance_url +
'/services/data/v24.0/chatter/users/me';
// Make the HTTP request using a wrapper function that handles expired
// sessions.
var response = withRetry(service, function() {
return UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
}
});
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
However, when I run the following code, I get a 401:
function updateQuoteUrls3() {
var service = getService();
var accessToken = service.getAccessToken();
var quoteId = "a1Gf200000GkZex"; // ID
var folderUrl = "https://drive.google.com/drive/folders/DEFXXX"; // Google_Drive_Folde_URL__c
var sheetUrl = "https://docs.google.com/spreadsheets/d/XXX";
var instanceUrl = "https://na53.salesforce.com";
var queryUrl = "/services/data/v25.0/sobjects/i360__Quote__c/" + quoteId + ".json";
var payload = {
"Google_Drive_Folde_URL__c": folderUrl,
"Pricing_Sheet_URL__c": sheetUrl
};
var headers = {
Authorization: 'Bearer ' + service.getAccessToken(),
"Content-Type": "application/json"
};
var options = {
"method": "patch",
"contentType": "application/json",
"headers": headers,
"payload": JSON.stringify(payload)
};
var url = instanceUrl + queryUrl;
var response = UrlFetchApp.fetch(url, options);
return response; // HTTPresponse - https://developers.google.com/apps-script/reference/url-fetch/http-response
}
I cannot figure out why I am getting the following error:
returned code 401. Truncated server response: [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] (use muteHttpExceptions option to examine full response)
I new to this, have searched for hours, but have come up with nothing so far. Help is greatly appreciated.