Ben Collins
Ben Collins

Reputation: 321

How do I create a doPost(e) function in Apps Script project to capture HTTP POST data from web service?

I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

Upvotes: 8

Views: 42715

Answers (4)

vstepaniuk
vstepaniuk

Reputation: 868

Deployed versions https://script.google.com/macros/s/<id>/exec do not output to Logger.

Instead use the development version https://script.google.com/macros/s/<id>/dev?access_token=<your_token> as described here:

https://github.com/tanaikech/taking-advantage-of-Web-Apps-with-google-apps-script#how-to-use-dev-mode-from-outside and https://stackoverflow.com/a/57915963/3525368

Access token are vaild for 1 hour only

Upvotes: 0

Jack Brown
Jack Brown

Reputation: 5892

This is the code I used to post the data to my sheet:

function doPost(e) {
  Logger.log("I was called")
  if(typeof e !== 'undefined')
  Logger.log(e.parameter);
  var ss= SpreadsheetApp.openById("ID here")
  var sheet = ss.getSheetByName("Sheet2")
  sheet.getRange(1, 1).setValue(JSON.stringify(e))
  return ContentService.createTextOutput(JSON.stringify(e))
}

Used curl to make a post request and got echo of the data sent!

Upvotes: 15

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17651

Instead of using Logger.log() as a way to notify yourself if your calls made it through, try sending an email to yourself instead. This is the snippet:

function doPost(e) {
  if(typeof e !== 'undefined')

  MailApp.sendEmail({
     to: "[email protected]",
     subject: "Call Sucessful",
     htmlBody: "I am your <br>" +
               "DATA"
    });
}

Just allow the necessary permission if asked. If I'm not mistaken Logger.log is for script editor only and not for your production web apps.

Upvotes: 6

OblongMedulla
OblongMedulla

Reputation: 1595

Could try something like this? Also you might look @ this thread: doPost(e) does not return parameters but doGet(e) does?

function doPost(e) {
  
  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));
  
}

Upvotes: 2

Related Questions