Compare

GitHub Webhook Handlers

The same webhook-verification logic implemented in Node.js, PHP, and Java — jump between matching sections to see how each language handles it.

GitHub Webhooks - Node.js

View full page →

What is GitHub Webhooks?

GitHub Webhooks allow you to receive real-time HTTP notifications when events occur in your repositories. This guide shows Node.js implementations using Express and vanilla HTTP with HMAC signature verification for secure automated deployments.


🟢 Node.js - Express Handler

Express server for handling GitHub webhooks.

import crypto from "crypto";
import express from "express";

const app = express();
const SECRET = "your_secret";

app.use(express.raw({ type: "application/json" }));

app.post("/webhook", (req, res) => {
  if (!verifySignature(req)) {
    return res.status(401).send("Invalid");
  }

  const event = req.headers["x-github-event"];
  if (event === "push") {
    require("child_process").exec("sh /path/to/deploy.sh");
  }

  res.send("OK");
});

app.listen(3000);

🔐 Node.js - Verify Signature

Verify GitHub webhook signature in Node.js.

function verifySignature(req) {
  const signature = req.headers["x-hub-signature-256"];
  const hmac = crypto.createHmac("sha256", SECRET);
  const digest = "sha256=" + hmac.update(req.body).digest("hex");
  return signature === digest;
}

Install & Run:

npm install express
node index.js

# Production
pm2 start index.js

Node.js - Vanilla (No Framework)

HTTP server without Express framework.

import crypto from "crypto";
import http from "http";

const SECRET = "your_secret";

http.createServer((req, res) => {
  if (req.method !== "POST" || req.url !== "/webhook") {
    res.writeHead(404);
    return res.end("Not Found");
  }

  let body = [];
  req.on("data", chunk => body.push(chunk));
  req.on("end", () => {
    const payload = Buffer.concat(body).toString();
    const signature = req.headers["x-hub-signature-256"];

    if (!verifySignature(signature, payload)) {
      res.writeHead(401);
      return res.end("Invalid");
    }

    if (req.headers["x-github-event"] === "push") {
      require("child_process").exec("sh /path/to/deploy.sh");
    }

    res.end("OK");
  });
}).listen(3001);

✅ Node.js - Vanilla Verify Signature

Signature verification for vanilla Node.js.

function verifySignature(signature, payload) {
  if (!signature) return false;

  const hmac = crypto.createHmac("sha256", SECRET);
  const digest = "sha256=" + hmac.update(payload).digest("hex");

  return signature === digest;
}

Run:

# Development
node server.js

# Production
pm2 start server.js

📦 Package.json

Required dependencies for Express version.

{
  "name": "github-webhook",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "express": "^4.18.0"
  }
}

⚙️ PM2 Setup

Run with PM2 process manager for production.

# Install PM2
npm install -g pm2

# Start application
pm2 start index.js --name github-webhook

# Auto-restart on boot
pm2 startup
pm2 save

# Monitor
pm2 logs github-webhook
pm2 monit

🔑 Environment Variables

Store secret securely using environment variables.

# .env file
SECRET=your_webhook_secret_here
PORT=3000
// Load environment variables
import dotenv from 'dotenv';
dotenv.config();

const SECRET = process.env.SECRET;
const PORT = process.env.PORT || 3000;

🐳 Docker Deployment

Containerize the Node.js webhook handler.

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]

Build and run:

docker build -t github-webhook-node .
docker run -p 3000:3000 -e SECRET=your_secret github-webhook-node

🌐 Nginx Reverse Proxy

Proxy webhook requests through Nginx.

server {
    listen 80;
    server_name webhook.example.com;

    location /webhook {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

🔧 Systemd Service

Run as a systemd service.

Create /etc/systemd/system/github-webhook.service:

[Unit]
Description=GitHub Webhook Handler
After=network.target

[Service]
Type=simple
User=nodejs
WorkingDirectory=/opt/webhook
ExecStart=/usr/bin/node /opt/webhook/index.js
Restart=on-failure
Environment=SECRET=your_secret

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable github-webhook
sudo systemctl start github-webhook

GitHub Webhooks - PHP

View full page →

What is GitHub Webhooks?

GitHub Webhooks allow you to receive real-time HTTP notifications when events occur in your repositories. This guide shows PHP implementation with HMAC signature verification for secure automated deployments on Apache and Nginx servers.


🐘 PHP - Native Handler

PHP webhook handler using native functions.

<?php
$secret = "your_secret";

// Read payload
$payload = file_get_contents("php://input");
$signature = $_SERVER["HTTP_X_HUB_SIGNATURE_256"] ?? "";

// Verify signature
$hash = "sha256=" . hash_hmac("sha256", $payload, $secret);
if (!hash_equals($hash, $signature)) {
    http_response_code(401);
    exit("Invalid signature");
}

// Handle event
$event = $_SERVER["HTTP_X_GITHUB_EVENT"] ?? "unknown";

if ($event === "push") {
    shell_exec("sh /path/to/deploy.sh");
}

echo "OK";
?>

🔐 PHP - Verify Signature

Signature verification function.

<?php
function verifyGitHubSignature($payload, $signature, $secret) {
    if (empty($signature)) {
        return false;
    }

    $hash = "sha256=" . hash_hmac("sha256", $payload, $secret);
    return hash_equals($hash, $signature);
}

// Usage
$payload = file_get_contents("php://input");
$signature = $_SERVER["HTTP_X_HUB_SIGNATURE_256"] ?? "";
$secret = "your_webhook_secret";

if (!verifyGitHubSignature($payload, $signature, $secret)) {
    http_response_code(401);
    exit("Invalid signature");
}
?>

📖 PHP - Parse JSON Payload

Parse and process webhook payload.

<?php
$payload = file_get_contents("php://input");
$data = json_decode($payload, true);

// Get repository information
$repo = $data['repository']['name'] ?? '';
$branch = $data['ref'] ?? '';
$pusher = $data['pusher']['name'] ?? '';

// Log webhook event
error_log("Webhook received: $repo, $branch by $pusher");

// Execute deployment
if ($branch === 'refs/heads/main') {
    shell_exec("cd /var/www/html && git pull origin main");
}
?>

✅ PHP - Complete Example

Full working PHP webhook handler with error handling.

<?php
// Configuration
$secret = getenv('WEBHOOK_SECRET') ?: 'your_secret';
$deploy_script = '/path/to/deploy.sh';
$log_file = '/var/log/github-webhook.log';

// Read payload
$payload = file_get_contents("php://input");
$signature = $_SERVER["HTTP_X_HUB_SIGNATURE_256"] ?? "";
$event = $_SERVER["HTTP_X_GITHUB_EVENT"] ?? "unknown";

// Log request
file_put_contents($log_file, date('Y-m-d H:i:s') . " - Event: $event\n", FILE_APPEND);

// Verify signature
$hash = "sha256=" . hash_hmac("sha256", $payload, $secret);
if (!hash_equals($hash, $signature)) {
    http_response_code(401);
    file_put_contents($log_file, "Invalid signature\n", FILE_APPEND);
    exit("Invalid signature");
}

// Handle push event
if ($event === "push") {
    $data = json_decode($payload, true);
    $branch = $data['ref'] ?? '';

    file_put_contents($log_file, "Push to: $branch\n", FILE_APPEND);

    // Execute deployment script
    $output = shell_exec("sh $deploy_script 2>&1");
    file_put_contents($log_file, "Deploy output: $output\n", FILE_APPEND);
}

http_response_code(200);
echo "OK";
?>

▶️ Run - Development

Run PHP development server.

# Start built-in server
php -S 0.0.0.0:8000

# Test webhook
curl -X POST http://localhost:8000/webhook.php \
  -H "X-GitHub-Event: push" \
  -d '{"ref":"refs/heads/main"}'

🪶 Run - Apache

Apache configuration for PHP webhook.

<VirtualHost *:80>
    ServerName webhook.example.com
    DocumentRoot /var/www/webhook

    <Directory /var/www/webhook>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/webhook_error.log
    CustomLog ${APACHE_LOG_DIR}/webhook_access.log combined
</VirtualHost>

Run - Nginx + PHP-FPM

Nginx configuration with PHP-FPM.

server {
    listen 80;
    server_name webhook.example.com;
    root /var/www/webhook;

    location /webhook.php {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

🔑 Environment Variables

Store secret in environment file.

Apache - Add to .htaccess:

SetEnv WEBHOOK_SECRET your_secret_here

Nginx - Add to site config:

fastcgi_param WEBHOOK_SECRET your_secret_here;

PHP-FPM - Add to pool config /etc/php/8.1/fpm/pool.d/www.conf:

env[WEBHOOK_SECRET] = your_secret_here

🐳 Docker Deployment

Containerize PHP webhook handler.

FROM php:8.1-apache
COPY webhook.php /var/www/html/
RUN chown -R www-data:www-data /var/www/html
EXPOSE 80

Build and run:

docker build -t github-webhook-php .
docker run -p 8000:80 -e WEBHOOK_SECRET=your_secret github-webhook-php

🔒 File Permissions

Set proper permissions for deployment script.

# Make deploy script executable
chmod +x /path/to/deploy.sh

# Give PHP user permission (if needed)
sudo chown www-data:www-data /path/to/deploy.sh

# Or add www-data to appropriate group
sudo usermod -aG deployers www-data

📝 Logging

Enhanced logging for debugging.

<?php
function logWebhook($message) {
    $log_file = '/var/log/github-webhook.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$timestamp] $message\n", FILE_APPEND);
}

// Log incoming request
logWebhook("Webhook received: " . $_SERVER["HTTP_X_GITHUB_EVENT"]);

// Log verification result
if (!verifySignature()) {
    logWebhook("ERROR: Signature verification failed");
} else {
    logWebhook("SUCCESS: Signature verified");
}
?>

View logs:

tail -f /var/log/github-webhook.log

GitHub Webhooks - Java

View full page →

What is GitHub Webhooks?

GitHub Webhooks allow you to receive real-time HTTP notifications when events occur in your repositories. This guide shows Java Spring Boot implementation with HMAC signature verification for secure automated deployments.


☕ Java - Basic Handler

Spring Boot REST controller for handling GitHub webhooks.

@RestController
public class WebhookController {
    private static final String SECRET = "your_secret";

    @PostMapping("/webhook")
    public String handle(HttpServletRequest req) throws IOException {
        String payload = readPayload(req);
        String signature = req.getHeader("X-Hub-Signature-256");

        if (!verifySignature(signature, payload)) {
            return "Invalid signature";
        }

        String event = req.getHeader("X-GitHub-Event");
        if ("push".equals(event)) {
            runDeployScript();
        }
        return "OK";
    }
}

📖 Java - Read Payload

Read the request body for signature verification.

private String readPayload(HttpServletRequest request) throws IOException {
    StringBuilder payload = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
        String line;
        while ((line = reader.readLine()) != null) {
            payload.append(line);
        }
    }
    return payload.toString();
}

🔐 Java - Verify Signature

Verify GitHub webhook signature using HMAC SHA-256.

private boolean verifySignature(String signature, String payload) {
    if (signature == null) return false;

    String expected = "sha256=" +
        Hex.encodeHexString(HmacUtils.hmacSha256(SECRET, payload));

    return expected.equals(signature);
}

Dependencies:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
</dependency>

🚀 Java - Deploy Script

Execute deployment script when webhook is received.

private void runDeployScript() {
    try {
        ProcessBuilder pb = new ProcessBuilder(
            "/bin/bash", "/path/to/deploy.sh"
        );
        pb.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

✅ Java - Complete Example

Full working Spring Boot webhook handler.

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacUtils;
import java.io.BufferedReader;
import java.io.IOException;

@RestController
public class GithubWebhookController {

    private static final String SECRET = "YOUR_WEBHOOK_SECRET";

    @PostMapping("/webhook")
    public String handleWebhook(HttpServletRequest request) throws IOException {

        // Read payload
        StringBuilder payload = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                payload.append(line);
            }
        }

        // Verify signature (X-Hub-Signature-256)
        String signature = request.getHeader("X-Hub-Signature-256");
        if (!verifySignature(signature, payload.toString())) {
            return "Invalid signature";
        }

        String event = request.getHeader("X-GitHub-Event");

        if ("push".equals(event)) {
            // Execute deployment script or command
            runDeployScript();
        }

        return "OK";
    }

    private boolean verifySignature(String signature, String payload) {
        if (signature == null) return false;

        String expected = "sha256=" +
                Hex.encodeHexString(HmacUtils.hmacSha256(SECRET, payload));

        return expected.equals(signature);
    }

    private void runDeployScript() {
        try {
            ProcessBuilder pb = new ProcessBuilder(
                "/bin/bash", "/path/to/deploy.sh"
            );
            pb.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

▶️ Run Application

Run the Spring Boot application.

# Run via JAR
java -jar target/yourapp.jar

Production Options:

  • Tomcat
  • Docker
  • systemd service

📦 Maven Dependencies

Add required dependencies to pom.xml.

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Apache Commons Codec for HMAC -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
    </dependency>
</dependencies>

⚙️ Application Properties

Configure server port in application.properties.

server.port=8080

🐳 Docker Deployment

Containerize the Spring Boot webhook handler.

FROM openjdk:17-slim
COPY target/webhook-handler.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

Build and run:

docker build -t github-webhook .
docker run -p 8080:8080 -e SECRET=your_secret github-webhook

🔧 Systemd Service

Run as a systemd service on Linux.

Create /etc/systemd/system/github-webhook.service:

[Unit]
Description=GitHub Webhook Handler
After=network.target

[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/webhook
ExecStart=/usr/bin/java -jar /opt/webhook/app.jar
Restart=on-failure

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable github-webhook
sudo systemctl start github-webhook