How to integrate Gumroad API with Google Apps Script - google-apps-script

I'm trying to see if a user is a paying customer for my gumroad product. I'm trying to integrate the Gumroad API to Google Apps Script.
I have the following code
function checkAccount(){
var token = <<token>>;
var userEmail = Session.getActiveUser().getEmail();
var url = "https://api.gumroad.com/v2/sales";
var headers = {"access_token=" : token};
var options = {
"method" : "GET",
"email" : userEmail,
"headers" : headers
};
var response = UrlFetchApp.fetch(url, options);
var jsonObject = JSON.parse(response.getContentText());
Logger.log(jsonObject);
}
I get the following error Exception: Request failed for https://api.gumroad.com returned code 401 which Gumroad is telling me 401 Unauthorized you did not provide a valid access token. I've checked the token and it's correct. I've logged the options and headers, and they show up correctly.
I'm just not sure why it's giving me a 401.

Try changing headers to this:
var headers = {
"Authorization": `access_token=${token}`
};
EDIT:
Based on this you could try:
headers: {
Authorization: `Bearer ${token}`}

Related

How do you include an Authorization http header with an access token in a square api call?

I'm trying to write square api data to a google sheet and am working through a 401:
Exception: Request failed for https://connect.squareup.com returned code 401. Truncated server response: {"errors": [{"code": "UNAUTHORIZED","detail": "Your request did not include an Authorization http header with an access token. The header value i... (use muteHttpExceptions option to examine full response)
function authorizeSquareUser()
{
var service = getSquareService();
var authorizationUrl = service.getAuthorizationUrl();
var template = HtmlService.createTemplateFromFile('square/auth-sidebar');
template.authorizationUrl = authorizationUrl;
console.log("Auth URL is %s", authorizationUrl);
template.service = "Square"
var page = template.evaluate().setTitle('Authorize Square').setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
SpreadsheetApp.getUi().showSidebar(page);
}
function listPayments() {
var url = "https://connect.squareup.com/v2/payments";
var headers = {
'Authorization': 'Bearer ' + getSquareService().getAccessToken(),
'Square-Version': '2022-02-16',
'Content-Type': 'application/json'
};
var response = UrlFetchApp.fetch(url, headers);
var data = JSON.parse(response.getContentText());
var text = response.getResponseCode();
Logger.log(data);
}
In your script, I think that the request header is not correct. So, how about the following modification?
From:
var response = UrlFetchApp.fetch(url, headers);
To:
var response = UrlFetchApp.fetch(url, {headers});
or
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + getSquareService().getAccessToken(),
'Square-Version': '2022-02-16',
'Content-Type': 'application/json'
}
});
Note:
If your access token cannot be used, I'm worried that another error occurs. At that time, please check your access token again.
Reference:
fetch(url, params)

Google Apps Script scrape data from website with OAuth and recaptcha

Background:
I want to scrape data from a website by "google apps script" for personal use.
The data is from a member page which means i have to set a username and password to payload and pass the cookies to member page. This worked before the website upgraded.
Below is the code i used before:
var url = "https://ww2.metroplex.com.hk/en/member/login";
var formData = {
'username': userEmail,
'password': userPW
};
var options = {
"method": "post",
'contentType': 'application/json',
'payload' : JSON.stringify(formData),
"followRedirects": false,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var responseCode = response.getResponseCode();
var redirectUrl = response.getHeaders()['Location'];
//**************Member Page (after login)******************
var url = "https://ww2.metroplex.com.hk/en/member/login/profile";
if (redirectUrl != null){
url = redirectUrl;
}
var cookie_string = response.getAllHeaders()['Set-Cookie'];
var cookie = [{}];
for (var i = 0; i < cookie_string.length; i++) {
cookie[i] = cookie_string[i].split( ';' )[0];
};
cookie = cookie.join(';');
var dataHeaders = {
'Cookie': cookie
};
options = {
"method": "get",
"headers": dataHeaders
};
var dataResponse = UrlFetchApp.fetch(url, options);
var dataResponseCode = response.getResponseCode();
var html_text = dataResponse.getContentText();
var table_array = html_text.split("Member Summary");
i want to get member information (Member Summary) like below:
The website currently upgraded and the above method did not work.
The "table_array" should be returned 2 array splitted by value "Member Summary", but currently the value is same as html_text
I trace the network by Chrome and i see there are few things that might need to pass during log-in
access token
authorization
recaptcha
I am not sure whether the recaptcha is required.
I don't know how to get it work. If anyone experiences this kind of website and can program it to log-in and scrape data. Please feel free to discuss
Below is the website i want to access:
https://ww2.metroplex.com.hk/en/movie/highlight
You can use temporary email for registration:
https://ww2.metroplex.com.hk/en/member/freeregister
and the trace network I preformed:
the access token when you go to the website
there is an oauth authorization
google recaptcha

Spotify API authorisation via Google Apps Script

I am using the following code to make requests to the Spotify API via Google Apps Script:
function search() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var artist = sheet.getRange(1,1).getValue();
artist = encodeURIComponent(artist.trim());
var result = searchSpotify(artist);
Logger.log(result);
}
function searchSpotify(artist) {
//searches spotify and returns artist ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/search?q=" + artist + "&type=artist&limit=1",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var uri = data.artists.items[0].uri.slice(15);
var getArtists = getRelatedArtists(uri);
Logger.log(getArtists);
return getArtists;
}
function getRelatedArtists(uri) {
//searches related artists with the returned ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/artists/" + uri + "/related-artists",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var listArtists = [];
for(var i = 0, len = data.artists.length; i < len; i++){
listArtists.push(data.artists[i].name);
}
return listArtists;
}
This works fine using the temporary Authorisation token from the Spotify website but this token refreshes every hour and so is obviously useless.
I am trying to use my own Authorisation token and ID which I have setup on Spotify however I'm struggling to make this work. As I understand it I may need to add an extra step at the beginning to start the authorisation process but I've tried all methods suggested but keep receiving server errors.
From the document, it seems that "Client Credentials Flow" uses the basic authorization.
In order to use this, at first, you are required to retrieve "client_id" and "client_secret".
Sample script:
var clientId = "### client id ###"; // Please set here.
var clientSecret = "### client secret ###"; // Please set here.
var url = "https://accounts.spotify.com/api/token";
var params = {
method: "post",
headers: {"Authorization" : "Basic " + Utilities.base64Encode(clientId + ":" + clientSecret)},
payload: {grant_type: "client_credentials"},
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
From curl sample, grant_type is required to send as form.
Result:
The document says that the response is as follows.
{
"access_token": "NgCXRKc...MzYjw",
"token_type": "bearer",
"expires_in": 3600,
}
Note:
This is a simple sample script. So please modify this for your situation.
I prepared this sample script by the sample curl in the document.
Reference:
Client Credentials Flow
Edit:
As your next issue, you want to retrieve the access token from the returned value. If my understanding is correct, how about this modification? Please modify my script as follows.
From:
Logger.log(res.getContentText())
To:
var obj = JSON.parse(res.getContentText());
Logger.log(obj.access_token)
When the value is returned from API, it returns as a string. So it is required to parse it as an object using JSON.parse().

SSL Error when making a request via UrlFetchApp

I'm trying to make a simple GET request to a site with a valid SSL certificate using UrlFetchApp, but I continuously encounter this error:
ScriptError: SSL Error https://dev.kaizena.com/api/config
Interestingly enough, the same request works as expected when I make a request to https://kaizena.com/api/config
Here's the code I'm using:
var url = "https://dev.kaizena.com/api/config";
var payload = JSON.stringify(data);
var headers = { "Accept":"application/json",
"Content-Type":"application/json"//,
};
var options = { "method":"GET",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
}
var response = UrlFetchApp.fetch(url);
Again, the code works as expected if I change the URL to https://kaizena.com/api/config (which also has a valid SSL certificate). Could someone let me know specifically what an "SSL Error" is?
Thanks,
Edward
You can use validateHttpsCertificates to ignore this SSL error.
var options = {
'validateHttpsCertificates' : false
};
var response = UrlFetchApp.fetch(url, options);
It looks like the issue is with Google not recognizing the provider of the SSL Certificate I used. For reference, I was using PositiveSSL, which provided a valid certificate but didn't seem to make Apps Script very happy. I switched to RapidSSL today and now it all works.
Thank you all for the help.
The syntax for urlFetchApp is:
fetch(url)
or
fetch(url, params)
urlFetchApp
You are creating a payload, header and options, but then not using them.
var response = UrlFetchApp.fetch(url);
Should be:
var response = UrlFetchApp.fetch(url, options);

How to follow HTTPResponse in Google Apps Script?

I get this error below when I GET my google apps script.
ERROR: The script completed but did not return anything.
Since I will be posting to my app (which redirects to my app when the post is complete), I should be automatically redirected back to my app?
function doGet(e){
var options = {
"method" : 'POST',
"payload" : "user_id="+e.parameter.user_id+"&gmail="+getEmail()
};
var url = 'http://somedomain.com/users/give_gmail_permission/';
var response = UrlFetchApp.fetch(url, options);
return response;
}
What am I doing wrong? How do I follow HTTPResponse in Google Apps Script?
change the line:
return response
for
return HtmlService.createHtmlOutput("<b>"+response.getResponseCode()+"</b><br>"+response.getContentText()).
setSandboxMode(HtmlService.SandboxMode.NATIVE);
the modified script:
function doGet(e){
var options = {
"method" : 'POST',
"payload" : "user_id="+e.parameter.user_id+"&gmail="+getEmail()
};
var url = 'http://somedomain.com/users/give_gmail_permission/';
var response = UrlFetchApp.fetch(url, options);
Logger.log("response code: "+response.getResponseCode());
Logger.log("response: "+response.getContentText());
return HtmlService.createHtmlOutput("<b>"+response.getResponseCode()+"</b><br>"+response.getContentText()).
setSandboxMode(HtmlService.SandboxMode.NATIVE);
}