Friends Chat (text + Reverb)

REST API, real-time events, Unity & Unreal integration

Friends Chat API (text + real-time)



Direct text chat between accepted friends, friend groups (up to 16 members), and clan channels in the same game. REST for history and sending; Laravel Reverb (Pusher-compatible WebSocket) for live delivery.

Developer page: Chat API
Postman: Extended collection → folder Chat (Friends DM)
Unity script: public/downloads/unity/IDCChatManager.cs
Unreal: public/downloads/unreal/IDCChatClient.h / .cpp

Requirements



RuleDetail
AuthGame session Authorization: Bearer {access_token} (same as shop, inventory, etc.)
FriendshipGET/POST /api/v1/friendships — status must be accepted for DM and group invites (each member must be friend of creator)
Group2–16 members, same game, POST /chat/conversations/group
ClanClan members only, one chat room per clan, POST /chat/conversations/clan — see also Clan Hub (roles, invites, presence)
Blocked / pendingCannot open DM or send messages
Mute penaltyUser can read; POST …/messages returns 403
Game scopeUsers must share the same game_id

Friend presence (lobby / party / group invite)



GET /api/v1/friendships/presence — same signals as Clan Hub presence:

FieldMeaning
statusonline \in_match \offline
last_seen_atFrom game_users.last_login_at
match_keyActive match if player joined /matches/.../join (Redis)

Query (optional):

  • user_ids[] — subset of accepted friends only (ignored if not a friend).

  • include_self=1 — adds data.self for your own row (useful before creating a group).


  • Response data.friends[] includes friendship_id for each row.

    Use this to grey out offline friends, show “in match”, or pre-select online friends for POST /chat/conversations/group and shared match_key party flow.

    Match session (partida) — not friends-only



    For in-match text (TDM, public lobbies, Photon-style rooms), use /api/v1/matches, not friend group chat.

    TopicBehavior
    Ticket issuerPanel signs tickets requested by your trusted backend via POST /api/v1/server/matches/ticket with the game's gp_ server secret. Body: game_id, internal player_id, match_key, optional team_id.
    AccessPlayer Bearer + a five-minute ticket bound to the same game/player/match/team. Knowing match_key is insufficient. No friendship required.
    CreateHost player calls POST /api/v1/matches with Bearer and JSON match_key, join_ticket (issued with team_id: null). Omit member_user_ids or send []; non-empty lists return 403.
    JoinEach player, including the host, sends Bearer and JSON join_ticket, team_id, voice_enabled, optional voice_provider to POST /matches/{matchKey}/join. Team must match the ticket; voice requires team and provider.
    ChannelsAll (data.chat.all) — whole match. Team (data.chat.team) — created when a player joins with team_id.
    Send messagePOST /chat/conversations/{conversation_id}/messages — use all or team conversation_id from create/join.
    Real-timeReverb private channel private-chat.conversation.{id} per conversation (subscribe to both if you use both).
    VoiceTeam-only via match join — see MATCH_VOICE_E2E.md and Voice API.

    Full flow, production URLs, and E2E checks: MATCH_VOICE_E2E.md.

    The backend requests tickets and relays them to their owners; it does not use gp_ as a player Bearer. There is no S2S match-create endpoint in this contract: the authorized host player creates the panel session before other players join. For a team join, the host needs a team ticket in addition to its null-team create ticket. The field is join_ticket in the JSON body; neither a field named ticket nor a ticket header is read. See the exact ticket contract.

    Server setup (local)



  • 1. .env: BROADCAST_CONNECTION=reverb and REVERB_* variables (see .env.example).

  • 2. php artisan migrate

  • 3. php artisan serve

  • 4. php artisan reverb:start


  • Production (nginx → Reverb on 8082)



    Set in .env (generate unique REVERB_APP_* per environment; do not copy from local):

    VariableTypical production value
    APP_URLhttps://gamepanel.idcgames.com
    BROADCAST_CONNECTIONreverb
    REVERB_APP_IDapp id (string)
    REVERB_APP_KEYpublic key for clients
    REVERB_APP_SECRETsecret (server only)
    REVERB_HOSTpublic hostname clients use (same as panel domain)
    REVERB_PORT443 if clients use wss via nginx; use 8082 only if WS is exposed on that port
    REVERB_SCHEMEhttps (or http behind internal only)
    REVERB_SERVER_HOST127.0.0.1 when nginx proxies to localhost
    REVERB_SERVER_PORT8082 (process listen port behind nginx)

    Nginx on the panel must proxy /app (WebSocket clients) and /apps (Laravel broadcasting HTTP API) to http://127.0.0.1:8082. Without /apps, POST …/messages can return 500 (Pusher error: ).

    After deploy: php artisan migrate --force and php artisan config:cache.

    Start Reverb (Linux, from project root):

    nohup php artisan reverb:start --host=127.0.0.1 --port=8082 >> storage/logs/reverb.log 2>&1 &


    If REVERB_SERVER_HOST / REVERB_SERVER_PORT are already set in .env, this is equivalent:

    nohup php artisan reverb:start >> storage/logs/reverb.log 2>&1 &


    Use supervisor/systemd in production instead of nohup when possible; restart after deploy.

    REST endpoints



    All under /api/v1/chat, middleware: auth.api, update.session, check.penalties (global game penalties). Send messages also use check.communication (mute).

    GET /api/v1/chat/realtime-config



    Returns WebSocket settings for the client:

    {
    "success": true,
    "data": {
    "enabled": true,
    "broadcaster": "reverb",
    "auth_endpoint": "http://localhost:8000/api/v1/chat/broadcasting/auth",
    "key": "local-reverb-key",
    "ws_host": "localhost",
    "ws_port": 8080,
    "ws_scheme": "http",
    "force_tls": false
    }
    }


    GET /api/v1/chat/conversations?per_page=20



    Paginated inbox: friend info, last_message, unread_count, channel (e.g. private-chat.conversation.12).

    POST /api/v1/chat/conversations



    Body:

    { "friend_user_id": 42 }


    Creates or returns the direct thread with that friend.

    POST /api/v1/chat/conversations/group



    Body:

    {
    "name": "Party Alpha",
    "member_user_ids": [12, 34],
    "group_key": "optional-stable-id-for-match-party"
    }


    Creator is added automatically. Every member_user_ids entry must be an accepted friend of the creator. Max 16 members. Reusing the same group_key reopens/syncs the same group thread.

    POST /api/v1/chat/conversations/clan



    Body:

    { "clan_id": 5 }


    Opens the clan chat (created on first access). Participants are synced from current clan_user rows. Non-members receive 422.

    GET /api/v1/chat/conversations/{conversationId}



    Single conversation summary.

    GET /api/v1/chat/conversations/{conversationId}/messages?per_page=50&before_id=



    Message history, newest first. Use before_id to load older pages.

    POST /api/v1/chat/conversations/{conversationId}/messages



    Body:

    {
    "body": "Hello!",
    "client_message_id": "optional-uuid-for-idempotency"
    }


  • Max length: 2000 characters.

  • Re-sending the same client_message_id returns the existing message (no duplicate).


  • POST /api/v1/chat/conversations/{conversationId}/read



    Body:

    { "message_id": 99 }


    Updates read cursor for unread_count.

    Real-time (Reverb)



    ItemValue
    ProtocolPusher-compatible (same as Laravel Echo + pusher-js)
    Private channelprivate-chat.conversation.{conversationId}
    Event namemessage.sent
    AuthPOST /api/v1/chat/broadcasting/auth with Bearer token

    Auth body (form or JSON, Laravel accepts both):

    {
    "socket_id": "1234.5678",
    "channel_name": "private-chat.conversation.12"
    }


    Event payload (broadcastWith):

    {
    "message": {
    "id": 100,
    "conversation_id": 12,
    "sender_id": 5,
    "sender_username": "PlayerA",
    "body": "Hello!",
    "client_message_id": "abc-123",
    "created_at": "2026-04-08T12:00:00.000000Z"
    }
    }


    On the wire, Pusher wraps this as event message.sent on the subscribed channel.



  • 1. Login → store access_token.

  • 2. Ensure friendship is accepted (/api/v1/friendships).

  • 3. POST /chat/conversations with friend_user_id → store conversation.id and channel.

  • 4. GET …/messages for UI history.

  • 5. GET /chat/realtime-config → connect WebSocket to ws_host:ws_port with app key.

  • 6. Before subscribe: call auth_endpoint with Bearer + socket_id + channel_name.

  • 7. Subscribe to private channel; listen for message.sent.

  • 8. Send new lines via POST …/messages (do not rely only on WS for sending).


  • ---

    Unity integration



    1. Prerequisites



  • Unity 2020.3 LTS+

  • Newtonsoft.Json (com.unity.nuget.newtonsoft-json) — already required by IDCGamesAPIManager.cs

  • Copy IDCChatManager.cs into your project (namespace IDCGames.API)

  • After login, pass the same access_token into IDCChatManager.SetAccessToken(token)


  • 2. REST (built into IDCChatManager)



    var chat = GetComponent();
    chat.SetAccessToken(apiManager.AccessToken);

    // Open DM with friend (game user id from friendships API)
    var conv = await chat.OpenConversationAsync(friendGameUserId);

    // History
    var page = await chat.GetMessagesAsync(conv.id);

    // Send
    var sent = await chat.SendMessageAsync(conv.id, "Hello!", clientMessageId: Guid.NewGuid().ToString());

    // Mark read
    await chat.MarkReadAsync(conv.id, sent.id);


    Use OnChatError / returned success flags for 403 mute or 422 friendship errors.

    3. Real-time (Reverb / Pusher protocol)



    Unity has no built-in Echo. Use a Pusher-compatible client:

  • 1. Call GetRealtimeConfigAsync() from IDCChatManager (or duplicate the GET).

  • 2. Add a Pusher client for .NET compatible with custom host/port, for example:

  • - pusher-websocket-dotnet (configure cluster/host from realtime-config).
  • 3. Implement authorizer: HTTP POST to auth_endpoint with headers:

  • - Authorization: Bearer {access_token}
    - Body: socket_id, channel_name (e.g. private-chat.conversation.12)
  • 4. Subscribe to the channel name from the conversation response (channel field, without duplicating the private- prefix if your library adds it automatically).

  • 5. Bind event message.sent and deserialize the message object into your UI model.


  • Tip: If you skip WebSockets in a first build, poll GET …/messages every few seconds; switch to Reverb when ready.

    4. UI wiring (suggested)



  • Friends list from /api/v1/friendships?status=accepted → open chat sets friend_user_id.

  • One chat window per conversation_id.

  • On message.sent, append line if conversation_id matches active tab; bump unread otherwise.

  • Call MarkReadAsync when the user focuses the chat and sees the latest message.


  • ---

    Unreal Engine integration



    1. Prerequisites



  • Enable plugins: HTTP, Json, WebSockets (for real-time later)

  • Copy IDCChatClient.h / IDCChatClient.cpp into your game module

  • Module dependencies: HTTP, Json, JsonUtilities


  • 2. REST (Blueprint-friendly)



    Create UIDCChatClient (or use your existing IDCGamesAPIManager token):

  • 1. SetAccessToken / SetApiBaseUrl (e.g. http://localhost:8000)

  • 2. OpenConversation(FriendUserId) → bind OnConversationOpened

  • 3. LoadMessages(ConversationId) → bind OnMessagesLoaded

  • 4. SendChatMessage(ConversationId, Body, ClientMessageId) → bind OnMessageSent

  • 5. MarkConversationRead(ConversationId, MessageId)


  • All requests send Authorization: Bearer … like other GamePanel APIs.

    3. Real-time (Reverb)



  • 1. GET /api/v1/chat/realtime-config — parse key, ws_host, ws_port, auth_endpoint.

  • 2. Open WebSocket to Reverb (Pusher wire protocol) with the app key.

  • 3. On socket_id from the server, POST to auth_endpoint with Bearer token and channel_name.

  • 4. Subscribe to private-chat.conversation.{id}.

  • 5. Parse incoming JSON for event message.sent and update UChatWidget.


  • Unreal does not ship a full Pusher client; many teams use REST send + WS receive with a small parser for Pusher frames, or a third-party plugin. Minimum viable: polling LoadMessages until WS is integrated.

    4. Errors



    HTTPMeaning
    401Invalid/expired token — refresh session
    403Mute / communication restriction
    404Unknown conversation or not a participant
    422Friendship not accepted, blocked, or validation error

    ---

    Friendship API (reminder)



    Chat uses game user ids from the friendships API:

  • GET /api/v1/friendships?status=accepted

  • POST /api/v1/friendships — request

  • POST /api/v1/friendships/{id}/accept


Postman: set collection variable friend_user_id to the friend's game_users.id before Open Conversation With Friend.

Testing



php artisan test --filter=Chat


Covers: DM, mute, broadcast auth, 3-player group, clan with 3 members, stranger blocked from clan chat.

Manual: Extended Postman → login → set friend_user_id → Chat (Friends DM) folder in order.

After deploy run:

php artisan migrate



RevocaciĂłn de acceso a clanes (2026-10-17)



Los clientes deben suscribirse al valor channel devuelto por la API, sin construirlo a partir del ID. Los chats de clan usan private-chat.conversation.{id}.{membershipVersion}; la versión cambia al cambiar los miembros. Los canales simples de los ejemplos anteriores continúan para chats directos y grupos, pero ya no autorizan chats de clan. Tras un cambio de miembros, los miembros restantes deben volver a consultar la conversación y suscribirse al canal actual. Salir, ser expulsado, ser vetado o disolver el clan elimina también el acceso HTTP y la autorización de nuevas suscripciones. Los canales anteriores dejan de recibir nuevos mensajes del clan.