Subscription failed using Stripe API in Google Apps Script - javascript

I'm trying to make an add-on using Google Apps Script & Stripe where user can subscribe for an item as an yearly subscription. Every time I purchase the subscription from Stripe checkout, I get error like this,
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: #45b5a607",
"param": "#45b5a607",
"type": "invalid_request_error"
}
}
When I check the log in Stripe Dashboard I get the POST body like this,
{
"items": "[Ljava.lang.Object",
"#45b5a607": null,
"customer": "cus_Dix0eSYM5qP0kx"
}
This is my code in Google Apps Script,
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var customer = {
'email': customerEmail,
'source': token
};
var optCreate = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : customer,
'muteHttpExceptions' : true
};
var createCustomer = UrlFetchApp.fetch(urlCreate, optCreate);
var respCreate = JSON.parse(createCustomer.getContentText());
var customerId = respCreate.id;
if (customerId == null) { return "Error"; }
var data = {
"customer" : customerId,
"items" : [
{
"plan" : "plan_Diuw7CdAGcSrhm"
}
]
};
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : data,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
var resp = JSON.parse(response.getContentText());
Logger.log(resp);
I think I must be doing something wrong in my data JSON object. The items field is not working correctly that's why POST body is weird. What is the correct way here?

You need to stringify the payload.
var options = {
'method' : 'post',
"headers" : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : JSON.stringify(data),
'muteHttpExceptions' : true
};

It looks like you're POSTing JSON data, but Stripe's API does not accept JSON — you need to use form encoding. i.e your code needs to set data to be in this format:
items[0][plan]=plan_CvVNfwZ4pYubYg&customer=cus_Diygqj4wAq6L9T
You can refer to cURL examples in Stripe's API docs for this. Generally you should use an official library to simplify making API requests, but that may not be possible with Apps Script.

Related

"401 Error Code" using google script app fetch post

Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}
I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.

Send twilio whatsapp message from Google App Script

I am trying to send a WhatsApp message using twilio's HTTP endpoint but it is failing with error
{"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}
I did not purposefully add 'content-type': 'application/x-www-form-urlencoded' as the URLFetchApp adds the same automatically.
function sampletTextMessage(){
var ACCOUNT_SID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var ACCOUNT_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var options = {
"method" : "post",
'headers' : {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN),
},
'payload' :{
'body' : 'Your Twilio code is 1238432',
'to' : 'whatsapp:+91XXXXXXXXX3',
'from': 'whatsapp:+1XXXXXXXXX6',
},
'muteHttpExceptions' : true
};
var url="https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
var response = UrlFetchApp.fetch(url,options);
Logger.log(response);
}
It looks like your case is wrong, capitalize To, From, and Body.
Reference:
How to Send SMS from a Google Spreadsheet
var payload = {
"To": to,
"Body" : body,
"From" : "YOURTWILIONUMBER"
};

How do I add a value to a custom field on Trello using google scripts?

Using google scripts and Trello API, I am having trouble sending a put request to set the options on a pre-defined trello custom field.
This is what the trello API suggests for javascript, however since I'm using google scripts, I'm constrained to use google's "UrlFetchApp" class, how would I do so?
var url = "https://api.trello.com/1/cards/{idCard}/customField/{idCustomField}/item?token={yourToken}&key={yourKey}";
var data = {value: { number: "42" }};
fetch(url, { body: JSON.stringify(data), method: 'PUT', headers: {'content-type': 'application/json'}})
.then((resp) => resp.json()) //Error would occur here
.then((data) => console.log(JSON.stringify(data, null, 2)))
.catch((err) => console.log(JSON.stringify(err, null, 2)))
https://developers.trello.com/reference#customfielditemsid
If I were to attempt to run that example in google scripts I get error:
Syntax error. (line 135, file "Code")
So I've attempted to use URLFetchApp:
var url = "https://api.trello.com/1/cards/" + cardId + "/customField/{customFieldIDHere}/item?token={TokenHere}&key={KeyHere}";
var data = {value: { "text": "42" }};
var payload = {"customField" : data};
var options = {"method" : "put",
"payload" : payload};
UrlFetchApp.fetch(url,options); //Error would occur here
https://developers.google.com/apps-script/reference/url-fetch
But I get this error:
"Request failed for https://api.trello.com returned code 400. Truncated server response: Invalid value for custom field type"
I've also attempted to do var mData = JSON.stringify(data); and use mData in the options but still get the same error unfortunately
The problem was, that I didn't need var = {customField" : data}
Instead, all I needed to do was:
var options = {
"method" : "put",
"payload" : JSON.stringify(data),
"contentType": "application/json"
};

Getting code 500 back from Sling API JSON Post

So it seems that Sling (sling.is) updated their API, but never sent out an email with warning or information, so my script is broken. The end goal of my code (which worked fine prior to their update) is to simply post shifts for employees to Sling upon a company event being approved.
I'm running all of this code in google apps script since I need to pull data from a spreadsheet to create the shifts. The code works by first "adding" the shifts to the system, and then secondly "publishing" those shifts so all employees can see them. I managed to figure out how to fix the first part as it seems they switched some basic syntax around. But I can't for the life of me figure out how to fix the second (publishing) part.
Sling doesn't offer any support for their API, so I thought posting here would be my next best bet.
Here's the error I'm receiving:
"Request failed for https://api.sling.is/v1/shifts/sync returned code
500. Truncated server response: {"message": "Oops, an unexpected error occured."} (use muteHttpExceptions option to examine full response)
(line 257, file "Code")"
//CREATE SHIFTS ON SLING
//This is pulling data from google spreadsheet cells
var staff = getByName('Attendants', row);
var start = Utilities.formatDate(getByName('Date', row),
ss.getSpreadsheetTimeZone(), "YYYY-MM-dd") + "T" +
Utilities.formatDate(getByName('Starting Time of Attendants', row),
ss.getSpreadsheetTimeZone(), "H:mm") + ":00.000-04";
var end = Utilities.formatDate(getByName('Date', row),
ss.getSpreadsheetTimeZone(), "YYYY-MM-dd") + "T" +
Utilities.formatDate(getByName('Ending Time of Attendants', row),
ss.getSpreadsheetTimeZone(), "H:mm") + ":00.000-04";
var notes = getByName('City', row) + ", " + getByName('Event Type', row)
var payload = {
"available": true,
"dtstart": start,
"dtend": end,
"location": {
"id": 1022310
},
"position": {
"id": 1022302
},
"summary": notes,
"user": {
"id": 1
}
};
var headers = {
"Authorization" : "9e632842f4e61927336337f1aa65b75c"
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers,
'payload' : JSON.stringify(payload)
};
for(i=1; i<=staff; i++){
UrlFetchApp.fetch("https://api.sling.is/v1/shifts?
ignoreConflicts=false&publish=true", options);
}
// All of that ^^ works
var payloadtwo =
{
"summary": notes
};
var optionstwo = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers,
'payload' : JSON.stringify(payloadtwo)
};
UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
I even tried completely removing the payload (body) parameter from the JSON options.
var payloadtwo = {
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04"
};
var optionstwo = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers
};
UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
and then it says
"Request failed for https://api.sling.is/v1/shifts/sync returned code 400.
Truncated server response:
{"message": "Publishing requires either a date range or a list of
events"} (use muteHttpExceptions option to examine full response)
(line 256, file "Code")"
Sling API's "documentation" for the shift posting feature is available here: https://api.sling.is/#/shifts/post_shifts_sync
Any help would be greatly appreciated.
From the API document in your question, it seems that the request body is an object including an array. And it seems that the key is event. So could you please try this modified script? When you run this, please set notes and headers.
Modified script :
var payloadtwo = {
"event": [ // or "Event"
{
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04",
}
]
};
var optionstwo = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payloadtwo),
'headers': headers,
'muteHttpExceptions': true,
};
var res = UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
Logger.log(res)
Note :
If the error occurs, please modify from 'payload': JSON.stringify(payloadtwo), to 'payload': payloadtwo, and run it again.
I couldn't try to test because I have no account. So if this script occurs the error, please tell me. I would like to think of other modification points.
Edit 1 :
Modified script :
var payloadtwo = [
{
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04",
}
];
var optionstwo = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payloadtwo), // or payloadtwo
'headers': headers,
'muteHttpExceptions': true,
};
var res = UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
Logger.log(res)

"JSON_PARSING_ERROR: Unexpected character (d) at position 0." when sending GCM request from GAS

This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};

Categories