# 從 Sinatra 發送即時事件

> 在 Sinatra 應用中，用指向你 Hibira 主機的 pusher gem 發送 Hibira 事件、簽署頻道訂閱並驗證 webhook。

Source: https://hibira.io/zh-tw/guides/sinatra

在 Sinatra 應用中，用指向你 Hibira 主機的 pusher gem 發送 Hibira 事件、簽署頻道訂閱並驗證 webhook。

Package: pusher

- pusher gem 可發送事件，並簽署私有與 presence 頻道。
- Webhook 會先以 App secret 驗證，再執行你的程式碼。

## 1. 安裝

```shell
bundle add pusher
```

## 2. 使用

```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
```

## 開始之前

- 應用程式的密鑰只會在建立應用程式或輪替密鑰時顯示一次。請只放在伺服器上，不要放進瀏覽器或遊戲的建置檔。
- Free 方案需要把頁面載入的每個來源都加進應用程式的「允許的來源」（開發時是 http://localhost:3000，之後是您的網域）。"*" 需要付費方案。

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