Webhook.
Suena como lo que pasa cuando te cruzas con una araña y un pirata. Sin embargo, en el mundo de Internet, los webhooks son algo completamente diferente. Los webhooks ayudan a conectar los servicios.
Dejame explicar.
Digamos que tenemos dos servicios hipotéticos. Uno es un servicio que genera datos y el otro que recopila y organiza esos datos.
Los desarrolladores del primer servicio pensaron: “Hombre, nuestra plataforma es tan útil. Demos a los usuarios la posibilidad de reenviar datos en tiempo real a otros servicios ".
Pensaron los desarrolladores del segundo servicio. "Caray, sería fantástico si nuestros usuarios pudieran importar datos más fácilmente". Entonces, agregaron webhooks para recibir datos en tiempo real de un servicio como el primer servicio.
Ahora, como usuario, usas ambos servicios. Ahora tiene el poder en sus manos para conectarlos.
La mejor manera de explicarlo es con un ejemplo del mundo real.

Ejemplo del mundo real
En un proyecto reciente, conecté un sensor de IoT a una hoja de Google Docs. Solo me tomó unos 10 minutos. Les voy a mostrar lo mismo ahora mismo.
Primero comencemos configurando la hoja de Google.
- Crea una nueva hoja

- Una vez que esté allí, vaya a Herramientas y haga clic en Editor de secuencias de comandos

- Debería abrir una nueva ventana que se parece a esto:

- Copia y pega este codigo. Lo explicaré después de que hagamos eso.
//this is a function that fires when the webapp receives a POST requestfunction doPost(e) { //Return if null if( e == undefined ) { console.log("no data"); return HtmlService.createHtmlOutput("need data"); } //Parse the JSON data var event = JSON.parse(e.postData.contents); var data = event.data;
//Get the last row without data var sheet = SpreadsheetApp.getActiveSheet(); var lastRow = Math.max(sheet.getLastRow(),1); sheet.insertRowAfter(lastRow); //Get current timestamp var timestamp = new Date(); //Insert the data into the sheet sheet.getRange(lastRow + 1, 1).setValue(event.published_at); sheet.getRange(lastRow + 1, 2).setValue(data.temperature); sheet.getRange(lastRow + 1, 3).setValue(data.humidity); sheet.getRange(lastRow + 1, 4).setValue(data.pm10); sheet.getRange(lastRow + 1, 5).setValue(data.pm25); sheet.getRange(lastRow + 1, 6).setValue(data.tvoc); sheet.getRange(lastRow + 1, 7).setValue(data.c02); SpreadsheetApp.flush(); return HtmlService.createHtmlOutput("post request received");}
Ahora, entendamos todo.
function doPost(e) {
Es la función a la que se llama en un evento POST. Considere este script como un servidor web. Lo estamos enviando datos a una dirección específica (que tendremos en un minuto caliente)
e es el objeto de la llamada HTTP. Tendrá los datos que le enviamos. Por tanto, es una buena idea comprobar si es NULL. Si es así, no es necesario ejecutar el script.
Si tenemos datos válidos, cambiémoslos de una cadena a JSON utilizable. Puede usar la función favorita de todos JSON.parse
para hacerlo.
var event = JSON.parse(e.postData.contents);
Recuerde, la estructura de los datos determinará cómo los procesará. Es posible que deba ejecutar JSON.parse
varias veces dependiendo de qué tan anidados estén sus datos y en qué formato están.
Una vez que tenga sus datos, ¡es hora de ponerlos en el lugar correcto!
//Get the last row without datavar sheet = SpreadsheetApp.getActiveSheet();var lastRow = Math.max(sheet.getLastRow(),1);sheet.insertRowAfter(lastRow);
Estas tres llamadas lo llevarán a la primera fila disponible comenzando en la fila 1 (dejando la fila 0 para las etiquetas de las columnas).
Luego, finalmente, colocamos los datos en la fila a la que pertenece:
sheet.getRange(lastRow + 1, 1).setValue(event.published_at);
Donde el primer parámetro de sheet.getRange
es la fila y el segundo es la columna. Puede usar la setValue
función para configurar lo que desee en esa celda en particular.
Por cierto, la inspiración para este código vino de esta publicación.
Frio. Entonces tenemos un guión. ¿Cómo lo llamamos?

- Presiona ese botón Publicar

- Hacer clic
Deploy as a web app

- Cambie la configuración para que coincida con la captura de pantalla a continuación. Luego haga clic en
Deploy

- Es posible que aparezca una pantalla que le pide que actualice sus permisos. Hacer clic
Review Permissions

- Haga clic en
Advanced
y luego haga clic enGo to
me> in the bottom left.
- Finally, click
Allow
- In the last screen, copy your Webhook URL!

Test it
Now we can test if everything works by using Postman. If you haven’t played with Postman yet, it’s a great graphical user interface for curl
.
- Install Postman. You may need an account to go further.
- Once inside, create a new request. Name it so you know it belongs to this Google Docs webhook
- Click
body
and enter the following test code:
{ "event": "gdxg", "data": { "temperature": 21 }, "coreid": "zczxvz", "published_at": "zcvzxcvx"}
- Finally, click that blue
Send
button.
- Go back to your excel sheet and see the magic!

Now we’re cooking with gas!

Conclusion
I hope you’ve gotten the above example to work. Luckily for you, there’s a lot less to worry about once you get this part up and running!
To recap, we’ve talked about webhooks and why they’re used. You should be feeling confident at this point to go and set up some of your own. If you’re still feeling intimidated, I recommend using services like Zapier or IFTTT. (They’re shiny front ends for APIS and Webhooks already available.)
Last but not least check out the full post where I integrate hardware and web in one awesome project.
Happy webhooking!