This gem will help you to quickly setup a route in your Rails application which listens to a GitHub webhook
Add this line to your application's Gemfile:
gem 'github_webhook'And then execute:
$ bundle install
First, configure a route to receive the github webhook POST requests.
# config/routes.rb
resource :github_webhooks, only: :create, defaults: { formats: :json }Then create a new controller:
# app/controllers/github_webhooks_controller.rb
class GithubWebhooksController < ActionController::Base
include GithubWebhook::Processor
def push(payload)
# TODO: handle push webhook
end
def webhook_secret(payload)
ENV['GITHUB_WEBHOOK_SECRET']
end
endAdd as many instance methods as events you want to handle in your controller. You can read the full list of events GitHub can notify you about.
First, install octokit, then run a rails console.
$ gem install octokit
$ rails consoleIn the rails console, add the WebHook to GitHub:
require "octokit"
client = Octokit::Client.new(:login => 'ssaunier', :password => 's3cr3t!!!')
repo = "ssaunier/github_webhook"
callback_url = "yourdomain.com/github_webhooks"
webhook_secret = "a_gr34t_s3cr3t" # Must be set after that in ENV['GITHUB_WEBHOOK_SECRET']
# Create the WebHook
client.subscribe "https://github.com/#{repo}/events/push.json", callback_url, secretThe secret is set at the webhook creation. Store it in an environment variable,
GITHUB_WEBHOOK_SECRET as per the example. It is important to have such a secret,
as it will guarantee that your process legit webhooks requests, thus only from GitHub.
You can have an overview of your webhooks at the following URL:
https://github.com/:username/:repo/settings/hooks