Chat with PHP and Laravel
As the Programmable Chat API is set to sunset in 2022, we will no longer maintain these chat tutorials.
Please see our Conversations API QuickStart to start building robust virtual spaces for conversation.
Programmable Chat will no longer be available or supported after July 25, 2022. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here.
If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.
Ready to implement a chat application using Twilio Programmable Chat Client?
This application allows users to exchange messages through different channels, using the Twilio Programmable Chat API. On this example, we'll show how to use this API features to manage channels and to show it's usages.
Properatiは不動産の買い手と売り手をリアルタイムにつなぐ手助けをするモバイルメッセージングAppを構築しました。 さらに詳しく。
For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.
トークンの生成
In order to create a Twilio Programmable Chat client, you will need an access token. This token holds information about your Twilio Account and Programmable Chat API keys.
新しい AccessToken
を作成し、これに ChatGrant
を提供することにより、このトークンを生成します。新しい AccessToken オブジェクトは、Twilio クレデンシャルを使用して作成されます。
Laravel では、AccessToken
オブジェクトをコントローラーにインジェクトするプロバイダーを作成する必要があります。TwilioChatGrantProvider.php
内部の ChatMessagingGrant
についても同じです。これらのオブジェクトの使用方法については、次のステップで紹介します。
We can generate a token, now we need a way for the chat app to get it.
トークン生成コントローラー
On our controller we expose the endpoint responsible for providing a valid token using this parameter:
identity
: ユーザー自身を識別します
AccessToken
オブジェクトを使用してトークンを生成したら、AccessTokenのメソッド token.toJWT()
を使用して文字列としてトークンを取得できます。 そうしたら、トークンをJSONエンコーディングされた文字列として返すだけです。
Now that we have a route that generates JWT tokens on demand, let's use this route to initialize our Twilio Chat Client.
Initializing the Programmable Chat Client
クライアントはエンドポイントにPOSTリクエストを発行することで新しいトークンを取得します。
With the token we can create a new Twilio.AccessManager
, and initialize our Twilio.Chat.Client
.
Now that we've initialized our Chat Client, lets see how we can get a list of channels.
チャンネルリストの取得
After initializing the client we can call the getPublicChannelDescriptors
method to retrieve all visible channels. This method returns a promise which we use to show the list of channels retrieved on the UI.
Next, we need a default channel.
一般チャンネルに参加する
このアプリケーションは、起動時に「General Channel」という名前のChannelに参加しようとします。 このChannelが存在しない場合、その名前でChannelを作成します。 このチャンネルが存在しない場合は、その名前でチャンネルを 1 つ作成します。このサンプルアプリケーションでは、公開チャネルの挙動を紹介していますが、ChannelクライアントではプライベートChannelを作成して招待の処理を行ったりといったことも可能です。
ご注意: アプリケーションが起動するたびに新しい一般チャネルを作成したくないので、一般チャンネルには一意な名前を設定します。
ここで、Channelイベントをいくつかリッスンしてみましょう。
チャンネルイベントをリスニングする
続いて、Channelイベントをリッスンします。 今回の場合は、リスナーに下記のイベントを設定しています。
messageAdded
:接続しているチャンネルに他のメンバーがメッセージを送信する場合。typingStarted
:接続しているチャンネルで他のメンバーがメッセージを入力している場合。typingEnded
:接続しているチャンネルで他のメンバーがメッセージの入力を中止した場合。memberJoined
:接続しているチャンネルに他のメンバーが参加する場合。memberLeft
:接続しているチャンネルから他のメンバーが退出する場合。
個々のイベントを処理するためにそれぞれの関数を登録します。
クライアントも同様にイベントを生成します。 このイベントを同様にリッスンできるようにする方法を見ていきましょう。
クライアントイベントをリスニングする
Just like with channels we can register handlers for events on the Client:
channelAdded
:チャンネルがクライアントに表示されるようになった場合。channelRemoved
:チャンネルがクライアントに表示されなくなった場合。tokenExpired
:提供されたトークンの有効期限が切れた場合。
ここで実際のチャットアプリケーションが用意できましたが、複数Channelを使用してもっと面白いものを作ってみましょう。
チャンネルを作成する
ユーザーが「+ Channel」リンクをクリックすると、新規のChannel名を入力できるテキストフィールドが表示されます。 Channelの作成は、friendlyName
キーを持つオブジェクトでcreateChannel
を呼び出すだけで簡単に行えます。 Programmable ChatドキュメントのChannelセクションで一覧されている追加のオプションを伴ってChannelを作成できます。
続いて、Channel間を切り替える方法を見ていきましょう。
他のChannelに参加する
サイドバーからチャンネルの名前をタップすると、そのチャンネルが selectedChannel
として設定されます。selectChannel
メソッドは選択したチャンネルへの参加および selectedChannel
の設定を行います。
いつか、ユーザーはChannelを削除したいと思うでしょう。 これを行う方法を見ていきましょう。
チャンネルを削除する
Channelの削除は、追加よりも簡単です。 アプリケーションは、"delete current channel"リンクによって、ユーザーにChannelを削除できるようにします。Twilioから実際にChannelを削除するのに必要なことは、削除しようとしているChannelのdelete
メソッドを呼ぶことだけです。 Channel
オブジェクトの他のメソッドと同様、successハンドラーを設定できるプロミスを返します。
That's it! We've just implemented a simple chat application for PHP using Laravel.
次はどこでしょうか?
Twilio を使う PHP 開発者であれば、他のチュートリアルも調べてみてください。
ウェブページのボタンを押して、電話を介して訪問者をライブサポートまたはセールス担当者に接続します。
音声通話または SMS テキストメッセージを介して調査を実施し、ユーザーから構造化データを迅速に収集します。
これは役に立ちましたか?
このチュートリアルをお読みいただき、ありがとうございます。ご意見やご感想などございましたら、ぜひお聞かせください。@twilio へツイートいただき、ご意見をお知らせください。
ヘルプが必要ですか?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.