PayPal Authorization for API with Appscript - google-apps-script

The following fails with the error :{"error":"invalid_client","error_description":"Client Authentication failed"}. It is unclear what aspect of the syntax needs to change as I have used the same format for another API and it has worked. The only difference I can see is PayPal's link has OAuth2 as the access tokens type, however they do define that Basic can be used with their suggested development platform Postman.
https://developer.paypal.com/api/rest/authentication/
function GetPayPalToken(){
response = UrlFetchApp.fetch('https://api-m.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + Utilities.base64Encode(PayPalClientID+':'+PayPalKey)
},
grant_type: 'client_credentials',
muteHttpExceptions: true
});
console.log(response.getContentText());
}

As detailed in the documentation referenced, the body must be grant_type=client_credentials

Related

Exception: Bad request: https://internal-api.company.com... -Google appscript

I have an internal API that I can check by postman status connected to VPN and with a token that changes daily:
but I have not been able to make the same query from Google Apps Script, I get this error:
Exception: Bad request: https://... .
function nomina() {
var url = 'https://internal-api.company.com/app-api/master/api/ssff/users';
var headers= {
'Authorization' : 'Bearer token',
'Accept': 'application/json',
'contentType': 'application/json'
}
var options =
{
'method' : 'GET',
'headers' : headers
}
var response = UrlFetchApp.fetch(url,options);
jsonParse=(JSON.parse(response))
}
Maybe you could suggest me something to be able to do the API query?
I need to know why it doesn't give me an answer, this is another API that I use and this does bring me information.
I see this similar post but have same error still:
Request to external api to get authentication token in google appscript
Google Apps Script run from the Google servers. It can't use your VPN. You should talk with the responsible of the API and request them to make a connection with Google servers. They might have to involve other people (system and / or networks administrators).

How to ensure the API response for a request is JSON type in Google Apps Script? [duplicate]

This question already has answers here:
Apps Script - UrlFetchApp.fetch {url, method: "GET"} to a gzip gets failed with code 406
(2 answers)
Closed 1 year ago.
I'm trying to login to the tableau rest API in apps script and then get all the available views under a workbook. I'm authenticating via PATs and on successful sign-in I receive a response from the API that looks like XML response.
Here's the fetch code for that:
function tableauTM() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
Accept: 'application/json',
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'Tableau',
personalAccessTokenSecret: '<token_secret>',
site: {
contentUrl: 'pixybi',
},
},
}
),
};
const response = UrlFetchApp.fetch(
'https://10ay.online.tableau.com/api/3.13/auth/signin', options
);
Logger.log(response)
This is the response text I receive:
<?xml version='1.0' encoding='UTF-8'?><tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api https://help.tableau.com/samples/en-us/rest_api/ts-api_3_13.xsd"><credentials token="1j4LgLC1TQagsevrKPwJEw|VGo4bJwHbRQPRYxuOaeHhnsVth7nNc3e" estimatedTimeToExpiration="363:04:39"><site id="c3f66f3d-1112-4bff-a5f4-b4022e303d13" contentUrl="udacitybi"/><user id="c34bf5f6-86b8-4de6-a619-f68837bce120"/></credentials></tsResponse>
How to ensure that the response is of JSON type and if that's not possible how can
one extract the attribute values for fields like token, user, and site id?
We tried the below code but it's throwing the type error: TypeError: Cannot read property 'getChild' of null
var root = XmlService.parse(response).getRootElement().getChild('credentials').getChild('user').getAttribute('id').getValue()
You can parse XML using XML Service. Based on your error message, no root element exists, therefore you should first try hasRootElement() before calling getRootElement(). Instead you can try getDescendants() and log out its result.
Fix your options by adding Headers under the headers parameter. See the UrlFetch Docs. Basically, see headers below for what I mean. Hopefully this should enable you to receive JSON.
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
headers: { Accept: 'application/json' }, …
}

How to grab REST API data and display in a html page

Hi i am trying to get data from my LMS's rest API and then display it on a html page, I have a URL and an authorization bearer key
I was provided with some examples of how I should show my url and where to place my Authorization key see below
GET https://example.thoughtindustries.com/incoming/v2/ping
Example Request
CURL https://example.thoughtindustries.com/incoming/v2/ping -H 'Authorization: Bearer APIKEY'
I get a call back using the CURL in Visual Studio code so i know it can be pulled.
I found this method online which I thought would work
$.ajax({
url: "https://api.apiscience.com/v1/monitors/1572022",
headers: {
"Authorization": "Bearer NN_6xxxxx"
}
}).done(function(data) {
$('#monitor_data').append(JSON.stringify(data))
});
<h2>Response Data</h2>
<div id="monitor_data">
<!--location for Javascript to print data-->
</div>
I thought this would be the answer when replacing with my own URL and key but nothing happened. Do I need to include the -H somewhere and if so what might that look like?
It's easy as you have already done this. Write a get ajax call to your API and render your html part from the response you get from the API.
Take a sample example:
var getGamePeriod = function(){
$.ajax({
type: "GET",
url: "yourendpointhere?param=val",
contentType: "application/json",
dataType : 'json',
success : function(response){
if(response && response.isSuccess){
// do your stuffs here..
}
},
error : function(data,textStatus,errorMessage){
alert( textStatus + " " + errorMessage);
}
});
}
Of course you need to pass header or auth token if it is required to access the API. Place this method under document.ready method.

Github GraphQL API Authentication

I want to retrieve data from github's graphql api but I keep getting error message:
{ message: 'This endpoint requires you to be authenticated.', documentation_url: 'https://docs.github.com/v3/#authentication' }
Despite using a token, I even generated a new token to see if the other one was broken. The script to fetch the data can be found at https://repl.it/#DukeSanmi/AcrobaticModernLanguage#index.js
What could be the issue?
Okay you need to put a space between bearer and your variables.githubToken like so:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer ' + variables.githubToken
};
Furthermore, NEVER publish secrets/credentials like API tokens in public code!

Sending image in correct format to Google Cloud Storage

I'm currently using the JSON API to send an image to GCS. However, when I send an image in base64, the image does not show up. Here is my request code
fetch(gcloud_storage_url+`?uploadType=media&name=${name}`, {
method: 'post',
headers: {
'Content-Type': 'image/jpeg',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify({image: imageBase64})
}).then(resp => { console.log(resp) })
Not sure if my post body is in the wrong format.
As per the documentation, when using JSON API to upload image to Cloud Storage where ‘uploadType=media’, make sure the media is less than 5 MB and it does not contain metadata. If you have bigger media file or metadata, use ‘multipart’ or ‘resumable’ for ‘uploadType’. Here is an example of the upload method. If not, as Oliver commented, please provide any error or response information.