官方包 · 框架
从 Phoenix 发送实时事件与频道授权
从 Elixir 发送 Hibira 事件,并在 Phoenix controller 中签署私有和 presence 频道订阅。无需额外的包:HTTP API 使用 HMAC-SHA256 签名,用 :crypto 即可完成。
ReqHex: req ↗
最快的方式:装好 Hibira 插件,粘贴一段提示词
在你的 AI 编程助手装好插件,再粘贴提示词。助手会帮你登录、需要时创建免费应用、写好代码并发送测试事件。 GitHub ↗
安装插件
claude plugin marketplace add hibira-io/agent-plugin claude plugin install hibira@hibira粘贴这段提示词
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 验证访客。
登录后,示例代码会自动填入您的集群主机。 登录
安装
# mix.exs {:req, "~> 0.5"}发送事件
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签署频道订阅
# 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 完全相同。 免费创建账号 →