import pymysql
import pymysql.cursors
from flask import Flask, request
app = Flask(__name__)
# Connect to the MySQL database
connection = pymysql.connect(
host='hostname',
user='username',
password='password',
db='database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Extract the endpoint secret from the request headers
endpoint_secret = request.headers.get('X-Endpoint-Secret')
# Validate the endpoint secret
if endpoint_secret != 'YOUR_ENDPOINT_SECRET':
return 'Unauthorized', 401
# Extract the event data from the request body
event = request.get_json()
# Save the event data to the MySQL database
try:
with connection.cursor() as cursor:
sql = 'INSERT INTO events (data) VALUES (%s)'
cursor.execute(sql, (json.dumps(event)))
connection.commit()
except pymysql.Error as e:
return f'MySQL error: {e.args[1]}', 500
# Send an HTTP 200 response
return 'OK', 200
require 'sinatra'
require 'json'
require 'mysql2'
client = Mysql2::Client.new(
host: "hostname",
username: "username",
password: "password",
database: "database"
)
error Mysql2::Error do
status 500
"MySQL error: #{env['sinatra.error'].message}"
end
post '/webhook' do
# Extract the endpoint secret from the request headers
endpoint_secret = request.env["HTTP_X_ENDPOINT_SECRET"]
# Validate the endpoint secret
if endpoint_secret != "YOUR_ENDPOINT_SECRET"
status 401
return "Unauthorized"
end
request.body.rewind
data = JSON.parse(request.body.read)
begin
client.query("INSERT INTO events (data) VALUES ('#{data.to_json}')")
rescue Mysql2::Error => e
status 500
return "MySQL error: #{e.message}"
end
"OK"
end
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const app = express();
app.use(bodyParser.json());
const connection = mysql.createConnection({
host: 'hostname',
user: 'username',
password: 'password',
database: 'database'
});
app.post('/webhook', (req, res) => {
// Extract the endpoint secret from the request headers
const endpoint_secret = req.get('X-Endpoint-Secret');
// Validate the endpoint secret
if (endpoint_secret !== 'YOUR_ENDPOINT_SECRET') {
res.status(401).send('Unauthorized');
return;
}
// Extract the event data from the request body
const event = req.body;
// Save the event data to the MySQL database
connection.query(
'INSERT INTO events (data) VALUES (?)',
[JSON.stringify(event)],
(error) => {
if (error) {
console.error(error);
res.status(500).send('MySQL error');
return;
}
console.log('Event saved to database');
}
);
// Send an HTTP 200 response
res.sendStatus(200);
});
app.listen(3000, () => {
console.log('Webhook listening on port 3000');
});
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
)
func main() {
http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
// Extract the endpoint secret from the request headers
endpointSecret := r.Header.Get("X-Endpoint-Secret")
// Validate the endpoint secret
if endpointSecret != "YOUR_ENDPOINT_SECRET" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract the event data from the request body
var event interface{}
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// Save the event data to the MySQL database
if err := saveEvent(event); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Send an HTTP 200 response
w.WriteHeader(http.StatusOK)
})
http.ListenAndServe(":3000", nil)
}
func saveEvent(event interface{}) error {
// Create a new MySQL connection
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s",
os.Getenv("MYSQL_USERNAME"),
os.Getenv("MYSQL_PASSWORD"),
os.Getenv("MYSQL_HOSTNAME"),
os.Getenv("MYSQL_PORT"),
os.Getenv("MYSQL_DATABASE"),
)
db, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer db.Close()
// Convert the event data to JSON
data, err := json.Marshal(event)
if err != nil {
return err
}
// Execute the INSERT statement
_, err = db.Exec("INSERT INTO events (data) VALUES (?)", data)
return err
}