User API guide/uk: Difference between revisions

From SimplyBook.me
Created page with "Якщо активовано будь-яку спеціальну функцію вибору співробітника [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("any_unit")] і в масиві "unit_map" не встановлено спеціальний термін для пари "послуга-виконавець", то користувачеві слід дозволити вибрати будь-який варіант постач..."
FuzzyBot (talk | contribs)
Updating to match new version of source page
Line 1: Line 1:
<languages/>
<languages/>
{{#seo: |title=Посібник користувача API - SimplyBook.me |description=Використовуйте API користувача SimplyBook.me для створення розширених інтеграцій. Дотримуйтесь нашого посібника для безпроблемного впровадження. Дізнайтеся більше тут! |titlemode=додати |keywords=fAQ, поширені запитання, програмне забезпечення для бронювання, запитання щодо системи бронювання, онлайн-бронювання, програмне забезпечення для календаря, система бронювання, календар бронювання, програмне забезпечення для планування, онлайн-планування зустрічей, онлайн-планування, плагіни, настроювані функції, посилання на настроювану сторінку бронювання, доменне ім'я, настроюване доменне ім'я, настроювана URL-адреса }}
<div lang="en" dir="ltr" class="mw-content-ltr">
<br><be>
{{#seo:
|title=User API guide - SimplyBook.me
|description=Use the SimplyBook.me User API to create advanced integrations. Follow our guide for seamless implementation. Learn more here!
|titlemode=append
|keywords=faq, frequently asked questions, booking software, appointment system questions, appointments online, calendar software, booking system, booking calendar, scheduling software, online appointment scheduling, online scheduling, plugins, custom features, custom booking page link, domain name, custom domain name, custom url
}}
</div>
<br><br>


Використовуйте наш API для розробників, щоб створити власний інтерфейс бронювання. Ви можете розробити будь-яке рішення, від найпростішого віджета до багатофункціонального додатка з функціоналом, налаштованим відповідно до специфіки вашого бізнесу.
<div lang="en" dir="ltr" class="mw-content-ltr">
Use our developer API to create your own booking interface. You can design any solution you want varying from the simplest widget to multifunctional application with functionality customized according to your business specific.
</div>


Інтерфейс програмування додатків Simplybook використовує [https://en.wikipedia.org/wiki/JSON-RPC#Version_2.0 протокол JSON-RPC 2.0].
<div lang="en" dir="ltr" class="mw-content-ltr">
Simplybook Application Programming Interface uses [https://en.wikipedia.org/wiki/JSON-RPC#Version_2.0 JSON-RPC 2.0 protocol].
</div>


Перегляньте [https://simplybook.me/api_example/index.html приклад інтерфейсу бронювання на основі API], а також ознайомтеся [https://simplybook.me/api_example/scheduler.js з вихідним кодом] цього рішення.
<div lang="en" dir="ltr" class="mw-content-ltr">
<br><br><be>
See [https://simplybook.me/api_example/index.html an example of API-based booking interface], and also read [https://simplybook.me/api_example/scheduler.js the source code] of this solution.
<br><br><br>
</div>




 
<div lang="en" dir="ltr" class="mw-content-ltr">
= '''АВТОРИЗАЦІЯ''' =
='''AUTHORIZATION'''=
<br><br>
<br><br>
Для використання методів Simplybook API необхідна автентифікація. Для авторизації в Simplybook API вам потрібно отримати ключ доступу — access-token. Щоб отримати цей access-token, ви повинні викликати метод JSON-RPC getToken на сервісі https://user-api.simplybook.me/login, передавши свій особистий API-ключ. Ви можете скопіювати свій API-ключ в адміністративному інтерфейсі: перейдіть за посиланням «Custom Features» (Налаштування) і виберіть «API Custom Feature» (Налаштування API). Потім потрібно ініціювати віддалений доступ до Simplybook API. Ваш запит повинен містити такі заголовки: «X-Company-Login», «X-Token».
Using Simplybook API methods require an authentication. To authorize in Simplybook API you need to get an access key — access-token. In order to get this access-token you should call the JSON-RPC method getToken on https://user-api.simplybook.me/login service passing your personal API-key. You can copy your API-key at admin interface: go to the 'Custom Features' link and select API Custom Feature 'Settings'. Then you have to init remote access to Simplybook API. Your request should contain the following headers: 'X-Company-Login', 'X-Token'.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Getting the access-token can be implemented either from client side or from your server which is the more secure solution.
</div>




Отримання токена доступу можна реалізувати як з боку клієнта, так і з боку вашого сервера, що є більш безпечним рішенням.
<div lang="en" dir="ltr" class="mw-content-ltr">
 
You may use [https://simplybook.me/api_example/json-rpc-client.js javascript JSON-RPC-client library] and [https://simplybook.me/api_example/JsonRpcClient.zip php JSON-RPC-client library] from our examples for your own solution development.
Ви можете використовувати [https://simplybook.me/api_example/json-rpc-client.js бібліотеку javascript JSON-RPC-client] та [https://simplybook.me/api_example/JsonRpcClient.zip бібліотеку php JSON-RPC-client] з наших прикладів для розробки власних рішень.
</div>


Зверніть увагу, що токен доступу діє протягом однієї години. Це зроблено з міркувань безпеки. Вам потрібно буде поновлювати його щонайменше раз на годину.
<div lang="en" dir="ltr" class="mw-content-ltr">
Please note access-token has one hour one time. This is done for security reasons. You will need to regenerate it at least once per hour.
<br><br><br>
<br><br><br>
</div>




 
<div lang="en" dir="ltr" class="mw-content-ltr">
<div class="mw-translate-fuzzy">
='''CLIENT API([https://simplybook.me/api/doc#/admin COMPANY PUBLIC SERVICE])AUTHORIZATION'''=
= '''CLIENT API ([https://simplybook.me/api/doc#/admin ДЕРЖАВНА СЛУЖБА]) АВТОРИЗАЦІЯ''' =
<br><br>
<br><br>
== '''Авторизація з боку клієнта''' ==
=='''Authorization from client side code'''==
<br><br>
<br><br>
'''Отримання токен-ключа'''.
'''Getting the token-key'''.
<br><br>
<br><br>
  <nowiki>var loginClient = new JSONRpcClient({
  <nowiki>var loginClient = new JSONRpcClient({
Line 40: Line 58:
var token = loginClient.getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);</nowiki>
var token = loginClient.getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);</nowiki>
<br><br>
<br><br>
'''Ініціалізація JSON-RPC-клієнта.'''
'''Initialization JSON-RPC-client.'''
<br><br>
<br><br>
  <nowiki>this.client = new JSONRpcClient({
  <nowiki>this.client = new JSONRpcClient({
Line 51: Line 69:
});</nowiki>
});</nowiki>
<br><br>
<br><br>
== '''Авторизація з боку сервера''' ==
=='''Authorization from server side code'''==
<br><br>
<br><br>
'''Отримання токен-ключа.'''<br><br>
'''Getting the token-key.'''<br><br>
  <nowiki>$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
  <nowiki>$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
$token = $loginClient-&gt;getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);</nowiki>
$token = $loginClient->getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);</nowiki>
<br><br>
<br><br>
'''Ініціалізація JSON-RPC-клієнта.'''
'''Initialization JSON-RPC-client.'''
<br><br>
<br><br>
  <nowiki>$client = new JsonRpcClient('https://user-api.simplybook.me' . '/', array(
  <nowiki>$client = new JsonRpcClient('https://user-api.simplybook.me' . '/', array(
  'headers' =&gt; array(
    'headers' => array(
      'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
        'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
      'X-Token: ' . $token
        'X-Token: ' . $token
  )
    )
));</nowiki>
));</nowiki>
<br><br><br>
<br><br><br>
= '''АВТОРИЗАЦІЯ API КОРИСТУВАЧА/АДМІНІСТРАТОРА ([https://simplybook.me/api/doc#/admin СЛУЖБА АДМІНІСТРУВАННЯ КОМПАНІЇ]''' =
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
='''USER/ADMIN API ([https://simplybook.me/api/doc#/admin COMPANY ADMINISTRATION SERVICE]) AUTHORIZATION'''=
<br><br>
<br><br>
== '''Авторизація з боку клієнта''' ==
=='''Authorization from client side code'''==
<br><br>
<br><br>
'''Отримання токен-ключа.'''
'''Getting the token-key.'''
<br><br>
<br><br>
  <nowiki>var loginClient = new JSONRpcClient({
  <nowiki>var loginClient = new JSONRpcClient({
Line 78: Line 99:
var token = loginClient.getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);</nowiki>
var token = loginClient.getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);</nowiki>
<br><br>
<br><br>
'''Ініціалізація JSON-RPC-клієнта.'''
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
'''Initialization JSON-RPC-client'''.
<br><br>
<br><br>
  <nowiki>this.client = new JSONRpcClient({
  <nowiki>this.client = new JSONRpcClient({
Line 89: Line 113:
});</nowiki>
});</nowiki>
<br><br>
<br><br>
== '''Авторизація з боку сервера''' ==
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
=='''Authorization from server side code'''==
<br><br>
<br><br>
'''Отримання токен-ключа.'''
'''Getting the token-key.'''
<br><br>
<br><br>
  <nowiki>$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
  <nowiki>$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
$token = $loginClient-&gt;getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);</nowiki>
$token = $loginClient->getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);</nowiki>
<br><br>
<br><br>
'''Ініціалізація JSON-RPC-клієнта.'''
'''Initialization JSON-RPC-client.'''
<br><br>
<br><br>
  <nowiki>$client = new JsonRpcClient('https://user-api.simplybook.me' . '/admin/', array(
  <nowiki>$client = new JsonRpcClient('https://user-api.simplybook.me' . '/admin/', array(
'headers' =&gt; array(
'headers' => array(
'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
'X-User-Token: ' . $token
'X-User-Token: ' . $token
)
)
));</nowiki>
));</nowiki>
<br><br><be>
<br><br><br>
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
='''GETTING DATA FROM SIMPLYBOOK SERVER'''=
<br><br>
A booking page usually is a page where clients choose service they need, an employee and a time of their meeting. Then a client enters some contact info and confirms the booking. The more complex solutions may include filling different intake forms, making some group or multi-times booking and so on. Lets describe the workflow of creation the simpliest booking page. Then if you need to add some extra functionality to your page, see here the full list of [https://simplybook.me/api/doc Simplybook API methods].
</div>


 
<div lang="en" dir="ltr" class="mw-content-ltr">
= '''ОТРИМАННЯ ДАНИХ З СЕРВЕРА SIMPLYBOOK''' =
So the first thing you should display is the list of services and the list of employes. Get this data by getEventList and getUnitList methods. They both return a list with complete information about each item in it, so you have many possibilities how to display services and employees at your page. To make employee filtration use unit_map property of the service list, it contains the info about employees who can provide the selected service.
<br><br>
<br><br>
Сторінка бронювання зазвичай є сторінкою, на якій клієнти вибирають необхідну послугу, співробітника та час зустрічі. Потім клієнт вводить контактну інформацію та підтверджує бронювання. Більш складні рішення можуть включати заповнення різних форм, створення групових або багаторазових бронювань тощо. Опишемо робочий процес створення найпростішої сторінки бронювання. Якщо вам потрібно додати додаткові функції на свою сторінку, перегляньте повний список [https://simplybook.me/api/doc методів API Simplybook].
</div>
 
 


Отже, перше, що ви повинні відобразити, це список послуг та список співробітників. Отримайте ці дані за допомогою методів getEventList та getUnitList. Обидва вони повертають список з повною інформацією про кожен елемент, що міститься в ньому, тому у вас є багато можливостей для відображення послуг та співробітників на вашій сторінці. Щоб здійснити фільтрацію співробітників, використовуйте властивість unit_map списку послуг, яка містить інформацію про співробітників, які можуть надати вибрану послугу.
<div lang="en" dir="ltr" class="mw-content-ltr">
<br><be>
'''Code example of getting services list'''
 
 
 
'''Приклад коду для отримання списку послуг'''
<br><br>
<br><br>
  <nowiki>$services = $client-&gt;getEventList();
  <nowiki>$services = $client->getEventList();
// повертає масив (array(
// returns array(array(
//    'id' =&gt; 1, - ідентифікатор послуги
//    'id' => 1, - service id
//    'name' =&gt; 'Service 1', - назва послуги
//    'name' => 'Service 1', - service's name
//    'description' =&gt; 'Опишіть свою послугу...', - опис послуги
//    'description' => 'Describe your service...', - service description
//    'duration' =&gt; 60, - тривалість послуги
//    'duration' => 60, - service duration
//    'hide_duration' =&gt; 0, - прапорець приховування тривалості від клієнтів,
//    'hide_duration' => 0, - Hide duration to clients flag,
//    'picture' =&gt; null, - ім'я файлу зображення або null
//    'picture' => null, - file name of picture or null
//    'picture_path' =&gt; '/uploads/apidemo/event__picture/small/', - повний шлях до зображення,
//    'picture_path' => '/uploads/apidemo/event__picture/small/', - full path to picture,
//    'position' =&gt; 1 - позиція послуги
//    'position' => 1 - service position
//    'is_active' =&gt; 1, - послуга активована
//    'is_active' => 1, - the service is activated
//    'is_public' =&gt; 1, - послуга доступна для бронювання клієнтами
//    'is_public' => 1, - the service is allowed to book by clients
// ), ...)</nowiki>
// ), ...)</nowiki>
<br><br>
<br><br>
'''Приклад коду для отримання списку виконавців послуг'''
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
'''Code example of getting service performers list'''
<br><br>
<br><br>
  <nowiki>$services = $client-&gt;getUnitList();
  <nowiki>$services = $client->getUnitList();
// повертає масив(array(
// returns array(array(
//    'id' =&gt; 1, - ідентифікатор виконавця
//    'id' => 1, - performer id
//    'name' =&gt; 'Provider 1', - ім'я виконавця
//    'name' => 'Provider 1', - performer name
//    'phone' =&gt; '111111111', - номер телефону виконавця
//    'phone' => '111111111', - perfomer phone number
//    'description' =&gt; 'Опишіть свого виконавця...', - опис виконавця
//    'description' => 'Describe your performer...', - performer description
//    'email' =&gt; 'test@gmail.com', - електронна адреса виконавця,
//    'email' => 'test@gmail.com', - perfomer email,
//    'is_active' =&gt; 1, - виконавець активований
//    'is_active' => 1, - the performer is activated
//    'is_visible' =&gt; 1, - виконавець видимий для клієнтів,
//    'is_visible' => 1, - the perfomer is visible for clients,
//    'picture' =&gt; null, - ім'я файлу зображення або null,
//    'picture' => null, - file name of picture or null,
//    'picure_path' =&gt; '/uploads/apidemo/unit_group__picture/small/', - повний шлях до зображення
//    'picure_path' => '/uploads/apidemo/unit_group__picture/small/', - full path to picture
//    'position' =&gt; 1, - позиція виконавця
//    'position' => 1, - performer position
//    'qty' =&gt; 1, кількість виконавців
//    'qty' => 1, performer quantity
// ), ...)</nowiki>
// ), ...)</nowiki>
<br><be>
<br><br>
 
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
The next step to a client is to pick a date and time of his service. We've used a Bootstrap date-picker in API-usage example, you can also use this or any other calendar. To set your calendar first date use getFirstWorkingDay method. It can take employee id as a parameter and returns the next date when the selected employee (or any employee in the company by default) is avaiable for booking. To show time slots inside a selected date you need getWorkCalendar and getStartTimeMatrix methods. The first method give you an information about working day start and end time, and about day-offs. And the second one returns the list of time-slots which can be booked for a certain date.
<br><br>
'''Code example of getting work days info'''
<br><br>
</div>


Наступним кроком для клієнта є вибір дати та часу надання послуги. У прикладі використання API ми використовували календар Bootstrap, але ви можете використовувати цей або будь-який інший календар. Щоб встановити першу дату календаря, скористайтеся методом getFirstWorkingDay. Він може приймати ідентифікатор співробітника як параметр і повертає наступну дату, коли вибраний співробітник (або будь-який співробітник компанії за замовчуванням) доступний для бронювання. Щоб показати часові слоти в межах вибраної дати, вам потрібні методи getWorkCalendar і getStartTimeMatrix. Перший метод надає інформацію про початок і кінець робочого дня, а також про вихідні дні. Другий метод повертає список часових слотів, які можна забронювати на певну дату.
<div lang="en" dir="ltr" class="mw-content-ltr">
<br><be>
<nowiki>$year = 2015;
 
$month = 3; // March
 
$performerId = 1; // Can be null
 
$workDaysInfo = $client->getWorkCalendar($year, $month, $performerId);
'''Приклад коду для отримання інформації про робочі дні'''
// returns array(
<br><br>
//    '2015-03-01' => array('from' => '09:00:00', 'to' => '18:00:00', 'is_day_off' => 0),
<nowiki>$year = 2015;
//    '2015-03-02' => array('from' => '09:00:00', 'to' => '18:00:00', 'is_day_off' => 0),
$month = 3; // березень
$performerId = 1; // може бути нульовим
$workDaysInfo = $client-&gt;getWorkCalendar($year, $month, $performerId);
// повертає масив (
//    '2015-03-01' =&gt; array('from' =&gt; '09:00:00', 'to' =&gt; '18:00:00', 'is_day_off' =&gt; 0),
//    '2015-03-02' =&gt; array('from' =&gt; '09:00:00', 'to' =&gt; '18:00:00', 'is_day_off' =&gt; 0),
//    ...
//    ...
//);</nowiki>
//);</nowiki>
<br><be>
<br><br>
 
'''Code example of getting start time matrix'''
 
 
'''Приклад коду для отримання матриці часу початку'''
<br><br>
<br><br>
  <nowiki>$dateFrom = '2015-03-03';
  <nowiki>$dateFrom = '2015-03-03';
Line 183: Line 209:
$performerId = 1;
$performerId = 1;
$qty = 1;
$qty = 1;
$availableTime = $client-&gt;getStartTimeMatrix($dateFrom, $dateTo, $serviceId, $performerId, $qty);
$availableTime = $client->getStartTimeMatrix($dateFrom, $dateTo, $serviceId, $performerId, $qty);
// повертає масив (
// returns array(
//    '2015-03-03' =&gt; array('09:00:00', '09:30:00', '10:00:00', ....),
//    '2015-03-03' => array('09:00:00', '09:30:00', '10:00:00', ....),
//    '2015-03-04' =&gt; масив('09:00:00', '09:30:00', '10:00:00', ....),
//    '2015-03-04' => array('09:00:00', '09:30:00', '10:00:00', ....),
//);</nowiki>
//);</nowiki>
<br><be>
<br><br>
</div>


 
<div lang="en" dir="ltr" class="mw-content-ltr">
 
Another usefull method you may need is calculateEndTime. Each service can have its own duration, also your company's employees possible have different work schedule form day to day. So using this method you can show to a client an end date and time of the service he've booked in a correct way.
Ще один корисний метод, який може вам знадобитися, — calculateEndTime. Кожна послуга може мати свою тривалість, а також співробітники вашої компанії можуть мати різний графік роботи в різні дні. Тож за допомогою цього методу ви можете правильно показати клієнту дату та час закінчення послуги, яку він забронював.
<br><br>
<br><be>
'''Code example of calculating booking end time'''
 
 
 
'''Приклад коду для розрахунку часу закінчення бронювання'''
<br><br>
<br><br>
  <nowiki>$startDateTime = '2015-03-03 09:00:00';
  <nowiki>$startDateTime = '2015-03-03 09:00:00';
$serviceId = 1;
$serviceId = 1;
$performerId = 1;
$performerId = 1;
$availableTime = $client-&gt;calculateEndTime($startDateTime, $serviceId, $performerId);
$availableTime = $client->calculateEndTime($startDateTime, $serviceId, $performerId);
// повертає '2015-03-03 10:00:00'
// returns '2015-03-03 10:00:00'
</nowiki>
</nowiki>
<br><be>
<br><br>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
When a client clicks confirm booking button you have to call book method. This is the main function which performs all necessary validations and registers a new booking in Simplybook system. It takes information about booking, client data like name and phone and some additional params. See all params descriptions of this method in [https://simplybook.me/api/doc API functions list]. The book method responce contains an uniqe code and other details of the new booking or the list of errors if some problems occured, so you can use this information to show booking result to a client in convinient and intuitive way.
<br><br><br>
</div>


 
<div lang="en" dir="ltr" class="mw-content-ltr">
Коли клієнт натискає кнопку «Підтвердити бронювання», ви повинні викликати метод book. Це основна функція, яка виконує всі необхідні перевірки та реєструє нове бронювання в системі Simplybook. Вона бере інформацію про бронювання, дані клієнта, такі як ім'я та телефон, а також деякі додаткові параметри. Дивіться опис всіх параметрів цього методу в [https://simplybook.me/api/doc списку функцій API]. Відповідь методу book містить унікальний код та інші деталі нового бронювання або список помилок, якщо виникли проблеми, тому ви можете використовувати цю інформацію, щоб показати результат бронювання клієнту в зручний та інтуїтивно зрозумілий спосіб.
='''USING OF API SECRET KEY'''=
<br><br><be>
<br><br>
 
In some cases the book method may require the confirmation, e.g. if your accept payments from clients you confirm booking only after the payment is already came. The Simplybook API confirmBookng method takes booking-id and secure signature as params (another method which requires secure signature is cancelBookng). For the secure signature generation your secret API-key should be used. See how it can be done in the example below. You can find the secret key at admin interface under 'Settings' link of API Custom Feature in 'Custom Features' list.
 
 
= '''ВИКОРИСТАННЯ СЕКРЕТНОГО КЛЮЧА API''' =
<br><br>
<br><br>
У деяких випадках метод бронювання може вимагати підтвердження, наприклад, якщо ви приймаєте платежі від клієнтів, ви підтверджуєте бронювання тільки після того, як платіж вже надійшов. Метод Simplybook API confirmBookng приймає ідентифікатор бронювання та безпечний підпис як параметри (інший метод, який вимагає безпечного підпису, - cancelBookng). Для генерації безпечного підпису слід використовувати ваш секретний ключ API. Дивіться, як це можна зробити, у прикладі нижче. Секретний ключ можна знайти в адміністративному інтерфейсі за посиланням «Налаштування» в розділі «Налаштування API» у списку «Налаштування».
</div>
<br><be>


 
<div lang="en" dir="ltr" class="mw-content-ltr">
 
'''Code example of service booking and its confirmation using secret API key'''
'''Приклад коду бронювання послуги та її підтвердження за допомогою секретного API-ключа'''
<br><br>
<br><br>
  <nowiki>$additionalFields = array(
  <nowiki>$additionalFields = array(
'6740d3bce747107ddb9a789cbb78abf3' =&gt; 'value1',  
'6740d3bce747107ddb9a789cbb78abf3' => 'value1',  
'b0657bafaec7a2c9800b923f959f8163' =&gt; 'value2'
'b0657bafaec7a2c9800b923f959f8163' => 'value2'
);
);
$clientData = array(
$clientData = array(
'name' =&gt; 'Client name',
'name' => 'Client name',
'email' =&gt; 'client@email.com',
'email' => 'client@email.com',
'phone' =&gt; '+13152108338'
'phone' => '+13152108338'
);
);
$bookingsInfo = $client-&gt;book($eventId, $unitId, $date, $time, $clientData, $additionalFields);
$bookingsInfo = $client->book($eventId, $unitId, $date, $time, $clientData, $additionalFields);
</div>


if ($bookingsInfo-&gt;require_confirm) {
<div lang="en" dir="ltr" class="mw-content-ltr">
foreach ($bookingsInfo-&gt;bookings as $booking) {
if ($bookingsInfo->require_confirm) {
$sign = md5($booking-&gt;id . $booking-&gt;hash . YOUR_API_SECRET_KEY);
  foreach ($bookingsInfo->bookings as $booking) {
$result = $client-&gt;confirmBooking($booking-&gt;id, $sign);
  $sign = md5($booking->id . $booking->hash . YOUR_API_SECRET_KEY);
echo '
  $result = $client->confirmBooking($booking->id, $sign);
  echo '
Confirm result
Confirm result
';
';
var_dump($result);
  var_dump($result);
}
    }
}</nowiki>
}</nowiki>
<br><be>
<br><br>
 
</div>
 


'''Приклад коду для отримання форм для введення даних'''
<div lang="en" dir="ltr" class="mw-content-ltr">
'''Code example of getting intake forms'''
<br><br>
<br><br>
  <nowiki>$fields = $client-&gt;getAdditionalFields($eventId);
  <nowiki>$fields = $client->getAdditionalFields($eventId);
// повертає - масив(масив(
// returns - array(array(
// 'name' =&gt; 'b0657bafaec7a2c9800b923f959f8163', - назва поля
// 'name' => 'b0657bafaec7a2c9800b923f959f8163', - field name
// 'title' =&gt; 'Test digits', - назва поля
// 'title' => 'Test digits', - field title
// 'type' =&gt; 'digits', - тип поля
// 'type' => 'digits', - field type
// 'values' =&gt; null, - доступні значення для поля типу select
// 'values' => null, - available values for select field type
// 'default' =&gt; null, - значення за замовчуванням для поля
// 'default' => null, - default value for field
// 'is_null' =&gt; null, - чи поле може бути нульовим
// 'is_null' => null, - is filed nullable
// 'on_main_page' =&gt; 1,  
// 'on_main_page' => 1,  
// 'pos' =&gt; 1, - позиція поля
// 'pos' => 1, - field position
// 'value' =&gt; null
// 'value' => null
// )), ...)</nowiki>
// )), ...)</nowiki>
<br><br><be>
<br><br><br>
</div>


 
<div lang="en" dir="ltr" class="mw-content-ltr">
 
='''SIMPLYBOOK CUSTOM FEATURES'''=
= '''ПЕРСОНАЛЬНІ ФУНКЦІЇ SIMPLYBOOK''' =
<br><br>
If your company specific requires some additional functionality you can activate some of our additional Custom Features. The complete Custom Features list with detailed description is avaiable in your admin interface under the 'Custom Feature' link. After the necessary Custom Feature is enabled the corresponding API methods will be activated so you can use them in your code.
<br><br><br>
='''BOOKING FUNCTIONALITY CODEFLOW'''=
<br><br>
<br><br>
Якщо ваша компанія потребує додаткових функцій, ви можете активувати деякі з наших додаткових функцій. Повний перелік функцій з докладним описом доступний в адміністративному інтерфейсі за посиланням «Додаткові функції». Після увімкнення необхідної функції будуть активовані відповідні методи API, які ви зможете використовувати у своєму коді.
Authorize in Simplybook API using '''loginClient.getToken(companyLogin, apiKey);''' function.
<br><br><be>
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
Check if Service categories Custom Feature is activated by [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("event_category")]  if yes then display list of categories [https://simplybook.me/en/api/doc#getCategoriesList getCategoriesList()].
</div>


= '''ФУНКЦІОНАЛЬНІСТЬ БРОНЮВАННЯ CODEFLOW''' =
<br><br>
Авторизуйте в Simplybook API за допомогою функції '''loginClient.getToken(companyLogin, apiKey);'''.


Перевірте, чи активована функція «Категорії послуг» за допомогою [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("event_category")]. Якщо так, то відобразіть список категорій [https://simplybook.me/en/api/doc#getCategoriesList getCategoriesList()].
<div lang="en" dir="ltr" class="mw-content-ltr">
Get list of services (events) and performers (units) using [https://simplybook.me/en/api/doc#getEventList getEventList()] and [https://simplybook.me/en/api/doc#getUnitList getUnitList()] functions. If "unit_map" array is available for service it means this service can be provided by given performers only.
</div>






Отримати список послуг (подій) та виконавців (одиниць) за допомогою функцій [https://simplybook.me/en/api/doc#getEventList getEventList()] та [https://simplybook.me/en/api/doc#getUnitList getUnitList()]. Якщо для послуги доступний масив "unit_map", це означає, що ця послуга може бути надана тільки зазначеними виконавцями.
<div lang="en" dir="ltr" class="mw-content-ltr">
If Any Employee Selector Custom Feature is activated [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("any_unit")] and no special duration is set for service-performer pair in "unit_map" array then user should be allowed to select Any provider option or choose provider manually. But manual selection of performers should not be possible if [https://simplybook.me/en/api/doc#getCompanyParam getCompanyParam("any_unit__hide_other_units")] is enabled.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
Use [https://simplybook.me/en/api/doc#getStartTimeMatrix getStartTimeMatrix ($from as current date, $to as current date, $eventId, $unitId, $count as selected participants value )] to get available timeslots for given date. '''$unitId''' should be null if Any employee option is selected.
</div>


Якщо активовано будь-яку спеціальну функцію вибору співробітника [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("any_unit")] і в масиві "unit_map" не встановлено спеціальний термін для пари "послуга-виконавець", то користувачеві слід дозволити вибрати будь-який варіант постачальника або вибрати постачальника вручну. Але ручний вибір виконавців не повинен бути можливим, якщо активовано [https://simplybook.me/en/api/doc#getCompanyParam getCompanyParam("any_unit__hide_other_units")].


Використовуйте [https://simplybook.me/en/api/doc#getStartTimeMatrix getStartTimeMatrix ($from як поточну дату, $to як поточну дату, $eventId, $unitId, $count як значення вибраних учасників)], щоб отримати доступні часові слоти для заданої дати. '''$unitId''' повинен бути нульовим, якщо вибрано опцію «Будь-який співробітник».
<div lang="en" dir="ltr" class="mw-content-ltr">
If Any Employee selector is active and Any employee was selected call [https://simplybook.me/en/api/doc#getAvailableUnits getAvailableUnits($eventId, $dateTime, $count)] to get available $unitId
</div>


Якщо активний селектор «Будь-який співробітник» і було вибрано будь-якого співробітника, викличте [https://simplybook.me/en/api/doc#getAvailableUnits getAvailableUnits($eventId, $dateTime, $count)], щоб отримати доступний $unitId




<div lang="en" dir="ltr" class="mw-content-ltr">
If Intake Forms Custom Feature is activated [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("event_field")] call [https://simplybook.me/en/api/doc#getAdditionalFields getAdditionalFields($eventId)] function to get list of fields for client to fill.
</div>




Якщо активована функція «Налаштування форм для нових клієнтів», викличте функцію [https://simplybook.me/en/api/doc#isPluginActivated isPluginActivated("event_field")] [https://simplybook.me/en/api/doc#getAdditionalFields getAdditionalFields($eventId)], щоб отримати список полів, які клієнт повинен заповнити.
<div lang="en" dir="ltr" class="mw-content-ltr">
Call [https://simplybook.me/en/api/doc#book book($eventId, $unitId, $date, $time, $clientData, $additional, $count, $batchId)] to make a booking.
</div>


Викличте [https://simplybook.me/en/api/doc#book книгу ($eventId, $unitId, $date, $time, $clientData, $additional, $count, $batchId)], щоб зробити бронювання.
<div lang="en" dir="ltr" class="mw-content-ltr">
 
<br><br>
<br><be>
</div>

Revision as of 12:19, 15 May 2025



Use our developer API to create your own booking interface. You can design any solution you want varying from the simplest widget to multifunctional application with functionality customized according to your business specific.

Simplybook Application Programming Interface uses JSON-RPC 2.0 protocol.

See an example of API-based booking interface, and also read the source code of this solution.



AUTHORIZATION



Using Simplybook API methods require an authentication. To authorize in Simplybook API you need to get an access key — access-token. In order to get this access-token you should call the JSON-RPC method getToken on https://user-api.simplybook.me/login service passing your personal API-key. You can copy your API-key at admin interface: go to the 'Custom Features' link and select API Custom Feature 'Settings'. Then you have to init remote access to Simplybook API. Your request should contain the following headers: 'X-Company-Login', 'X-Token'.

Getting the access-token can be implemented either from client side or from your server which is the more secure solution.


You may use javascript JSON-RPC-client library and php JSON-RPC-client library from our examples for your own solution development.

Please note access-token has one hour one time. This is done for security reasons. You will need to regenerate it at least once per hour.



CLIENT API(COMPANY PUBLIC SERVICE)AUTHORIZATION



Authorization from client side code



Getting the token-key.

var loginClient = new JSONRpcClient({
	'url': 'https://user-api.simplybook.me' + '/login',
	'onerror': function (error) {},
});
var token = loginClient.getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);



Initialization JSON-RPC-client.

this.client = new JSONRpcClient({
	'url': 'https://user-api.simplybook.me',
	'headers': {
		'X-Company-Login': YOUR_COMPANY_LOGIN,
		'X-Token': token
	},
	'onerror': function (error) {}
});



Authorization from server side code



Getting the token-key.

$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
$token = $loginClient->getToken(YOUR_COMPANY_LOGIN, YOUR_API_KEY);



Initialization JSON-RPC-client.

$client = new JsonRpcClient('https://user-api.simplybook.me' . '/', array(
    'headers' => array(
        'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
        'X-Token: ' . $token
    )
));




USER/ADMIN API (COMPANY ADMINISTRATION SERVICE) AUTHORIZATION



Authorization from client side code



Getting the token-key.

var loginClient = new JSONRpcClient({
'url': 'https://user-api.simplybook.me' + '/login',
'onerror': function (error) {},
});
var token = loginClient.getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);



Initialization JSON-RPC-client.

this.client = new JSONRpcClient({
'url': 'https://user-api.simplybook.me' + '/admin/',
'headers': {
'X-Company-Login': YOUR_COMPANY_LOGIN,
'X-User-Token': token
},
'onerror': function (error) {}
});



Authorization from server side code



Getting the token-key.

$loginClient = new JsonRpcClient('https://user-api.simplybook.me' . '/login/');
$token = $loginClient->getUserToken(YOUR_COMPANY_LOGIN, YOUR_USER_LOGIN, YOUR_USER_PASSWORD);



Initialization JSON-RPC-client.

$client = new JsonRpcClient('https://user-api.simplybook.me' . '/admin/', array(
'headers' => array(
'X-Company-Login: ' . YOUR_COMPANY_LOGIN,
'X-User-Token: ' . $token
)
));




GETTING DATA FROM SIMPLYBOOK SERVER



A booking page usually is a page where clients choose service they need, an employee and a time of their meeting. Then a client enters some contact info and confirms the booking. The more complex solutions may include filling different intake forms, making some group or multi-times booking and so on. Lets describe the workflow of creation the simpliest booking page. Then if you need to add some extra functionality to your page, see here the full list of Simplybook API methods.

So the first thing you should display is the list of services and the list of employes. Get this data by getEventList and getUnitList methods. They both return a list with complete information about each item in it, so you have many possibilities how to display services and employees at your page. To make employee filtration use unit_map property of the service list, it contains the info about employees who can provide the selected service.

Code example of getting services list

$services = $client->getEventList();
// returns array(array(
//     'id' => 1, - service id
//     'name' => 'Service 1', - service's name
//     'description' => 'Describe your service...', - service description
//     'duration' => 60, - service duration
//     'hide_duration' => 0, - Hide duration to clients flag,
//     'picture' => null, - file name of picture or null
//     'picture_path' => '/uploads/apidemo/event__picture/small/', - full path to picture,
//     'position' => 1 - service position
//     'is_active' => 1, - the service is activated
//     'is_public' => 1, - the service is allowed to book by clients
// ), ...)



Code example of getting service performers list

$services = $client->getUnitList();
// returns array(array(
//    'id' => 1, - performer id
//    'name' => 'Provider 1', - performer name
//    'phone' => '111111111', - perfomer phone number
//    'description' => 'Describe your performer...', - performer description
//    'email' => 'test@gmail.com', - perfomer email,
//    'is_active' => 1, - the performer is activated
//    'is_visible' => 1, - the perfomer is visible for clients,
//    'picture' => null, - file name of picture or null,
//    'picure_path' => '/uploads/apidemo/unit_group__picture/small/', - full path to picture
//    'position' => 1, - performer position
//    'qty' => 1, performer quantity
// ), ...)



The next step to a client is to pick a date and time of his service. We've used a Bootstrap date-picker in API-usage example, you can also use this or any other calendar. To set your calendar first date use getFirstWorkingDay method. It can take employee id as a parameter and returns the next date when the selected employee (or any employee in the company by default) is avaiable for booking. To show time slots inside a selected date you need getWorkCalendar and getStartTimeMatrix methods. The first method give you an information about working day start and end time, and about day-offs. And the second one returns the list of time-slots which can be booked for a certain date.

Code example of getting work days info

$year = 2015; $month = 3; // March $performerId = 1; // Can be null $workDaysInfo = $client->getWorkCalendar($year, $month, $performerId); // returns array( // '2015-03-01' => array('from' => '09:00:00', 'to' => '18:00:00', 'is_day_off' => 0), // '2015-03-02' => array('from' => '09:00:00', 'to' => '18:00:00', 'is_day_off' => 0), // ... //);

Code example of getting start time matrix

$dateFrom = '2015-03-03';
$dateTo = '2015-03-04';
$serviceId = 1;
$performerId = 1;
$qty = 1;
$availableTime = $client->getStartTimeMatrix($dateFrom, $dateTo, $serviceId, $performerId, $qty);
// returns array(
//     '2015-03-03' => array('09:00:00', '09:30:00', '10:00:00', ....),
//     '2015-03-04' => array('09:00:00', '09:30:00', '10:00:00', ....),
//);



Another usefull method you may need is calculateEndTime. Each service can have its own duration, also your company's employees possible have different work schedule form day to day. So using this method you can show to a client an end date and time of the service he've booked in a correct way.

Code example of calculating booking end time

$startDateTime = '2015-03-03 09:00:00';
$serviceId = 1;
$performerId = 1;
$availableTime = $client->calculateEndTime($startDateTime, $serviceId, $performerId);
// returns '2015-03-03 10:00:00'



When a client clicks confirm booking button you have to call book method. This is the main function which performs all necessary validations and registers a new booking in Simplybook system. It takes information about booking, client data like name and phone and some additional params. See all params descriptions of this method in API functions list. The book method responce contains an uniqe code and other details of the new booking or the list of errors if some problems occured, so you can use this information to show booking result to a client in convinient and intuitive way.


USING OF API SECRET KEY



In some cases the book method may require the confirmation, e.g. if your accept payments from clients you confirm booking only after the payment is already came. The Simplybook API confirmBookng method takes booking-id and secure signature as params (another method which requires secure signature is cancelBookng). For the secure signature generation your secret API-key should be used. See how it can be done in the example below. You can find the secret key at admin interface under 'Settings' link of API Custom Feature in 'Custom Features' list.

Code example of service booking and its confirmation using secret API key

$additionalFields = array(
	'6740d3bce747107ddb9a789cbb78abf3' => 'value1', 
	'b0657bafaec7a2c9800b923f959f8163' => 'value2'
);
$clientData = array(
	'name' => 'Client name',
	'email' => 'client@email.com',
	'phone' => '+13152108338'
);
		
$bookingsInfo = $client->book($eventId, $unitId, $date, $time, $clientData, $additionalFields);
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
if ($bookingsInfo->require_confirm) {
   foreach ($bookingsInfo->bookings as $booking) {
	   $sign = md5($booking->id . $booking->hash . YOUR_API_SECRET_KEY);
	   $result = $client->confirmBooking($booking->id, $sign);
	   echo '
Confirm result
';
	   var_dump($result);
    }
}



Code example of getting intake forms

$fields = $client->getAdditionalFields($eventId);
// returns - array(array(
//		'name' => 'b0657bafaec7a2c9800b923f959f8163', - field name
//		'title' => 'Test digits', - field title
//		'type' => 'digits', - field type
//		'values' => null, - available values for select field type
//		'default' => null, - default value for field
//		'is_null' => null, - is filed nullable
//		'on_main_page' => 1, 
//		'pos' => 1, - field position
//		'value' => null
// )), ...)




SIMPLYBOOK CUSTOM FEATURES



If your company specific requires some additional functionality you can activate some of our additional Custom Features. The complete Custom Features list with detailed description is avaiable in your admin interface under the 'Custom Feature' link. After the necessary Custom Feature is enabled the corresponding API methods will be activated so you can use them in your code.


BOOKING FUNCTIONALITY CODEFLOW



Authorize in Simplybook API using loginClient.getToken(companyLogin, apiKey); function.


Check if Service categories Custom Feature is activated by isPluginActivated("event_category") if yes then display list of categories getCategoriesList().


Get list of services (events) and performers (units) using getEventList() and getUnitList() functions. If "unit_map" array is available for service it means this service can be provided by given performers only.


If Any Employee Selector Custom Feature is activated isPluginActivated("any_unit") and no special duration is set for service-performer pair in "unit_map" array then user should be allowed to select Any provider option or choose provider manually. But manual selection of performers should not be possible if getCompanyParam("any_unit__hide_other_units") is enabled.


Use getStartTimeMatrix ($from as current date, $to as current date, $eventId, $unitId, $count as selected participants value ) to get available timeslots for given date. $unitId should be null if Any employee option is selected.


If Any Employee selector is active and Any employee was selected call getAvailableUnits($eventId, $dateTime, $count) to get available $unitId


If Intake Forms Custom Feature is activated isPluginActivated("event_field") call getAdditionalFields($eventId) function to get list of fields for client to fill.