PHPackages                             avplab/viber-api - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. avplab/viber-api

ActivePackage[API Development](/categories/api)

avplab/viber-api
================

Viber Api supplies comfortable way to deal with Viber Rest API and Viber Bot creation

v1.1.0(5y ago)18MITPHPPHP &gt;=7.0.0CI failing

Since Sep 25Pushed 5y ago1 watchersCompare

[ Source](https://github.com/avplab/viber-api)[ Packagist](https://packagist.org/packages/avplab/viber-api)[ Docs](http://github.com/avplab/viber-api)[ RSS](/packages/avplab-viber-api/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (5)Used By (0)

ViberApi
========

[](#viberapi)

The ViberApi gives an ability to create fully functional php bots for Viber, based on Viber REST API.

Installation
------------

[](#installation)

Install the component by using [Composer](https://getcomposer.org). Update your project's `composer.json` file to include dependency.

```
"require": {
    "avplab/viber-api": "^1.0.0"
}

```

Usage
-----

[](#usage)

To create any bot, the package provides two base classes `Callback\Request` and `Client`.

### Registration

[](#registration)

Run the following script once to register your webhook(bot). It could be run locally.

```
#register.php

namespace EchoBot;

use AvpLab\ViberApi\Callback\Request;
use AvpLab\ViberApi\Client;

$token = '';
$name = 'Echo Bot';
$url = 'https://webhook.url';

$client = new Client($token, $name);

$client->setWebhook(
    $url,
    [
        Request::DELIVERED,
        Request::SEEN,
        Request::FAILED,
        Request::CONVERSATION_STARTED,
        Request::SUBSCRIBED,
        Request::UNSUBSCRIBED,
        Request::WEBHOOK,
        Request::MESSAGE
    ]
);

```

### Code

[](#code)

Once you are done with registration you can write the code of the bot

```
namespace EchoBot;

use AvpLab\ViberApi\Client;
use AvpLab\ViberApi\Callback\Request;
use AvpLab\ViberApi\Message\TextMessage;

/**
 * The Echo bot will reply with the same message it received
 */

$request = new Request();
$client = new Client('', 'Echo Bot');

// when user starts the conversation or was subscribed (by deep link)
if ($request->isConversationStarted()) {
    if ($request->getData()->subscribed) {
        // user is already subsribed on the bot
        $message = new TextMessage('Welcome back !');
    } else {
        // new user
        $message = new TextMessage('Welcome ! I will respond with the same message');
    }
    // response with welcome message
    $client->responseWelcomeMessage($message);
}

// User sent the text message to the bot
if ($request->isMessageText()) {
    // response to the user(sender) with the same message as received
    $client->sendMessage($request->getMessageSenderId(), new TextMessage($request->getMessageText()));
}

```

### Get request from API

[](#get-request-from-api)

The `Request` provides all the information about callback-request from the Viber API to your server. You can trust the request data, as it is verified for authenticity (see [X-Viber-Content-Signature](https://developers.viber.com/docs/api/rest-bot-api/#callbacks)). If for some reason the request cannot be processed, a `BadRequestException` will be thrown.

### Send request to API

[](#send-request-to-api)

To send requests to the API, the `Client` object is used(the request is sent based on cURL). If for some reason the request does not reach the API, a `ServerErrorResponseException` exception will be thrown. If the API received the request, but for some reason responded with an error (see API errors), an `ApiException` exception will be thrown.

#### Messages

[](#messages)

The API is using term "message" as request body. Message is a JSON which has predefined structure(see the API docs). Viber describes several types of messages: `text`, `picture`, `video`, `contact`, `rich-media`, `file`, `sticker`, `location` and `url`. To prepare the specific message for sending to the API, you have to create an object of one of the predefined classes:

- TextMessage
- PictureMessage
- VideoMessage
- ContactMessage
- RichMediaMessage
- FileMessage
- StickerMessage
- UrlMessage

### Keyboards

[](#keyboards)

Each message may contain a keyboard. To add the keyboard use the `Keyboard` objects(see Keyboard methods for details).

### API

[](#api)

*AvpLab/Callback/Request*

The request object which contains all the info sent by Viber API

- *isWebhook()* - the callback was sent on `webhook` event
- *isSubscribed()* - the callback was sent on `subscribed` event
- *isUnsubsribed()* - the callback was sent on `unsubscribed` event
- *isConversationStarted()* - the callback was sent on `conversation_started` event
- *isDelivered()* - the callback was sent on `delivered` event
- *isSeen()* the - callback was sent on `seen` event
- *isFailed()* - the callback was sent on `failed` event
- *isMessage()* - the callback was sent on `message` event. User sent a message to Public Account(aka PA)
- *isMessageText()* - the `text` message was sent to PA
- *isMessagePicture()* - the `picture` message was sent to PA
- *isMessageVideo()* - the `video` message was sent to PA
- *isMessageFile()* - the `file` message was sent to PA
- *isMessageSticker()* - the `sticker` message was sent to PA
- *isMessageUrl()* - the `url` message was sent to PA
- *isMessageLocation()* - the `location` message was sent to PA
- *isMessageContact()* - the `contact` message was sent to PA
- *getEvent()* - returns the callback event name, which triggered the callback
- *getTimestamp()* - returns the time of event
- *getMessageToken()* - returns Unique ID of the message
- *getMessage()* - returns the message data
- *getMessageText()* - returns the message.text string
- *getMessageTrackingData()* - returns the message.tracking\_data string
- *getMessageSender()* - returns the sender data of the message
- *getMessageSenderId()* - returns the sender.id
- *getConversationContext()* - returns the context string of the callback triggered by `convestation_started` event. Any additional parameters added to the [deep link](https://developers.viber.com/docs/tools/deep-links) used to access the conversation passed as a string.
- *getConversationUser()* - returns the user's data, who triggered the conversation.
- *getData()* - returns the callback request data

*AvpLab/Client*

The http client which communicates with Viber API.

- \_\_construct(string $token, string $senderName, string $senderAvatar = null)

    - $token - the authentication token which was provided during the creation of account
    - $senderName - the bot's name
    - $senderAvatar - the bot's avatar url
- setWebhook(string $url, array $eventTypes = \[\], bool $sendName = true, bool $sendPhoto = true) - register the webhook(used once when configuring the bot)

    - $url - the URI of the bot
- removeWebhook() - unregister the webhook
- getToken() - returns the configured token
- getSenderName() - returns the bot's name
- getSenderAvatar() - returns the bot's avatar url
- sendMessage(string $receiver, Message $message, bool $withSender = true) - sends the message to the Viber API

    - $receiver - Id of receiver( Usually gets from request-&gt;getMessageSenderId() )
    - $message - Message object(see [Messages](#Messages) section for details)
    - $withSender - Include the bot's name and avatar configured for the client into the message
- broadcastMessage(array $broadcastList, Message $message, bool $withSender = true) - broadcast the message to several receivers

    - $broadcastList - array of receivers Id
    - $message - Message object(see [Messages](#Messages) section for details)
    - $withSender - Include the bot's name and avatar configured for the client into the message
- getAccountInfo() - returns the info of the account that bot communicated with
- getUserDetails(string $userId) - returns the info about the user

    - userId - Id of the user
- getOnline($ids) - returns the list with online statuses of selected users

    - ids - array of users Id
- responseWelcomeMessage(Message $message, bool $withSender = true) - send a response to the Viber API with the message. Is used when `conversation_started` event's callback is handled.

    - $message - Message object(see [Messages](#Messages) section for details)
    - $withSender - Include the bot's name and avatar configured for the client into the message

### Framework

[](#framework)

To simplify the bot's creation and make the code cleaner there is also a framework provided.

#### Usage

[](#usage-1)

```
#index.php

namespace EchoBot;

use AvpLab\ViberApi\Framework\Bot;
use EchoBot\Controller\IndexController;

$bot = new Bot('', 'Echo Bot');

$bot->onConversationStarted([IndexController::class, 'conversationStarted'])
    ->onMessage('/', [IndexController::class, 'index'])
    ->run();

```

```
#Controller/IndexController.php
