Как создать Viber-бота с помощью PHP
В ноябре 2016 года Viber внедрил публичные аккаунты (Viber public account, или просто PA). С их выходом стало доступно и api, которое позволяет:
Все это позволяет создать довольно неплохого бота, или же интегрировать бота в уже существующий проект, что вполне может улучшить качество взаимодействие с пользователями. Если вы уже создавали ботов для telegram или slack — то создать бота для Viber не составит большого труда.
Вступление
Еще некоторое время назад у меня появилась необходимость взаимодействовать с пользователями вайбера. Хотелось бы внедрить в свое приложение типовые диалоги с пользователями, а еще предоставлять «кнопочные диалоги» (в тех случаях когда пользователь видит несколько кнопок под чатом). Но на тот момент открытого (публичного) API для этого не было, и приходилось либо отказываться либо изворачиваться с граблями.
С релизом публичных аккаунтов (PA) ситуация изменилась, теперь мы можем создать более полноценное взаимодействие с «кнопочными диалогами» и нужными нам «конверсиями». Все это здорово, если не одно НО — нет SDK для PHP (ради справедливости, есть sdk для nodejs и python). Именно этот пробел я решил заполнить, и описать как можно создать простого бота на php, и за одно создать SDK.
Первые шаги
В форме вы указываете телефон, к которому будет выдан доступ к публичным аккаунтам, и спустя некоторое время вы получите сообщения формата «. You now have early access to Public Accounts. «. После чего вам необходимо перезапустить Viber-клиент и пройти следующие шаги:
Открыть раздел «Публичные аккаунты» (иконка вверху справа — )
Нажать на «создать аккаунт» (иконка внизу справа — )
На последнем шаге будет доступен выбор способа работы с сообщениями, выберите «api» и скопируйте ключ. (или его можно просто посмотреть на экране «редактирования информации» PA):
Для примера, мой ключ будет: 1111111111111111-2222222222222222-3333333333333333
Серверная часть
Для разработки бота и работы с Viber-API я использую небольшой SDK: https://github.com/Bogdaan/viber-bot-php. Он позволит опустить некоторые подробности взаимодействия c REST-api и построить некоторую логику нашего бота. Установим его:
Для начала нам необходимо зарегистрировать адрес вебхука — тот адрес по которому бекенд вибера будет доставлять нам сообщения от пользователей и некоторые другие события. Веб сервер, на котором будет расположен бот (и соотвественно вебхук) обязательно должен работать по https с корректным SSL сертификатом. Самоподписанный сертификат тут не подойдет, если его нет — попробуйте использовать letsencrypt.org.
И зарегистрируем вебхук выполнив файл:
Теперь, когда пользователь отправит сообщение, или зайдет в чат, по адресу вебхука будут отправлены запросы. Создадим файл bot.php :
Можно немного улучшить функционал бота и добавить логгирование. Сделаем это с помощью monolog:
Как получить токены для создания чат-бота в Телеграме, Вайбере и в Вконтакте?
Начну с того, что такое чат-бот, и зачем он нужен в социальных сетях. Бот — это программа, которая имитирует некоторые действия человека. Нужен он для того, чтобы можно автоматизировать рутинные задачи, ускорить их выполнение.
Они нужны там, где есть много похожих действий, которые сейчас выполняются руками (или не выполняются вовсе — просто потому что нет столько рук). Бот может принять заказ в интернет-магазине, прислать подборку видеороликов, посоветовать подходящие концерты или ближайший ресторан. Все действия с чат-ботом разворачиваются в диалоговом окне пользователя социальной сети.
Почти все известные социальные сети, учитывая потребности бизнеса, предоставляют возможность создания таковых. Таким образом, чат-бота можно создать в Телеграме, Вайбере и в Вконтакте. Для этого нужно сначала получить специальный токен от социальной сети – далее работать с этим токеном в любом бот-конструкторе – платном или бесплатно, развлекательном или не развлекательном. Именно для бизнес-целей можно использовать нашу бот-платформу-Index, предоставляющую готовые решения бронирования, лояльности, обратной связи, доставки и т.д. (бота там можно создать БЕСПЛАТНО за несколько минут, просто свяжитесь с нами).
Получение токена в Вконтакте
Получение токена в Телеграме
Получение токена в Вайбере
Надеюсь, эта статья была полезной для вас, и вы уже во всю экспериментируете над созданием крутых ботов, а если нужна в этом помощь, свяжитесь с нами!
Viber API Documentation 7.3.0
Docs / API / Viber REST API
Viber REST API
Get Started
In order to implement the API you will need the following:
Supported platforms
Bots are currently supported on iOS and Android devices running Viber version 6.5 and above and on desktop from version 6.5.3.
Important notes for bot developers:
Send and receive message flow
The following diagram describes the flow of sending and receiving messages by the account. All API requests and callbacks mentioned in the diagram will be explained later in this document.
Authentication token
The authentication token (also known as application key) is a unique and secret account identifier. It is used to authenticate request in the Viber API and to prevent unauthorized persons from sending requests on behalf of a bot. Each API request must include an HTTP Header called X-Viber-Auth-Token containing the account’s authentication token.
HTTP header
The authentication token is generated upon bot creation and can be viewed by the account’s admins in the “edit info” screen of their bot or on the Viber Admin Panel.
Note: Failing to send the authentication token in the header will result in an error with the missing_auth_token message.
Webhooks
Once you have your token you will be able to set your account’s webhook. This webhook will be used for receiving callbacks and user messages from Viber.
Setting the webhook will be done by calling the set_webhook API with a valid & certified URL. This action defines the account’s webhook and the type of events the account wants to be notified about.
For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. The certificate CA should be on the Sun Java trusted root certificates list.
Note that once you set your webhook the 1-on-1 conversation with your account will become available. To disable 1-on-1 conversation with your account you’ll need to remove your webhook – see removing your webhook below.
Viber’s API allows you to receive user names and photos. This has been updated to comply with privacy laws and allow developers who don’t make use of user names and photos as part of their service to opt out. If you don’t use user names photos, please opt-out to default values.
To set the request, pass send_name and send_photo flags with the set_webhook request.
Note: This feature will work if the user has allowed “Content Personalisation” (More → Privacy → personal data). If the user has disallowed content personalization, you will receive placeholder values.
Setting a Webhook
Resource URL
Post data
Post parameters
Set webhook Response
Response parameters
Event types filtering
Set webhook callback
For each set_webhook request Viber will send a callback to the webhook URL to confirm it is available. The expected HTTP response to the callback is 200 OK – any other response will mean the webhook is not available. If the webhook is not available the set_webhook response sent to the user will be status 1: invalidUrl.
Callback data
Callback parameters
| Name | Description | Possible values |
|---|---|---|
| event | Callback type – which event triggered the callback | webhook |
| timestamp | Time of the event that triggered the callback | Epoch time |
| message_token | Unique ID of the message |
Removing your webhook
Once you set a webhook to your bot your 1-on-1 conversation button will appear and users will be able to access it.
At the moment there is no option to disable the 1-on-1 conversation from the bot settings, so to disable this option you’ll need to remove the webhook you set for the account. Removing the webhook is done by Posting a set_webhook request with an empty webhook string.
Resource URL
Post data
Post parameters
| Name | Description |
|---|---|
| url | required. Account webhook URL to receive callbacks & messages from users. In this case, use an empty string to remove any previously set webhook |
Send Message
The send_message API allows accounts to send messages to Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot. (see subscribed callback for additional information). You can share your bot with the users via a deeplink.
Validation
Maximum total JSON size of the request is 30kb.
Can send up to 100 messages to a user in an hour (XX:00-XX:00) without reply, message count towards the limit is reset when a user replies to a message. Once the limit is reached, you will receive an error callback saying:
Resource URL
General send message parameters
The following parameters are available for all message types:
Message types
Below is a list of all supported message types with post data examples.
Text message
Post data
Post parameters
Picture message
Post data
Post parameters
Video message
Post data
Post parameters
File message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. file |
| media | URL of the file | required. Max size 50 MB. See forbidden file formats for unsupported file types |
| size | Size of the file in bytes | required |
| file_name | Name of the file | required. File name should include extension. Max 256 characters (including file extension). Sending a file without extension or with the wrong extension might cause the client to be unable to open the file |
Contact message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. contact |
| contact.name | Name of the contact | required. Max 28 characters |
| contact.phone_number | Phone number of the contact | required. Max 18 characters |
Location message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. location |
| location | Location coordinates | required. latitude (±90°) & longitude (±180°) within valid ranges |
URL message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. url |
| media | URL | required. Max 2,000 characters |
Sticker message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. sticker |
| sticker_id | Unique Viber sticker ID. For examples visit the sticker IDs page |
Rich Media message / Carousel content message
The Rich Media message type allows sending messages with pre-defined layout, including height (rows number), width (columns number), text, images and buttons.
Below you will find an exmaple of a Carousel Content Message, that allows a user to scroll through a list of items, each composed of an image, description and call to action button.
Each item on the list shown to the user is a button in the Rich Media message’s “Buttons” array. Sending one button is also permitted.
The parameters for Rich Media message and its buttons are also used for Keyboards. You can find additional information on them in the following article.
Notes:
Post data
Post parameters
Button element
| Name | Description | Possible values |
|---|---|---|
| Columns | Button column span. Default ButtonsGroupColumns | 1..ButtonsGroupColumns |
| Rows | Button row span. Default ButtonsGroupRows | 1..ButtonsGroupRows |
Keyboards
The Viber API allows sending a custom keyboard using the send_message API, to supply the user with a set of predefined replies or actions. The keyboard can be attached to any message type or sent on it’s on. Once received, the keyboard will appear to the user instead of the device’s native keyboard. The keyboards are fully customizable and can be created and designed specifically for the account’s needs. The client will always display the last keyboard that was sent to it.
Read the following article to learn more about keyboards.
Validation
Maximum total JSON size of the request is 30kb.
Resource URL
Post data
Keyboards can be attached to any message type and be sent and displayed together. To attach a keyboard to a message simply add the keyboard’s parameters to the message JSON.
The example below shows a keyboard sent with a text message (note that the keyboard doesn’t contain all optional values).
Broadcast Message
The broadcast_message API allows accounts to send messages to multiple Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot by sending a message to the bot.
Validation
Maximum total JSON size of the request is 30kb. The maximum list length is 300 receivers. The Broadcast API is used to send messages to multiple recipients with a rate limit of 500 requests in a 10 seconds window.
Resource URL
Post parameters
This API method uses the same parameters as the send REST API method with a few variations described below.
broadcast_list
This mandatory parameter defines the recipients for the message. Every user must be subscribed and have a valid user id. The maximum list length is 300 receivers. For example (this should be a part of the full JSON body):
Place holders
Broadcast message can contain place holders that will be replaced with receiver information (each receiver will get it’s own information). The place holders can appear anywhere in the message, even in tracking data. The list of the place holders:
Post example
Response
Response parameters
Response example
Get Account Info
The get_account_info request will fetch the account’s details as registered in Viber. The account admin will be able to edit most of these details from his Viber client.
Resource URL
Post data
Response
Response parameters
Get User Details
The get_user_details request will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the account regarding user’s actions. This request can be sent twice during a 12 hours period for each user ID.
Resource URL
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| id | Unique Viber user id | required. subscribed valid user id |
Response
Response parameters
Get Online
The get_online request will fetch the online status of a given subscribed account members. The API supports up to 100 user id per request and those users must be subscribed to the account.
Resource URL
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| ids | Unique Viber user id | required. 100 ids per request |
Response
Response parameters
Callbacks
Each callback will contain a signature on the JSON passed to the callback. The signature is HMAC with SHA256 that will use the authentication token as the key and the JSON as the value. The result will be passed as HTTP Header X-Viber-Content-Signature so the receiver can determine the origin of the message.
Re-try logic
In case the webhook is offline Viber will re-try to deliver the callback until HTTP status code 200 is received. There will be 2 retry attempts 2 second apart.
Input
Key (your bot’s authentication token):
Output
HTTP header
Subscribed
You will receive a subscribed event when unsubscribed users do the following:
Note: A subscribe event will delete any context or tracking_data information related to the conversation. This means that if a user had a conversation with a service and then chose to unsubscribe and subscribe again, a new conversation will be started without any information related to the old conversation.
Callback data
Callback parameters
Unsubscribed
The user will have the option to unsubscribe from the PA. This will trigger an unsubscribed callback.
Callback data
Callback parameters
Conversation started
Conversation started event fires when a user opens a conversation with the bot using the “message” button (found on the account’s info screen) or using a deep link.
This event is not considered a subscribe event and doesn’t allow the account to send messages to the user; however, it will allow sending one “welcome message” to the user. See sending a welcome message below for more information.
Once a conversation_started callback is received, the service will be able to respond with a JSON containing same parameters as a send_message request. The receiver parameter is not mandatory in this case.
Note: the conversation_started callback doesn’t contain the context parameter by default.
To add this paramater and determine its value, you can use a deeplink like this: viber://pa?chatURI=your_bot_URI&context=your_context
Callback data
Callback parameters
Sending a welcome message
The Viber API allows sending messages to users only after they subscribe to the account. However, Viber will allow the account to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.
The welcome message will be sent as a response to a conversation_started callback, which will be received from Viber once the user opens the conversation with the account. To learn more about this event and when is it triggered see Conversation started in the callbacks section.
Welcome message flow
Sending a welcome message will be done according to the following flow:
The welcome message will be a JSON constructed according to the send_message requests structure, but without the receiver parameter. An example welcome message would look like this:
Note: The welcome message should be sent as the body of the HTTP response to the conversation_started callback, and not to the send_message endpoint.
Message receipts callbacks
Viber offers message status updates for each message sent, allowing the account to be notified when the message was delivered to the user’s device ( delivered status ) and when the conversation containing the message was opened ( seen status ).
The seen callback will only be sent once when the user reads the unread messages, regardless of the number of messages sent to them, or the number of devices they are using.
If the message recipient is using their Viber account on multiple devices, each of the devices will return a delivered, meaning that several delivered callbacks can be received for a single message.
If Viber is unable to deliver the message to the client it will try to deliver it for up to 14 days. If the message wasn’t delivered within the 14 days it will not be delivered and no “delivered” or “seen” callbacks will be received for it.
Callback data
Delivered
Callback parameters
Failed callback
The “failed” callback will be triggered if a message has reached the client but failed any of the client validations.
Since some of the message validations take place on the server while the others take place on the client, some messages may only fail after reaching the client. In such cases the flow will be as follows:
Such message will not be displayed to the receiver and no “delivered” or “seen” callbacks will be returned for it.
Callback data
Callback parameters
Receive message from user
Callback data
Callback general parameters
Callback message parameters
The callback message parameters depend on the type of message. For each message type, only the relevant parameters will be received.
Message status
Once a 200 OK response is received from the PA, the message status will change to delivered on the user’s side. “Seen” status is not currently supported for messages sent from user to PA.
Error Codes
The following error codes will be returned with API responses. The status parameter will include the error code value while the status_message parameter will include the error name or a more specific string describing the error.
Note: Failing to send the authentication token in the header will result in an error with the missing auth_token message.
Viber API Documentation 7.3.0
Docs / API / Viber REST API
Viber REST API
Get Started
In order to implement the API you will need the following:
Supported platforms
Public Accounts/ bots are currently supported on iOS and Android devices running Viber version 6.5 and above and on desktop from version 6.5.3.
Send and receive message flow
The following diagram describes the flow of sending and receiving messages by the account. All API requests and callbacks mentioned in the diagram will be explained later in this document.
Authentication token
The authentication token (also known as application key) is a unique and secret account identifier. It is used to authenticate request in the Viber API and to prevent unauthorized persons from sending requests on behalf of a Public Account/ bot. Each API request must include an HTTP Header called X-Viber-Auth-Token containing the account’s authentication token.
HTTP header
The authentication token is generated upon account creation and can be viewed by the account’s admins in the “edit info” screen of their Public Account/ bot or on the Viber Admin Panel.
Note: Failing to send the authentication token in the header will result in an error with the missing_auth_token message.
Webhooks
Once you have your token you will be able to set your account’s webhook. This webhook will be used for receiving callbacks and user messages from Viber.
Setting the webhook will be done by calling the set_webhook API with a valid & certified URL. For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. This action defines the account’s webhook and the type of events the account wants to be notified about.
Once a set_webhook request is sent Viber will send a callback to the webhook to check its availability and return a response to the user.
Note that once you set your webhook the 1-on-1 conversation with your account will become available. To disable 1-on-1 conversation with your account you’ll need to remove your webhook – see removing your webhook below.
Viber’s API allows you to receive user names and photos. This has been updated to comply with privacy laws and allow developers who don’t make use of user names and photos as part of their service to opt out. If you don’t use user names photos, please opt-out to default values.
To set the request, pass send_name and send_photo flags with the set_webhook request.
Note: This feature will work if the user has allowed “Content Personalisation” (More → Privacy → personal data). If the user has disallowed content personalization, you will receive placeholder values.
Setting a Webhook
Resource URL
Post data
Post parameters
Set webhook Response
Response parameters
Event types filtering
Set webhook callback
For each set_webhook request Viber will send a callback to the webhook URL to confirm it is available. The expected HTTP response to the callback is 200 OK – any other response will mean the webhook is not available. If the webhook is not available the set_webhook response sent to the user will be status 1: invalidUrl.
Callback data
Callback parameters
| Name | Description | Possible values |
|---|---|---|
| event | Callback type – which event triggered the callback | webhook |
| timestamp | Time of the event that triggered the callback | Epoch time |
| message_token | Unique ID of the message |
Removing your webhook
Once you set a webhook to your Public Account/ bot your 1-on-1 conversation button will appear and users will be able to access it.
At the moment there is no option to disable the 1-on-1 conversation from the Public Account/ bot settings, so to disable this option you’ll need to remove the webhook you set for the account. Removing the webhook is done by Posting a set_webhook request with an empty webhook string.
Resource URL
Post data
Post parameters
| Name | Description |
|---|---|
| url | required. Account webhook URL to receive callbacks & messages from users. In this case, use an empty string to remove any previously set webhook |
Send Message
The send_message API allows accounts to send messages to Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the Public Account by pressing the subscribe button or by sending a message, or by sending a message to a bot (see subscribed callback for additional information).
Validation
Maximum total JSON size of the request is 30kb.
Resource URL
General send message parameters
The following parameters are available for all message types:
Message types
Below is a list of all supported message types with post data examples.
Text message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. text |
| text | The text of the message | required |
Picture message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. picture |
| text | Description of the photo. Can be an empty string if irrelevant | required. Max 120 characters |
| media | URL of the image (JPEG) | required. Max size 1 MB. Only JPEG format is supported. Other image formats as well as animated GIFs can be sent as URL messages or file messages |
| thumbnail | URL of a reduced size image (JPEG) | optional. Max size 100 kb. Recommended: 400×400. Only JPEG format is supported |
Video message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. video |
| media | URL of the video (MP4, H264) | required. Max size 50 MB. Only MP4 and H264 are supported |
| size | Size of the video in bytes | required |
| duration | Video duration in seconds; will be displayed to the receiver | optional. Max 180 seconds |
| thumbnail | URL of a reduced size image (JPEG) | optional. Max size 100 kb. Recommended: 400×400. Only JPEG format is supported |
File message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. file |
| media | URL of the file | required. Max size 50 MB. See forbidden file formats for unsupported file types |
| size | Size of the file in bytes | required |
| file_name | Name of the file | required. File name should include extension. Max 256 characters (including file extension). Sending a file without extension or with the wrong extension might cause the client to be unable to open the file |
Contact message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. contact |
| contact.name | Name of the contact | required. Max 28 characters |
| contact.phone_number | Phone number of the contact | required. Max 18 characters |
Location message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. location |
| location | Location coordinates | required. latitude (±90°) & longitude (±180°) within valid ranges |
URL message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. url |
| media | URL | required. Max 2,000 characters |
Sticker message
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| type | Message type | required. sticker |
| sticker_id | Unique Viber sticker ID. For examples visit the sticker IDs page |
Carousel content message
The Carousel Content Message type allows a user to scroll through a list of items, each composed of an image, description and call to action button.
Note: Carousel Content Message is supported on devices running Viber version 6.7 and above.
Post data
Post parameters
Button element
| Name | Description | Possible values |
|---|---|---|
| Columns | Button column span. Default ButtonsGroupColumns | 1..ButtonsGroupColumns |
| Rows | Button row span. Default ButtonsGroupRows | 1..ButtonsGroupRows |
Keyboards
The Viber API allows sending a custom keyboard using the send_message API, to supply the user with a set of predefined replies or actions. The keyboard can be attached to any message type or sent on it’s on. Once received, the keyboard will appear to the user instead of the device’s native keyboard. The keyboards are fully customizable and can be created and designed specifically for the account’s needs. The client will always display the last keyboard that was sent to it.
Read the following article to learn more about keyboards.
Validation
Maximum total JSON size of the request is 30kb.
Resource URL
Post data
Keyboards can be attached to any message type and be sent and displayed together. To attach a keyboard to a message simply add the keyboard’s parameters to the message JSON.
The example below shows a keyboard sent with a text message (note that the keyboard doesn’t contain all optional values).
Broadcast Message
The broadcast_message API allows accounts to send messages to multiple Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the Public Account by pressing the subscribe button or by sending a message, or by sending a message to a bot. The ability to send broadcast messages is only opened on application and approval from Viber account managers.
Validation
Maximum total JSON size of the request is 30kb. The maximum list length is 300 receivers. The Broadcast API is used to send messages to multiple recipients with a rate limit of 500 requests in a 10 seconds window.
Resource URL
Post parameters
This API method uses the same parameters as the send REST API method with a few variations described below.
broadcast_list
This mandatory parameter defines the recipients for the message. Every user must be subscribed and have a valid user id. The maximum list length is 300 receivers. For example (this should be a part of the full JSON body):
Place holders
Broadcast message can contain place holders that will be replaced with receiver information (each receiver will get it’s own information). The place holders can appear anywhere in the message, even in tracking data. The list of the place holders:
Post example
Response
Response parameters
Response example
Get Account Info
The get_account_info request will fetch the account’s details as registered in Viber. The account admin will be able to edit most of these details from his Viber client.
Resource URL
Post data
Response
Response parameters
Get User Details
The get_user_details request will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the account regarding user’s actions. This request can be sent twice during a 12 hours period for each user ID.
Resource URL
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| id | Unique Viber user id | required. subscribed valid user id |
Response
Response parameters
Get Online
The get_online request will fetch the online status of a given subscribed account members. The API supports up to 100 user id per request and those users must be subscribed to the account.
Resource URL
Post data
Post parameters
| Name | Description | Validation |
|---|---|---|
| ids | Unique Viber user id | required. 100 ids per request |
Response
Response parameters
Post to Public Chat
The post API allows the Public Account owner to post a message in the Public Account’s public chat.
Note: The post API is fully supported on Android and iOS versions 6.5.3 and above. Versions 6.5 and below support the post API for text and link messages only. Other message types (picture, video, etc.) will be converted and displayed as a link leading to the message’s media. Support for the post API on Viber’s desktop version is currently in beta phase and may not be fully compatible with all message types.
Validation
Maximum total JSON size of the request is 30kb.
Resource URL
Post data
The following example shows a post request of a text message. For other message types see possible message types below.
Post parameters
Possible message types
The type of the message will be set by the type parameter and the content of message will be sent according to same parameters and logic as send_message requests (see send message section for more details.
Note: This method does not support keyboard attachment.
Callbacks
Each callback will contain a signature on the JSON passed to the callback. The signature is HMAC with SHA256 that will use the authentication token as the key and the JSON as the value. The result will be passed as HTTP Header X-Viber-Content-Signature so the receiver can determine the origin of the message.
Re-try logic
In case the webhook is offline Viber will re-try to deliver the callback several times for up to an hour until HTTP status code 200 is received.
Input
Output
HTTP header
Subscribed
Before an account can send messages to a user, the user will need to subscribe to the account. Subscribing can take place in one of two ways:
Note: A subscribe event will delete any context or tracking_data information related to the conversation. This means that if a user had a conversation with a service and then chose to unsubscribe and subscribe again, a new conversation will be started without any information related to the old conversation.
Callback data
Callback parameters
Unsubscribed
The user will have the option to unsubscribe from the PA. This will trigger an unsubscribed callback.
Callback data
Callback parameters
Conversation started
Conversation started event fires when a user opens a conversation with the Public Account/ bot using the “message” button (found on the account’s info screen) or using a deep link.
This event is not considered a subscribe event and doesn’t allow the account to send messages to the user; however, it will allow sending one “welcome message” to the user. See sending a welcome message below for more information.
Once a conversation_started callback is received, the service will be able to respond with a JSON containing same parameters as a send_message request. The receiver parameter is not mandatory in this case.
Callback data
Callback parameters
Sending a welcome message
The Viber API allows sending messages to users only after they subscribe to the account. However, Viber will allow the account to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.
The welcome message will be sent as a response to a conversation_started callback, which will be received from Viber once the user opens the conversation with the account. To learn more about this event and when is it triggered see Conversation started in the callbacks section.
Welcome message flow
Sending a welcome message will be done according to the following flow:
The welcome message will be a JSON constructed according to the send_message requests structure, but without the receiver parameter. An example welcome message would look like this:
Note: The welcome message should be sent as the body of the HTTP response to the conversation_started event, and not to the send_message endpoint.
Message receipts callbacks
Viber offers message status updates for each message sent, allowing the account to be notified when the message was delivered to the user’s device ( delivered status ) and when the conversation containing the message was opened ( seen status ).
If the message recipient is using their Viber account on multiple devices, each of the devices will return a delivered and a seen status. This means that several callbacks can be received for a single message.
If Viber is unable to deliver the message to the client it will try to deliver it for up to 14 days. If the message wasn’t delivered within the 14 days it will not be delivered and no “delivered” or “seen” callbacks will be received for it.
Callback data
Delivered
Callback parameters
Failed callback
The “failed” callback will be triggered if a message has reached the client but failed any of the client validations.
Since some of the message validations take place on the server while the others take place on the client, some messages may only fail after reaching the client. In such cases the flow will be as follows:
Such message will not be displayed to the receiver and no “delivered” or “seen” callbacks will be returned for it.
Callback data
Callback parameters
Receive message from user
Callback data
Callback general parameters
Callback message parameters
The callback message parameters depend on the type of message. For each message type, only the relevant parameters will be received.
Message status
Once a 200 OK response is received from the PA, the message status will change to delivered on the user’s side. “Seen” status is not currently supported for messages sent from user to PA.
Error Codes
The following error codes will be returned with API responses. The status parameter will include the error code value while the status_message parameter will include the error name or a more specific string describing the error.
Note: Failing to send the authentication token in the header will result in an error with the missing auth_token message.











