Посібник користувача API

Revision as of 12:20, 15 May 2025 by Admin (talk | contribs) (Created page with "= '''АВТОРИЗАЦІЯ''' = <br><br> Для використання методів Simplybook API необхідна автентифікація. Для авторизації в Simplybook API вам потрібно отримати ключ доступу — access-token. Щоб отримати цей access-token, ви повинні викликати метод JSON-RPC getToken на сервісі https://user-api.simplybook.me/login, передавши...")



Використовуйте наш API для розробників, щоб створити власний інтерфейс бронювання. Ви можете розробити будь-яке рішення, від найпростішого віджета до багатофункціонального додатка з функціоналом, налаштованим відповідно до специфіки вашого бізнесу.

Інтерфейс програмування додатків Simplybook використовує протокол JSON-RPC 2.0.

Перегляньте приклад інтерфейсу бронювання на основі API, а також ознайомтеся з вихідним кодом цього рішення.



АВТОРИЗАЦІЯ



Для використання методів 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».

Отримання токена доступу можна реалізувати як з боку клієнта, так і з боку вашого сервера, що є більш безпечним рішенням.


Ви можете використовувати бібліотеку javascript JSON-RPC-client та бібліотеку php JSON-RPC-client з наших прикладів для розробки власних рішень.

Зверніть увагу, що токен доступу діє протягом однієї години. Це зроблено з міркувань безпеки. Вам потрібно буде поновлювати його щонайменше раз на годину.



CLIENT API (ДЕРЖАВНА СЛУЖБА) АВТОРИЗАЦІЯ



Авторизація з боку клієнта



Отримання токен-ключа.

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



Ініціалізація JSON-RPC-клієнта.

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



Авторизація з боку сервера



Отримання токен-ключа.

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



Ініціалізація JSON-RPC-клієнта.

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




АВТОРИЗАЦІЯ API КОРИСТУВАЧА/АДМІНІСТРАТОРА (СЛУЖБА АДМІНІСТРУВАННЯ КОМПАНІЇ



Авторизація з боку клієнта



Отримання токен-ключа.

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);



Ініціалізація JSON-RPC-клієнта.

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) {}
});



Авторизація з боку серверного коду



Отримання токен-ключа.

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



Ініціалізація JSON-RPC-клієнта.

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




ОТРИМАННЯ ДАНИХ З СЕРВЕРА SIMPLYBOOK



Сторінка бронювання зазвичай є сторінкою, на якій клієнти вибирають необхідну послугу, співробітника та час зустрічі. Потім клієнт вводить контактну інформацію та підтверджує бронювання. Більш складні рішення можуть включати заповнення різних форм, створення групових або багаторазових бронювань тощо. Опишемо робочий процес створення найпростішої сторінки бронювання. Якщо вам потрібно додати додаткові функції на свою сторінку, перегляньте повний список методів API Simplybook.

Отже, перше, що ви повинні відобразити, це список послуг та список співробітників. Отримайте ці дані за допомогою методів getEventList та getUnitList. Обидва вони повертають список з повною інформацією про кожен елемент, що міститься в ньому, тому у вас є багато можливостей для відображення послуг та співробітників на вашій сторінці. Щоб здійснити фільтрацію співробітників, використовуйте властивість unit_map списку послуг, яка містить інформацію про співробітників, які можуть надати вибрану послугу.

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.