что такое uri в вайбере
Как сделать ссылку на Viber?
Простой 14 комментариев
Example: Sending a message with the text “Hello” to +42333 tg:msg?text=Hello&to=+42333
Note that the to parameter will only work if you have that user in your contacts. Otherwise nothing happens when you click the link.
У меня в 2020 сработало следующее:
И на ПК, и на смартфоне (и Андроид и iOS).
Добавлю новостей из 2021 🙂
Чтобы открылся чат с указанным номером я использую одну ссылку для Андроида и Айоса, ПК и МОБ такого вида:
При нажатии на неё с мобильного или ПК (главное, чтобы был установлен Вайбер) откроется чат с номером 79001234567
Я не советую ставить ссылку такого вида:
Как создать чат-бота для Viber
Если вы хотите создать чат-бота для Facebook, Telegram или Slack, у вас, как правило, есть выбор: вы можете использовать одну из платформ разработки ботов без кода или написать его самостоятельно.
Но если вам нужен бот для Viber, ключевые платформы на данный момент ничем вам не помогут.
Придётся создавать его самостоятельно, с использованием любого языка программирования, с помощью которого можно послать POST запрос. В этой статье мы будем использовать PHP.
Создание аккаунта, получение токена
Если у вас ещё нет аккаунта на partners.viber.com, нужно будет зарегистрироваться.
После этого вы окажетесь в админ панели и сможете создать аккаунт бота.
Заполняем все поля, начиная с названия аккаунта (имени бота, которое будут видеть пользователи в Viber) и URI (используемого для создания глубокой ссылки на бота), заканчивая email и локацией. Нажимаем ”Create” и получаем токен. Копируем его.
Мы получим пуш-уведомление в Viber, по которому можно перейти в свежесозданного бота. Изначально аккаунт будет скрыт от других пользователей, пока вы не нажмёте кнопку «Показать» (“Publish”).
Установка webhook
Зарегистрируем адрес webhook, по которому бэкенд Viber будет доставлять сообщения, отправленные боту пользователями, и другие события.
Бот обязательно должен располагаться на веб сервере, который работает по https с корректным SSL сертификатом.
Перед тем, как привязать webhook, надо подумать, какие дополнительные события нужны будут нашему боту, и добавить их в наш запрос. Это могут быть следующие события:
Обязательные события, например, ”message”, придут в любом случае, на них специально подписываться не надо.
Можно написать скрипт, который будет выполнять необходимый запрос, но мы сделаем это через Postman, многофункциональное приложение для работы с API.
Вставляем наши данные во вкладке Headers.
Во вкладке Body вставляем ссылку на бота.
Если мы сделали всё правильно (а так оно и есть) — получаем статус-сообщение ОК.
В случае, если вы не пользуетесь Postman, а пишете код в PHP, привязка webhook будет выглядеть так:
Теперь сообщения, которые будут приходить на вашего бота, будут попадать на этот webhook в виде JSON объектов.
Создание бэкенда
С помощью следующего кода мы записываем в текстовый файл входящую информацию от Viber. Это облегчит будущую разработку.
Теперь пропишем функцию отправки сообщения в Viber — обычный POST запрос.
После того как пользователь откроет диалог с нашим ботом в Viber — наш бот получит JSON с информацией о пользователе и типом события conversation_started.
Наш бот, получив этот JSON может отправить пользователю одно сообщение. В нашем случае, создаём массив с необходимыми полями для отправки сообщения с текстом «Choose an option please» и двумя кнопками: «Show contact info» и «Working hours».
В полях ActionBody прописываем текст, который получит бот после нажатия пользователем соответствующей кнопки.
Когда юзер будет отправлять сообщения боту, мы будем получать в JSON тип события «message». Соответственно, делаем обработку возможных сообщений.
При получении JSON с типом события «message» мы проверяем все возможные сообщения, которые можем получить от юзера. В нашем случае это могут быть:
1. «contacts»
2. «working_hours»
3. «main_menu» — для возврата в главное меню мы сделали кнопку его вызова в каждом сообщении (Контакты и Рабочие часы).
Получая одно из сообщений мы формируем соответствующий массив, который в функции send() формируется в JSON.
Наш демо-бот готов!
Так он выглядит в Viber.
Что с этим ботом делать дальше?
Им можно делиться с пользователями Viber (предварительно убедитесь, что нажали кнопку «Показать» (“Publish”) в аккаунте бота в Viber).
Для этого используйте кнопку «Поделиться».
Что с ним пока нельзя делать — это создать глубокую ссылку на него (с использованием URI аккаунта, как мы писали выше) и найти его во вкладке с ботами Viber (discover screen) – ни среди ботов, представленных в подборках, ни при помощи поиска. Для того, чтобы ваше детище появилось там, нужно получить эппрув от Viber, заполнив «форму публикации бота» (есть в документации). У Viber целая куча предрассудков требований, которым бот должен удовлетворять для утверждения и публикации, включая «уникальную ценность» и хотя бы минимальное понимание свободного ввода пользователя.
Подробнее о публикации бота расскажем в будущем.
Роман Брязгалов, php-разработчик, специалист по диалоговым системам Singularika
Валерия Маляренко, копирайтер Singularika
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.