Shopify authentication using the google app script Class OAuthConfig - api

I am trying to connect with my shopify shop through the google javascrip. The schema for authentication should be something similar to the one you can find on google documentation for twitter. I'am trying the following code, but I always get the error:{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
function getInfofromshopify() {
var handle = "01-02-0316_cmt_utensili"
var urljson ="https://mysitename.myshopify.com/admin/products.json?handle="+handle;
var oAuthConfig = UrlFetchApp.addOAuthService("shopify");
oAuthConfig.setAccessTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setAuthorizationUrl("https://mysitename.myshopify.com/admin/oauth/authorize");
oAuthConfig.setConsumerKey(API_KEY);
oAuthConfig.setConsumerSecret(Shared_secret);
var options =
{
"oAuthServiceName" : "shopify",
"oAuthUseToken" : "always"
};
var response = UrlFetchApp.fetch(urljson,options);
var responsestr = response.getContentText();
var result = Utilities.jsonParse(responsestr)
}

This worked for me:
var url = "https://<YOUR_SHOP>.myshopify.com/admin/products.json";
var username = "<YOUR_SHOPIFY_API_KEY>";
var password = "<YOUR_SHOPIFY_API_PASSWORD>";
var response = UrlFetchApp.fetch(url, {"method":"get", "headers": {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)}});

Related

FTX API in Google Apps Script not authenticating

I've successfully connected to most other crypto exchanges but keep getting "success":false,"error":"Not logged in" when using FTX.
This is my code:
var host = 'https://ftx.com/api';
var endpoint ='/wallet/all_balances';
var url = host + endpoint;
var timestamp = ''+ new Date().getTime();
var payload = timestamp + 'GET' + endpoint+'';
var shaObj = new jsSHA("SHA-256", "BYTES");
shaObj.setHMACKey(secret, "BYTES");
shaObj.update(payload);
var signature = shaObj.getHMAC("HEX");
var options = {
method: 'get',
headers: {
'FTX-KEY': key,
'FTX-TS': timestamp,
'FTX-SIGN': signature
},
muteHTTPExceptions: 'true'
}
var jsondata = UrlFetchApp.fetch(url, options);
var data = JSON.parse(jsondata.getContentText());
Any help much appreciated!
Found the answer:
var host = 'https://ftx.com';
var endpoint ='/api/wallet/all_balances';

API integration using google app script calling methods on google sheets

I would like to add different API request on a spreadsheet where i already add some google app script code from here in oder to retrieve all orders from a woocommerce external source, however now i want to add another API calling request which allows me to list all products on my woocommerce source. So i type a new function below, modify the endpoint to /wp-json/wc/v3/products according to woocommerce API rest documentation here Woocommerce API rest doc. Here is the code i add to the Github code :
// Custom code to v2 Woocommerce API
function start_syncv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Products);
fetch_products(sheet)
}
function fetch_products(sheet) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B3").getValue();
var surl = website + "/wp-json/wc/v3/sheet?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + "&per_page=100";
var url = surl
Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = SpreadsheetApp.getSheetByName(sheet);
var consumption = {};
var arrayLength = params.length;
Logger.log(arrayLength)
for (var i = 0; i < arrayLength; i++) {
Logger.log("dfsfsdfsf")
var a;
var container = [];
a = container.push(params[i]["id"]);
Logger.log(a)
a = container.push(params[i]["name"]);
a = container.push(params[i]["sku"]);
a = container.push(params[i]["price"]);
a = container.push(params[i]["tax_status"]);
a = container.push(params[i]["stock_status"]);
a = container.push(params[i]["categories"]["name"]);
a = container.push(params[i]["images"]);
a = container.push(params[i]["attributes"]["options"]);
a = container.push(params[i]["_links"]["self"]["href"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet);
temp.appendRow(container);
}
}
I have issue using google sheets calling method describe here. As i want my new API call request, i think my main problem is to select the right sheet into the spreadsheet.
Here is a copy of my spreadsheet : Woocommerce-google sheets integration

azure active directory graph REST api call through SP.WebRequestInfo on SharePoint Online

Trying to make a REST call through SharePoint's SP.WebRequestInfo.
I'm getting the error "The remote server returned the following error while establishing a connection - 'Unauthorized'." trying to call https://graph.windows.net/[Client]/users?api-version=2013-11-0.
I've successfully retrieved a access token.
Can you help me out why i'm getting this error?
Here is the code i'm using:
var url = "https://graph.windows.net/xxx/users/?api-version=2013-11-08";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("GET");
request.set_headers({
"Authorization": token.token_type + " " + token.access_token,
"Content-Type": "application/json"
});
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var responseBody = JSON.parse(response.get_body());
deferred.resolve(responseBody);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
The code for retrieving the token is:
this.getToken = function (clientId, clientSecret) {
var deferred = $q.defer();
var resource = "https://graph.windows.net";
var formData = "grant_type=client_credentials&resource=" + encodeURIComponent(resource) + "&client_id=" + encodeURIComponent(clientId) + "&client_secret=" + encodeURIComponent(clientSecret);
var url = "https://login.windows.net/xxxxxx.onmicrosoft.com/oauth2/token?api-version=1.0";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("POST");
request.set_body(formData);
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var token = JSON.parse(response.get_body());
deferred.resolve(token);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
function errorHandler() {
deferred.reject(response.get_body());
}
return deferred.promise;
};
Erik, something is strange here - you are using the client credential flow from a JavaScript client - this reveals the secret issued to the client app to the user of the JS app.
The client credential flow also requires the directory admin to grant directory read permission to the client application - not sure if this was already configured - nevertheless it must only be used with a confidential client, not a public client like a JS app.
Azure AD does not yet implement the implicit_grant oauth flow using which a JS client app can acquire an access token on behalf of the user over redirect binding (in the fragment). This is a hugh-pro requirement that we're working on - stay tuned.

Cannot view MicrophoneLevel and VolumeEvent session info using OpenTok

I have set up a basic test page for OpenTok using API Key, Session and Token (for publisher). Is based on the QuickStart with code added to track the microphoneLevelChanged event. Page code is available here. The important lines are:
var apiKey = "API KEY HERE";
var sessionId = "SESSION ID HERE";
var token = "TOKEN HERE";
function sessionConnectedHandler(event) {
session.publish(publisher);
subscribeToStreams(event.streams);
}
function subscribeToStreams(streams) {
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
if (stream.connection.connectionId != session.connection.connectionId) {
session.subscribe(stream);
}
}
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
TB.log("test log stream created: " + event);
}
var pubProps = { reportMicLevels: true };
var publisher = TB.initPublisher(apiKey, null, pubProps);
var session = TB.initSession(sessionId);
session.publish(publisher);
session.addEventListener("sessionConnected", sessionConnectedHandler);
session.addEventListener("streamCreated", streamCreatedHandler);
session.addEventListener("microphoneLevelChanged", microphoneLevelChangedHandler);
session.connect(apiKey, token);
function microphoneLevelChangedHandler(event) {
TB.log("The microphone level for stream " + event.streamId + " is: " + event.volume);
}
I know that the logging works, as the logs show up from streamCreatedHandler. However, I am not getting any events logged in the microphoneLevelChangedHandler function. I have tried this with both one and two clients loading the pages (videos show up just fine).
What do I need to do to get the microphoneLevelChanged events to show up?
OpenTok's WebRTC js library does not have a microphoneLevelChanged event so there is nothing you can do, sorry.

PhoneGap FileTransfer with HTTP basic authentication

I'm attempting to upload a file from PhoneGap to a server using the FileTransfer method. I need HTTP basic auth to be enabled for this upload.
Here's the relevant code:
var options = new FileUploadOptions({
fileKey: "file",
params: {
id: my_id,
headers: { 'Authorization': _make_authstr() }
}
});
var ft = new FileTransfer();
ft.upload(image, 'http://locahost:8000/api/upload', success, error, options);
Looking over the PhoneGap source code it appears that I can specify the authorization header by including "headers" in the "params" list as I've done above:
JSONObject headers = params.getJSONObject("headers");
for (Iterator iter = headers.keys(); iter.hasNext();)
{
String headerKey = iter.next().toString();
conn.setRequestProperty(headerKey, headers.getString(headerKey));
}
However, this doesn't seem to actually add the header.
So: is there a way to do HTTP basic auth with PhoneGap's FileTransfer, for both iPhone and Android?
You can add custom headers by adding them to the options rather than the params like so:
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
options.headers = {'Authorization': authHeaderValue('Bob', '1234') };
The correct location for the headers array is as an immediate child of options. options->headers. Not options->params->headers. Here is an example:
//**************************************************************
//Variables used below:
//1 - image_name: contains the actual name of the image file.
//2 - token: contains authorization token. In my case, JWT.
//3 - UPLOAD_URL: URL to which the file will be uploaded.
//4 - image_full_path - Full path for the picture to be uploaded.
//***************************************************************
var options = {
fileKey: "file",
fileName: 'picture',
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': image_name}
};
var headers = {'Authorization':token};
//Here is the magic!
options.headers = headers;
//NOTE: I creaed a separate object for headers to better exemplify what
// is going on here. Obviously you can simply add the header entry
// directly to options object above.
$cordovaFileTransfer.upload(UPLOAD_URL, image_full_path, options).then(
function(result) {
//do whatever with the result here.
});
Here is the official documentation: https://github.com/apache/cordova-plugin-file-transfer
You can create a authorization header yourself. But you can also enter the credentials in the url like this:
var username = "test", password = "pass";
var uri = encodeURI("http://"+username + ':' + password +"#localhost:8000/api/upload");
See FileTransfer.js for the implementation (line 45):
function getBasicAuthHeader(urlString) {
var header = null;
// This is changed due to MS Windows doesn't support credentials in http uris
// so we detect them by regexp and strip off from result url
// Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
if (window.btoa) {
var credentials = getUrlCredentials(urlString);
if (credentials) {
var authHeader = "Authorization";
var authHeaderValue = "Basic " + window.btoa(credentials);
header = {
name : authHeader,
value : authHeaderValue
};
}
}
return header;
}