官方套件 · 框架

從 Phoenix 發送即時事件與頻道授權

從 Elixir 發送 Hibira 事件,並在 Phoenix controller 簽署私有與 presence 頻道訂閱。不需要額外套件:HTTP API 以 HMAC-SHA256 簽名,用 :crypto 就能完成。

最快的方式:裝好 Hibira 外掛,貼上一段提示詞

在你的 AI 程式助手裝好外掛,再貼上提示詞。助手會幫你登入、需要時建立免費應用、寫好程式碼並送出測試事件。 GitHub ↗

  1. 安裝外掛

    claude plugin marketplace add hibira-io/agent-plugin
    claude plugin install hibira@hibira
  2. 貼上這段提示詞

    Add Hibira Phoenix (Req) to this project.
    Follow https://hibira.io/guides/phoenix, adapted to how this project is already set up.
    If I have no Hibira app yet, create a Free one that allows http://localhost so I can test right away.
    Keep the app key and secret in environment variables, add placeholders to .env.example, and never commit real values or send the secret to a browser.
    When you are done, send a test event, show me it arriving, and list the files you changed.
  • 瀏覽器與 App 以 pusher-js 或任何 Pusher 用戶端訂閱;Phoenix 只要一個簽名的 POST 就能發送。
  • 同一個 HMAC 也用來簽署頻道訂閱與 Live Chat 驗證訪客。

登入後,範例程式碼會自動帶入您的叢集主機。 登入

  1. 安裝

    # mix.exs
    {:req, "~> 0.5"}
  2. 發送事件

    defmodule MyApp.Hibira do
      @host "https://ws.hibira.io"
      defp env(k), do: System.fetch_env!(k)
      defp hmac(data), do: :crypto.mac(:hmac, :sha256, env("HIBIRA_SECRET"), data) |> Base.encode16(case: :lower)
    
      def trigger(channels, event, data) do
        path = "/apps/#{env("HIBIRA_APP_ID")}/events"
        body = Jason.encode!(%{name: event, channels: channels, data: Jason.encode!(data)})
        query = [
          auth_key: env("HIBIRA_KEY"),
          auth_timestamp: System.os_time(:second),
          auth_version: "1.0",
          body_md5: :crypto.hash(:md5, body) |> Base.encode16(case: :lower)
        ]
        signed = query |> Enum.sort() |> Enum.map_join("&", fn {k, v} -> "#{k}=#{v}" end)
        Req.post!(@host <> path, body: body, headers: [{"content-type", "application/json"}],
          params: query ++ [auth_signature: hmac("POST\n#{path}\n#{signed}")])
      end
    
      # The body of POST /pusher/auth, from socket_id and channel_name.
      def auth(socket_id, channel), do: %{auth: "#{env("HIBIRA_KEY")}:#{hmac("#{socket_id}:#{channel}")}"}
    end
  3. 簽署頻道訂閱

    # router.ex: post "/pusher/auth", PusherController, :auth
    def auth(conn, %{"socket_id" => socket_id, "channel_name" => "private-user-" <> id = channel}) do
      if to_string(conn.assigns.current_user.id) == id,
        do: json(conn, MyApp.Hibira.auth(socket_id, channel)),
        else: send_resp(conn, 403, "")
    end

開始之前

  • 應用程式的密鑰只會在建立應用程式或輪替密鑰時顯示一次。請只放在伺服器上,不要放進瀏覽器或遊戲的建置檔。
  • 私人頻道與 presence 頻道需要後端提供授權端點,用應用程式密鑰簽署訂閱,做法和 pusher-js 相同。
  • presence 頻道要簽署 "socket_id:channel:channel_data",並把 channel_data 跟 auth 一起回傳,與 Pusher 協定相同。

請使用儀表板中的應用程式 Key;Secret 只放在你的伺服器上。頻道、事件與授權端點的用法和 Pusher 完全相同。 免費建立帳號 →