UrlFetchApp Post Variables Not being sent/received by php server - google-apps-script

var headers = {
"Accept": "application/json",
"Content-Type": "application/json"
};
var data = {
action: "test123"
};
var options = { "method":"POST",
"headers" : headers,
"followRedirects": false,
"validateHttpsCertificates": false,
"muteHttpExceptions" : true,
"contentType": "application/json",
"payload": JSON.stringify(data)
};
var requestURL = "http://requesturl.com/controller.php";
var response = UrlFetchApp.fetch(requestURL, options);
Logger.log(response.getContentText());
on the php server in controller.php
<?php
echo ($_POST['action']);
?>
I get nothing for the echo but I do get a 200 response code, any help would be much appreciated!!!!!!!!!

What result do you get trying the code:
var data = {
'action': 'test123'
};
var options = { "method":"POST",
"headers" : headers,
"followRedirects": false,
"validateHttpsCertificates": false,
"muteHttpExceptions" : true,
"contentType": "application/json",
"payload": data
};

Related

How to create post using Google My Business API - Google Apps Script

I can't figure out why I'm getting the below error when I attempt to create a post with the GMB API in Google Apps Script. I'm following this documentation https://developers.google.com/my-business/content/posts-data
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
"errorDetails": [
{
"code": 2,
"field": "summary",
"message": "Standard local post must have at least a media or summary."
}
]
}
]
}
}
Here is my script
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I tried the following adaption, but it did not work
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
payload: {
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Thanks in advance!
The request object needs to go into the payload. "payload" is a parameter of the options.
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var payload = {
"languageCode": "en-US",
"summary": "New Release!",
"callToAction": {
"actionType": "ORDER",
"url": "https://www.artivem.com/"
},
"media": [{
"sourceUrl": "https://untappd.akamaized.net/photos/2021_04_16/9999999999999999.jpg",
"mediaFormat": "PHOTO"
}]
}
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
if (response.getResponseCode() !== 200) {
console.log("Error Code: " + response.getResponseCode());
}
}

Using my personal clickup token to make a clickup api call from Google Apps Script

function getClickupTeam() {
let response = UrlFetchApp.fetch(clickupUrl + "team", {
"method": "GET",
"Authorization": clickupToken,
"muteHttpExceptions": true
})
Logger.log(response)
let json = JSON.parse(response);
Logger.log(json);
}
This URLFetchApp call returns {ECODE=OAUTH_017, err=Authorization header required} even though I am including my personal clickup token in the request. Am I missing something? Any help would be appreciated.
It looks like your request is malformed (be sure to check out the reference documentation for the UrlFetchApp.fetch(url, params) method.) The Authorization header should be in an explicit headers object. Plus, you don't need to set method to GET since its the default.
Something else to keep in mind for when you're making POST requests - Google Apps Script has this funny quirk where you have to define the Content-Type header using the contentType property. If you try to set that header in the headers object if will just get overridden by the default (application/x-www-form-urlencoded I believe).
So here's how you'd set up your GET request:
function getClickupTeam() {
let response = UrlFetchApp.fetch(clickupUrl + "team", {
"muteHttpExceptions": true,
"headers": {
"Authorization": clickupToken
}
}
console.log(response.getContentText());
let json = JSON.parse(response.getContentText());
console.log(json);
);
And for POST requests with a JSON payload you'd do something like this:
function getClickupTeam() {
let response = UrlFetchApp.fetch(clickupUrl + "team", {
"method": "POST",
"contentType": "application/json",
"muteHttpExceptions": true,
"headers": {
"Authorization": clickupToken
},
"payload": JSON.stringify({
"key": "value"
});
}
console.log(response.getContentText());
let json = JSON.parse(response.getContentText());
console.log(json);
);
While doing some research on the topic through https://clickup.com/api, I stumbled across some code. There are a couple of different ones for different things, I'd recommend the first, JavaScript (as that's whats closest to what your currently doing). In a comment you said it was for editing tasks so that's what this code is aimed for.
javascript
var request = new XMLHttpRequest();
request.open('PUT', 'https://api.clickup.com/api/v1/task/{task_id}');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', '"access_token"');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'name': 'New Task Name',
'content': 'New Task Content',
'assignees': {
'add': [
1
],
'rem': [
2
]
},
'status': 'Closed',
'priority': 3,
'due_date': '1508369194377'
};
request.send(JSON.stringify(body));
curl
curl --include \
--request PUT \
--header "Content-Type: application/json" \
--header "Authorization: "access_token"" \
--data-binary "{
\"name\": \"New Task Name\",
\"content\": \"New Task Content\",
\"assignees\": {
\"add\" : [
1
],
\"rem\" : [
2
]
},
\"status\": \"Closed\",
\"priority\": 3,
\"due_date\": \"1508369194377\"
}" \
'https://api.clickup.com/api/v1/task/{task_id}'
node.js
var request = require('request');
request({
method: 'PUT',
url: 'https://api.clickup.com/api/v1/task/{task_id}',
headers: {
'Content-Type': 'application/json',
'Authorization': '\'access_token\''
},
body: "{ \"name\": \"New Task Name\", \"content\": \"New Task Content\", \"assignees\": { \"add\": [ 1 ], \"rem\": [ 2 ] }, \"status\": \"Closed\", \"priority\": 3, \"due_date\": \"1508369194377\"}"
}, function (error, response, body) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
});
This is aimed for production let me know if you need mock server or debugging proxy

Mobiledevices: action missing

I am trying to perform a POST of the action, however, when I make the request I get code 400 speaking that the action value is missing.
my code:
function mobileAPIPOST() {
var response = UrlFetchApp.fetch(
"https://www.googleapis.com/admin/directory/v1/customer/my_customer/devices/mobile/fakexQ_fake0Z0dKFdSblfakeTnnfakel7IYwixfake4ddZfakeAIvnmu/action", {
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
"Content-Type": "application/json",
},
data: {
"action": "block"
},
muteHttpExceptions: true
});
}
I updated the code following the response from #TheMaster.
My updated code:
function mobileAPIPOST() {
var response = UrlFetchApp.fetch(
"https://www.googleapis.com/admin/directory/v1/customer/my_customer/devices/mobile/fakexQ_fake0Z0dKFdSblfakeTnnfakel7IYwixfake4ddZfakeAIvnmu/action", {
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
"Content-Type": "application/json",
},
payload: {
"action": "block"
},
muteHttpExceptions: true
});
}
error pointed out:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
UrlFetchApp doesn't have a data key parameter. Use payload instead.
Reference:
UrlFetchApp
Code Snippet:
UrlFetchApp.fetch(url,
{
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
},
contentType: 'application/json',
payload: JSON.stringify({
"action": "block"
}),
muteHttpExceptions: true
});

Create new Apps Script file with the Apps Script API - Error - Invalid JSON payload received

I'm getting the error:
Invalid JSON payload received
When trying to create a new Apps Script file with the Apps Script API.
How do I fix that error?
function createNewFile() {
var d,options,payload,response,theAccessTkn,url;
theAccessTkn = ScriptApp.getOAuthToken();
//See https://developers.google.com/apps-script/api/reference/rest/v1/projects/create
url = "https://script.googleapis.com/v1/projects";
d = new Date().toString().slice(0,10);
payload = {
"title": "AA_" + d
}
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"payload": JSON.stringify(payload)
};
response = UrlFetchApp.fetch(url,options);
Logger.log(response)
return response;
}
I have set the authorization scopes in the manifest file to avoid needing to add an OAuth library:
{
"timeZone": "America/New_York",
"oauthScopes": [
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.external_request"
],
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}
I needed to add "contentType": "application/json" to the options.
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"contentType": "application/json",
"payload": JSON.stringify(payload)
};

Node 'request' package, get string instead of object

let url = 'https://www.example.com';
let requestData = {
"key": {
"keyA": "value",
}
};
let options = {
url: url,
method: "POST",
headers: {
"Content-Type": "application/json",
},
json: requestData
};
request(options, function(err,httpResponse,result){});
How could I get the result as string instead of object?