D
D
danilx5562021-03-23 09:10:47
Google Apps Script
danilx556, 2021-03-23 09:10:47

How to receive webhooks through google apps script and write data to google sheets?

Good afternoon.

I want to accept webhooks from the BotHelp service . The service sends data in JSON.

I poked around on the Internet and I think that doPost will suit me. Wrote code in apps script:

function doPost (e) {
  var ss = SpreadsheetApp.openById('1YQmHQ07iFfQpSD-KBUZeHpFWOjOcdBkzrEmPPL9Bwf0');
  var sheet = ss.getSheetByName('list');

  var dateTime = Utilities.formatDate(new Date(), "GMT+3", "dd.MM.yyy HH:mm:ss");
  var vkuid = e.parameter.user_id;
  sheet.appendRow([dateTime, vkuid]);
  return ContentService.createTextOutput("Done");
}


I start sending a webhook in the BotHelp service. The Google script receives it and adds a new row to the Google spreadsheet:
6059847e5a989677760103.png

But for some reason the script does not receive the user_id parameter, or it does not receive it in the right way to write it into the cell. Since the second column is empty in the Google spreadsheet.

I checked on the pipedream service, it's kind of a service that can accept webhooks.

There, all data is transferred normally and my required "user_id" parameter is:
60598616f3e92083255058.png

Please tell me how can I get the "user_id" parameter from the webhook in my google apps script and write it to the table. Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
danilx556, 2021-03-23
@danilx556

Found a solution with the help of Alexander Ivanov https://qna.habr.com/user/oshliaer , thanks a lot.
Here is the working code:

function doPost (e) {
  var ss = SpreadsheetApp.openById('1YQmHQ07iFfQpSD-KBUZeHpFWOjOcdBkzrEmPPL9Bwf0');
  var sheet = ss.getSheetByName('list');

  var dateTime = Utilities.formatDate(new Date(), "GMT+3", "dd.MM.yyy HH:mm:ss");
  var jsonString = e.postData.getDataAsString();
  var jsonData = JSON.parse(jsonString);
  var vkuid = jsonData.user_id;
  //var vkuid = e.parameter.user_id;
  sheet.appendRow([dateTime, vkuid]);
  return ContentService.createTextOutput("Done");
}

S
Sergey Sokolov, 2021-03-23
@sergiks

if( !e || !e.postData || !e.postData.contents) {
        console.log({title:"Bad POST data", e: e});
        return;
    }

    contents = JSON.parse(e.postData.contents);
    if (! contents) {
        console.log({title:"Contents failed to decode", e:e});
        return;
    }

    const vk_user_id = contents.user_id;  // может, так?

    // посмотрите что выводит в лог
    console.log(contents);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question