# Realtime events from Sinatra

> Publish Hibira events, sign channel subscriptions and check webhooks from a Sinatra app with the pusher gem pointed at your Hibira host.

Source: https://hibira.io/guides/sinatra

Publish Hibira events, sign channel subscriptions and check webhooks from a Sinatra app with the pusher gem pointed at your Hibira host.

Package: pusher

- The pusher gem publishes events and signs private and presence channels.
- Webhooks are checked against the app secret before your code runs.

## 1. Install

```shell
bundle add pusher
```

## 2. Use it

```ruby
require "sinatra"
require "pusher"

HIBIRA = Pusher::Client.new(
  app_id: ENV.fetch("HIBIRA_APP_ID"), key: ENV.fetch("HIBIRA_APP_KEY"), secret: ENV.fetch("HIBIRA_APP_SECRET"),
  host: "ws.hibira.io", port: 443, use_tls: true
)

post "/orders/:id/ship" do
  HIBIRA.trigger("orders", "order.shipped", { id: params[:id].to_i })
  204
end

post "/pusher/auth" do
  halt 403 unless session[:user_id] # check the user may join params[:channel_name]
  content_type :json
  HIBIRA.authenticate(params[:channel_name], params[:socket_id]).to_json
end

post "/hibira/webhooks" do
  webhook = Pusher::WebHook.new(request, HIBIRA)
  halt 401 unless webhook.valid?
  webhook.events.each { |event| logger.info(event["name"]) }
  200
end
```

## Before you start

- The app secret is shown only once, when you create the app or rotate its secret. Keep it on your server, never in a browser or game build.
- On the Free plan, list every origin your pages load from in the app’s allowed origins (http://localhost:3000 while developing, then your domain). "*" needs a paid plan.

- [RubyGems](https://rubygems.org/gems/pusher)
