Skip to content

Instantly share code, notes, and snippets.

@lattespirit
Created July 25, 2017 06:09
Show Gist options
  • Save lattespirit/3da8474bd50f44b3698f4e70e6183a15 to your computer and use it in GitHub Desktop.
Save lattespirit/3da8474bd50f44b3698f4e70e6183a15 to your computer and use it in GitHub Desktop.
Handle Github Webhook using PHP(Laravel/Lumen Framework)
<?php
namespace App\Http\Controllers;
use Log;
use Illuminate\Http\Request;
use Symfony\Component\Process\Process;
use Laravel\Lumen\Routing\Controller as BaseController;
class WebhookController extends BaseController
{
private $body;
private $request;
private $message;
private $gitHubEvent;
private $gitHubSignature;
public function __construct(Request $request)
{
$this->request = $request;
$this->prepareParameter();
}
public function index()
{
if ($this->isPostRequestValid()) {
$process = new Process('cd /your/repo/path && sudo git fetch origin && sudo git merge origin master');
$process->run();
if ($process->isSuccessful()) {
Log::info($process->getOutput());
$this->message = 'Code updated.';
} else {
Log::info($process->getErrorOutput());
$this->message = 'Something went wrong';
}
}
return $this->message;
}
private function isPostRequestValid()
{
if ($this->gitHubEvent !== 'push') {
Log::info('Github Repository Event Not ALLOWED');
$this->message = 'Github Repository Event Not ALLOWED';
return false;
}
$computedSignature = 'sha1=' . hash_hmac('sha1', $this->body, $_ENV['GITHUB_HOOK_SECRET_TOKEN']);
if (! hash_equals($computedSignature, $this->gitHubSignature)) {
Log::info('Github Signature NOT Match');
$this->message = 'Github Signature NOT Match';
return false;
}
return true;
}
private function prepareParameter()
{
$headers = $this->request->headers->all();
$this->gitHubEvent = $headers['x-github-event'][0] ?? null;
$this->gitHubSignature = $headers['x-hub-signature'][0] ?? null;
$this->body = $this->request->getContent() ?? '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment