Skip to content
Buba Suma edited this page Jun 11, 2016 · 2 revisions

Using Pusher

Integrating Pusher with simplechat is very easy.

Get your free API keys

Create an account, and make a note of your app_id, app_key and app_secret.

Trigger events from your server

In the example below we trigger an event named new_message to Pusher on a channel called simplechat with the senderId and receiverId of the message.

namespace common\models;

//...
use Pusher;

class Message extends \bubasuma\simplechat\db\Message
{
    /**
     * @inheritDoc
     */
    public static function create($userId, $contactId, $text)
    {
        $errors = parent::create($userId, $contactId, $text);
         if ( empty($errors) ) {
             $options = [
                 'cluster' => 'APP_CLUSTER',
                 'encrypted' => true
             ];
             $pusher = new Pusher(
                 'APP_KEY',
                 'APP_SECRET',
                 'APP_ID',
                 $options
             );
             $pusher->trigger(
                 'simplechat',
                 'new_message', 
                 ['senderId' => $userId, 'receiverId' => $contactId]
             );
             return [];
         }
        return $errors;
    }
}

Subscribe to a Channel and listen events

Include the Pusher Client library

Include the pusher-js script tag on your page.

<script src="//js.pusher.com/3.1/pusher.min.js"></script>

Subscribe to simplechat and listen new_message

Now you can define callback that bind to new_message event on simplechat channel, coming in via the connection to Pusher:

var $messenger = $('#messenger');
var $conversations = $('#conversations');
var pusher = new Pusher('APP_KEY', {
    cluster: 'APP_CLUSTER',
    encrypted: true
});
var channel = pusher.subscribe('simplechat');
channel.bind('new_message', function(data) {
    if ($conversations.yiiSimpleChatConversations('widget').user.id == data.receiverId) {
        $conversations.yiiSimpleChatConversations('load', 'new');
        if ($conversations.yiiSimpleChatConversations('widget').current.contact.id == data.senderId) {
            $messenger.yiiSimpleChatMessages('load', 'new');
        }
    }
});