Generic Interface

Слои интерфейса Generic Interface
Транспортная Сеть
Отображение Данных
Контроллер
Операция (OTRS как поставщик услуг)
Invoker - запрашивающая сторона (OTRS как запрашивающая сторона, клинет)
Поток связи Generic Interface
OTRS как Поставщик
Удаленный Запрос:
OTRS Ответ:
OTRS как запрашиваемая сторона
OTRS Запрос:
Удаленный Ответ
Веб-сервисы
Графический интерфейс веб-сервиса
Обзор Веб-интерфейса
Добавить Веб Сервис
Изменения веб-сервиса:
Клонирование веб-сервиса:
Экспорт веб-сервиса
Импорт веб-сервиса:
История веб-сервиса
Удаление веб-сервиса
Отладчик веб-сервиса:
Изменение настроек веб-службы
Интерфейс командной строки Веб-Сервиса
Конфигурация Веб-сервиса
Отладчик веб-сервиса:
Конфигурация Веб-сервиса
Описание Конфигурации
Общий
Отладчик
Поставщик
Запрашиваемая сторона
Коннекторы (Connectors)
Комплект Коннекторов (Connectors)
Коннектор сессии
Коннектор Заявки
Примеры:
Конфигурация Веб-сервиса
Запрашивающая сторона Perl SOAP
Perl REST Requester
cURL Примеры для REST запросов

OTRS Generic Interface состоит измногоуровневого интерфейса, позволяющего OTRS взаимодействовать с другими системами с помощью веб-сервисов. Это взаимодействие может быть двунаправленной:

Слои интерфейса Generic Interface

Generic Interface is build based on a layer model, to be flexible and easy to customize.

A layer is a set of files, which control how the Generic Interface performs different parts of a web service. Using the right configuration, one can build different web services for different External Systems without creating new modules.

Note

If the Remote System does not support the current bundled modules of the Generic Interface, special modules need to be developed for that specific web service.

Перечень модулей предоставляемых Generic Interface поставляется вместе с OTRS и будет обновлен или увеличен с течением времени.

Рисунок: Слои графического интерфейса

Транспортная Сеть

This layer is responsible for the correct communication with the Remote System. It receives requests and generates responses when acting as provider, and generates requests and receives responses when acting as requester.

Provider communication is handled by a new web server handle called "nph-genericinterface.pl".

Requester communication could be initiated during an event triggered by a Generic Interface module or any other OTRS module. This event is catched by the event handler and depending on the configuration the event will be processed directly by the requester object or delegated to the Scheduler (a separated daemon designed to process tasks asynchronously).

Отображение Данных

This layer is responsible for translating data structures between OTRS and the Remote System (data internal and data external layers). Usually Remote Systems have different data structures than OTRS (including different values and names for those values), and here resides the importance of the layer to change the received information into something that OTRS can understand and on the opposite way send the information to each Remote System using their data dictionaries.

Example: "Priority" (OTRS) might be called "Prio" in a remote system and it could be that value "1 Low" (OTRS) should be mapped to "Information" on the remote system.

Контроллер

Controllers are collections of similar Operations or Invokers. For example, a Ticket controller might contain several standard ticket operations. Custom controllers can be implemented, for example a "TicketExternalCompany" controller which may contain similar functions as the standard Ticket controller, but with a different data interface, or function names (to adapt to the Remote System function names) or complete different code.

One application for Generic Interface could be to synchronize information with one Remote System that only can talk with another Remote System of the same kind. In this case new controllers needs to be developed and the Operations and Invokers has to emulate the Remote System behavior in such way that the interface that OTRS exposes is similar to the Remote System's interface.

Операция (OTRS как поставщик услуг)

An Operation is a single action that can be performed within OTRS. All operations have the same programming interface, they receive the data into one specific parameter, and return a data structure with a success status, potential error message and returning data.

Normally operations uses the already mapped data (internal) to call core modules and perform actions in OTRS like: Create a Ticket, Update a User, Invalidate a Queue, Send a Notification, etc. An operation has full access to the OTRS API to perform the action.

Invoker - запрашивающая сторона (OTRS как запрашивающая сторона, клинет)

An Invoker is an action that OTRS performs against a Remote System. Invokers use the OTRS Core modules to process and collect the needed information to create the request. When the information is ready it has to be mapped to the Remote System format in order to be sent to the Remote System, that will process the information execute the action and send the response back, to either process the success or handle errors.

Поток связи Generic Interface

The Generic Interface has a defined flow to perform actions as a provider and as a requester.

Эти потоки описаны ниже:

OTRS как Поставщик

Удаленный Запрос:
  1. HTTP-запрос

    • OTRS получает HTTP-запрос и передает его через слои.

    • Модуль провайдера отвечает за выполнение и управление этими действиями.

  2. Транспортная Сеть

    • Сетевой транспортный модуль декодирует данные запроса и отделяет Имя операции от остальных данных.

    • Название операции и данные операции будут возвращены поставщику.

  3. Внешние данные

    • Данные отправленные из удаленной системы (Это не слой базирующийся на модуле).

  4. Mapping

    • Данные преобразуются из формата Внешней Системы во внутренний формат данных OTRS так, как это указано в конфигурации отображения для этой операции (Mapping для входящих данных запроса).

    • Преобразованные данные возвращаются обратно поставщику.

  5. Внутренние Данные

    • Data as transformed and prepared to be passed to the operation (This is not a module based layer).

  6. Операция

    • Принимает и проверяет данные.

    • Осуществляет контроль доступа пользователей.

    • Выполняет действие.

OTRS Ответ:
  1. Операция

    • Возвращает результирующие данные поставщику.

  2. Внутренние Данные

    • Данные возвращаемые из операции.

  3. Mapping

    • The data is transformed back to the Remote system format as specified in the mapping configuration (Mapping for outgoing response data).

    • Преобразованные данные возвращаются обратно поставщику.

  4. Внешние данные

    • Данные преобразованы и подготовлены для приема Транспортной сетью как ответ.

  5. Транспортная Сеть

    • Получает данные уже в формате Удаленной Системы.

    • Создает правильный ответ для этого типа транспортной сети.

  6. HTTP ответ

    • Ответ отправляется обратно клиенту веб-сервиса.

    • В случае ошибки, сообщение об ошибке отправляется удаденной системе (например SOAP-ошибка, HTTP-ошибка и т.д.).

OTRS как запрашиваемая сторона

OTRS Запрос:
  1. Обработчки Event Trigger

    • В зависимости от настройки веб-сервис определяет будет ли запрос синхронным или асинхронным.

      • Синхронный

        • A direct call to the Requester is made in order to create a new request and to pass it through the layers.

      • Асинхронный

        • Create a new Generic Interface (Requester) task for the OTRS Scheduler (by delegating the request execution to the Scheduler, the user experience could be highly improved, otherwise all the time needed to prepare the request and the remote execution will be added to the OTRS Events that trigger those requests).

        • In its next cycle the Scheduler process reads the new task and creates a call to the Requester that will create a new request and then passes it through the layers.

  2. Запрашивающая сторона

    • Получает данные от событий.

    • Проверяет полученные данные (при необходимости).

    • Вызвать модули ядра для дополнения данных (при необходимости).

    • Возвращает структуру данных запроса или отправляет сигнал "Остановка связи" для Запрашивающей Стороны (requester), чтобы корректно отменить запрос.

  3. Внутренние Данные

    • Данные передаются от запрашивающей стороны (Это не слой, основанный на модуле).

  4. Mapping

    • The data is transformed to the Remote system format as specified in the mapping configuration (Mapping for outgoing response data).

    • Уже преобразованные данные возвращаются Запрашивающей Стороне.

  5. Внешние данные

    • Данные преобразованы и подготовлены для отправки удаленной системе.

  6. Транспортная Сеть

    • Receives the remote operation name and the data already transformed to the Remote System format from the requester.

    • Создает действительный запрос для транспортной сети.

    • Отправляет запрос удаленной системе и ожидает ответ от нее

Удаленный Ответ
  1. Транспортная сеть

    • Получает ответ и декодирует данные запроса.

    • Возвращает данные запрашивающей стороне.

  2. Внешние данные

    • Данные полученные от Удаленной Системы

  3. Mapping

    • Данные преобразуются из формата внешней системы во внутренний формат данных OTRS так, как это указано в конфигурации отображения для этой операции (Mapping для входящих данных отклика).

    • Уже преобразованные данные возвращаются Запрашивающей Стороне.

  4. Внутренние Данные

    • Data as transformed and ready to be passed back to the requester.

  5. Запрашивающая сторона

    • Получает возвращаемые данные.

    • Handles the data as needed specifically by each Invoker (included error handling if any).

    • Возврат результата Запроса и данных запрашивающей стороне.

  6. Обработчик или Планировщик Действий

    • Receives the data from the Requester, in the case of the Scheduler this data might contain information to Re-Schedule the task immediately or in the future.

Веб-сервисы

Веб-сервисы это метод взаимодействия между двумя системами, в нашем случае, OTRS и удаленной системой/Remote System.

Основой Web Service является его конфигурация, в которой определяется, какие действия он может выполнить сам внутри (Operation), какие действия запроса OTRS может выполнить Внешняя система (Invokers), каким образом данные преобразуются из одной системы в другую (Mapping), и с помощью какого протокола будет осуществляться взаимодействие (Transport)

Generic Interface - это инструмент, который позволяет создавать Web-сервисы для OTRS предопределенным образом, используя уже готовые блоки, которые независимы друг от друга и взаимозаменяемы.

Графический интерфейс веб-сервиса

Графический пользовательский интерфейс (GUI) является тем инструментом, который позволяет создавать сложные настройки веб-сервиса в дружественной и приятной среде интерфейса. Он позволяет:

  • Создание и Удалинеи веб-сервисов

  • Импортировать и Экспортировать настройки (в формате YAML) для существующих веб-сервисов.

  • Просматривать, Возвращаться и Экспортировать устаревшие конфигурационные параметры для существующих веб-сервисов на странице истории конфигурации.

  • Отслеживать все сообщения журнала для каждого из веб-сервисов на странице Отладчика.

Обзор Веб-интерфейса

Ссылка "Веб-Сервисы/Web Services" на главном экране интерфейса администратора (Панели Администратора) осуществляет переход к экрану обзора веб-сервисов, с помощью которого, вы можете управлять их настройками. Вы можете добавлять новые или изменять настройки существующих на этом экране.

Every web service configuration screen has in the upper part of the screen a "bread crumbs" style navigation path. This navigation path is useful to know exactly in which part of the web service configuration we are, and also enables the user to jump back to any part of the configuration process at any time (this action will not save any changes).

Note

Чтобы создать новый веб-сервис, нажмите кнопку "Добавить веб-сервис", введите все необходимы данные.

Рисунок: Обзор Веб-сервисов

Добавить Веб Сервис

Единственное поле в этой части - это "Имя" веб-сервиса, которое должно быть уникальным в системе и не может быть пустым. Остальные поля также необходимы для настройки, такие как "Уровень отладки/Debug Threshold" и "Действительность", но эти поля уже заполнены значениями по умолчанию, для каждого списка.

Значением по умолчанию для поля "Уровень отладки/Debug Threshold" является "debug". Каждое последующее значение "Уровень отладки/Debug Threshold" является более строгим и отбрасывает журналы связи более низкого порядка, чем то, что установлено в системе ранее.

Отладка уровней (от нижних к верхним)

  • Отладка

  • Информация

  • Уведомление

  • Ошибка

Также есть возможность определить протокол транспортной сети для "OTRS как Поставщика" и "OTRS как Запрашиваемую Сторону".

Нажмите кнопку "Сохнанить", чтобы зарегистрировать новый веб-сервис в базе данных или кнопку "Отменить" чтобы отменить эту операцию.

Если у вас уже имеется файл конфигурации веб-сервисов в формате YAML, вы можете импортировать его, нажав на кнопку "Импортировать веб-сервис" слева на экране. Для дальнейшей информации об импорте веб-сервисов обратитесь к следующей секции "Изменение Веб-сервисов/Web Service Change".

Note

Нажмите на имя веб-сервиса на странице просмотра чтобы изменить или добавить больше элементов веб-сервису.

Рисунок: Добавление нового веб-сервиса

Изменения веб-сервиса:

На этом экране имеется полный набор по управлению каждой частью веб-сервиса. Слева, в колонке "Действия" вы найдете несколько кнопок, позволяющих выполнить все доступные действия над веб-сервисом:

  • Клонирование веб-сервиса.

  • Экспортировать веб-сервис.

  • Импортировать веб-сервис.

  • История конфигурации.

  • Удалить веб-сервис.

  • Отладчик.

Note

Переход к "История конфигурации" и "Отладчик" приведет к открытию различных страниц.

Клонирование веб-сервиса:

Для клонирования веб-сервиса необходимо нажать кнопку "Клонировать веб-сервис", появится диалоговое окно, в котором можно использовать имя по умолчанию или же установить новое имя для (клонируемого) веб-сервиса.

Note

Запомните название веб-сервиса должно быть уникальным для всей системы.

Нажмите кнопку "Клонировать" чтобы создать копию веб-сервиса или кнопку "Отменитьl", чтобы закрыть диалоговое окно.

Рисунок: Клонирование веб-сервиса.

Экспорт веб-сервиса

Кнопка "ЭКспорт веб-сервиса/Export web service" дает возможность выгрузить конфигурацию текущего веб-сервиса в файл формата YAML, для загрузки его и сохранения в файловой системе. Это может быть особенно полезно, если вы желаете перенести веб сервис с одного сервера на другой, к примеру, из тесторой среды в рабочую.

Warning

Все сохраненные пароли в настройках веб-сервиса будут экспортированы в виде обычного текста.

Сразу же после нажатия кнопки "Экспорт веб-сервиса" появится диалоговое окно сохранения, на подобе того, которое появляется когда вы нажимаете в браузере ссылку сохранить.

Note

Каждый браузер в каждой операционной системе имеет свои собственные экраны диалога при сохранении и их вид. В зависимости от браузера и его настроек, возможен вариант, когда дилог при сохранении не отображается и файл сохраняется в каталоге по умолчанию для вашей файловой системы. Обратитесь к к докментации на браузер для уточнения этих моментов.

Рисунок: Экспорт веб-сервиса.

Импорт веб-сервиса:

Для загрузки имеющегося YAML файла конфигурации веб-сервиса требуется использование функции импорта. Нажмите кнопку "Импорт веб-сервиса", найдите нужный файл или укажите полный путь к нему в окне ввода

Нажмите кнопку "Импорт" чтобы создать новый веб-сервис с файла или кнопку "Отменить" чтобы закрыть диалоговое окно.

Note

Имя веб-сервиса будет взято из имени конфигурационного файла (напрмер, если имя файла MyWebservice.yml, то имя веб-сервиса будет - MyWebservice). Если в сисеме уже зарегистрирован веб-сервис с таким именем, система откроет экран изменения веб-сервиса, чтобы вы могли поменять имя импортируемого веб-сервиса.

Рисунок: Импорт веб-сервиса.

История веб-сервиса

Каждое изменение настроек веб-сервиса порождает новую запись в истории веб-сервиса (типа журнала). Экран истории веб-сервиса отображает список всех версий конфигурации для веб-сервиса. Каждая строка (версия) в "Истории конфигурации" представляет одно изменение в истории веб-сервиса.

Нажатие на конкретную строку приводит к показу всей конфигурации на конкретную дату/время. Конфигурация отображается в секции "Детали истории" на этом экране. На этом экране вы также имеете возможность экспортировать выбранную версию конфигурации веб-сервиса или восстановить эту версию, сделав ее текущей.

"Экспортировать настройки веб-сервиса" ведет себя точно так же как "Экспортировать веб-сервис". Для более подробной информации обратитесь к этому разделу.

Если сделанные изменения в конфигурации веб-сервиса приводят к неправильным результатам и исправить вручную сделанные изменения затруднительно, вы можете нажать на кнопку "Вернуть конфигурацию веб-сервиса". Нажатие приведет к открытию диалогового окна с вопросом, действительно ли вы желаете вернуться к предыдущей версии. Нажмите на кнопку "Вернуть конфигурацию веб-сервиса" в этом окне для замены текущей конфигурации выбранной версией или нажмите "Отменить" для закрытия окна.

Warning

Помните, что все пароли сохраненные в конфигурации веб-сервиса будут экспортироваться в виде обычного текста.

Пожалуйста, будьте внимательны при восстановление параметров конфигурации, эта операция не может быть отменена.

Рисунок: История веб-сервиса

Удаление веб-сервиса

Иногда возникает необходимость удалить веб-сервис полностью. Для этого можно нажать кнопку "Удалить веб-сервис", появится диалоговое окно с вопросом о подтверждении операции.

Кликните на кнопку "Удалить" чтобы подтвердить удаление веб-сервиса или кнопку "Отменить" чтобы закрыть диалоговое окно.

Warning

Операция удаления веб-сервиса не может быть отменена, пожалуйста, будьте внимательны при удалении веб-сервисов.

Рисунок: Удаление веб-сервиса

Отладчик веб-сервиса:

Отладчик хранит журнал веб-сервиса. На странице отладчика можно следить за всеми связями веб-сервера, когда он работает в роли поставщика и получателя.

Когда отображается эта страница начинает загружаться список запросов. После того как список будет полность загружен, можно выбрать одну из строк (что означает последовательность связей) и просмотреть подробню информацию. Эта информация будет отображаться во всплывающем окне ниже.

Можно сузить список используя фильтр в правой части страницы. Фильтрацию можно производить по:

  • Тип связи (поставщик или запрашиваемая сторона)

  • Дата: до и / или после определенной даты

  • Удаленный IP-адрес

  • Сочетание всех.

После того как настройки фильтра завершены, нажмите кнопку "Обновить" и новый список, отвечающий вашим критериям будет отображен.

Note

В зависимости от критериев поиска установленых в фильтре, новый поиск может вернуть пустой список.

В левой части экрана, под фреймом действий, вы можете выбрать "Вернуться к веб-сервису" или очистить журнал отладки, нажатием на кнопку "Очистить". При этом откроется диалоговое окно, где вас попросят подтвердить очистку журнала. Нажмите "Очистить" в диалоговом окне для выполнения этого действия или "Отменить" для закрытия диалога.

В разделе "Подробности Запроса" можно просматривать подробную информацию о комуникации. Здесь можно следить за полным потоком и проверять всевозможные ошибки или подтвержать успешные ответы.

Рисунок: Отладчик веб-сервиса.

Изменение настроек веб-службы

Возвратившись на экран изменения, перейдем к обзору правой его части. Здесь вы имеете возможность изменить все основные данные веб-сервиса, такие как имя, уровень отладки и т.д. Также, здесь, ниже, имеются еще две секции позволяющие изменить специальные параметры для типа связи "OTRS как провайдер" и "OTRS как получатель".

The web service configuration needs to be saved on each level. This means that if a setting is changed, links to other, deeper parts of the configuration will be disabled forcing you to save the current configuration level. After saving the disabled links will be re-enabled again allowing you to continue with the configuration.

On the "OTRS as provider" section it is possible to set or configure the network transport protocol. Only network transport back-ends that are registered are shown on the list. To configure the network transport click on the "Configure" button. It is also possible to add new operations in this box. To do this select one of the available operations from the "Add Operation" list. This will lead you to the operation configuration screen. After saving the new operation it will be listed in the table above.

"OTRS как запрашивающая сторона" очень похож на предыдущий, но вместо "операций" здесь можно добавить invokers

Нажмите кнопку "Сохранить" для сохранения и продолжения настройки веб-сервиса. "Сохранить и продолжить" - для сохранения и возврата в окно обзора веб-сервисов, или "Отменить" для отмены, сделанных на этом уровне, изменений и возврата к окну обзора веб-сервисов.

Рисунок: Изменения веб-службы.

Note

Like the other Generic Interface configuration screens such as Network Transport, Operation, Invoker and Mapping, the initial configuration (add) screen will only present two options: "Save" and "Cancel". If the configuration is re-visited, a new option "Save and Finish" will appear. The behavior of this feature is defined below.

"Сохранить и Закончить" сохранит настройки текущего уровеня в базе данных и вернет к предыдущей странице в иерархии конфигурации.

"Save and Finish" сохнанит текущий уровень настроек в базе данных и вернется к предыдущей странице в иерархии конфигурации.

"Отменить" будет отменять любые изменения конфигурации и возвращать их к текущему уровню конфигурации, после чего возвращаться на к предыдущему экрану в иерархии настроек.

Транспортаня сеть Веб-сервиса

In future the list of available network transports will be increased. Currently only "HTTP::SOAP" and "HTTP::REST" transports are available. Each transport has different configuration options to setup and they might use different frontend modules to configure them,

It is quite simple to configure the "HTTP::SOAP" protocol as provider. There are only two settings: "Namespace" and "Maximum message length". These fields are required. The first one is a URI to give SOAP methods a context, reducing ambiguities, and the second one is a field where you can specify the maximum size (in bytes) for SOAP messages that OTRS will process.

Figure: Web service provider network transport HTTP::SOAP.

For "HTTP::REST" the configuration might be a bit more complicated, as it grows dynamically for each configured operation by adding: "Route mapping for Operation '<OperationName>':" and "Valid request methods for Operation '<OperationName>':" settings to the default transport settings "Maximum message length:" and "Send Keep-Alive:"

  • Карта маршрута для выполнения операции '<OperationName>':

    In this setting a resource path is set. This path must be defined according to the needs of the web service considering that the path in conjunction with the HTTP request method determines the Generic Interface operation to be executed.

    Путь может содержать переменные в виде ':<ИмяПеременной>' каждая строка части пути заполняемая вместо переменной будет добавлена к запросу, используя имя переменной заданной в этом параметре.

    Примеры:

    Карта маршрута: /Resource

    • Допустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource?Param1=One

    • Недопустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherResource

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherResource?Param1=One

    Карта маршрута: /Resource/:ID

    • Допустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/1

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/1?Param1=One

      In both cases ID = 1 will be sent to the operation as part of the payload. In the second case also Param1 = One will be added, depending on the HTTP request method other parameters will be added if they come as a JSON string in the request header.

    • Недопустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource?Param1=One

    Карта маршрута: /Resource/OtherResource/:ID/:Color

    • Допустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherResource/1/Red

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherReosurce/123/Blue?Param1=One

      В первом примере ID = 1 and Цвет = Красный, тогда как во втором ID = 123 and Цвет = Синий.

    • Недопустимые запросы:

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/1

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherResource/1

      http://localhost/otrs/nph-genericinterface.pl/Webservice/Test/Resource/OtherResource/1?Param1=One

      In the first example the part of the path '/OtherResource' is missing as well as the :Color variable, on the second example just :Color variable is missing.

  • Допустимые методы запроса для Операции '<ИмяОперации>':

    The HTTP request methods to determine the operation to use together with the route mapping, possible options: CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT and TRACE.

    Totally different operations can share exactly the same mapping path, but the request method must be unique for each operation, in order to determine correctly the operation to use on each request.

Figure: Web service provider network transport HTTP::REST.

Операции веб-сервиса

The actions that can be performed when you are using OTRS as a provider are called "Operations". Each operation belongs to a controller. Controllers are collections of operations or invokers, normally operations from the same controller need similar settings and share the same configuration dialog. But each operation can have independent configuration dialogs if needed.

Name, Description, Backend, and Mappings are fields that normally appear on every operation, other special fields can appear in non default configuration dialogs to fulfill specific needs of the operation.

Normally there are two mapping configuration sections on each operation, one for the incoming data and another one for the outgoing data. You can choose different mapping types (backends) for each mapping direction, since their configuration is independent from each other and also independent from the operation backend. The normal and most common practice is that the operation uses the same mapping type in both cases (with inverted configuration). The complete mapping configuration is done in a separate screen which depends on the mapping type.

The operation backend is pre-populated and is not editable. You will see this parameter when you choose the operation on the web service edit screen. The field is only informative.

In the left part of the screen on the action column you have the options: "Go back to web service" (discarding all changes since the last save) and "Delete". If you click on the last one, a dialog will open and ask you if you like to remove the operation. Click on "Delete" button to confirm the removal of the operation and it configuration or "Cancel" to close the delete dialog.

Рисунок: Операции веб-сервиса

Web Service Requester Network Transport

The network transport configuration for the requester is similar to the configuration for the provider. For the Requester "HTTP::SOAP" network transport there are more fields to be set.

Apart from the "Endpoint" (URI of the Remote System web service interface to accept requests) and "Namespace" which are required fields, you can also specify:

  • Кодировка (такая как utf-8, latin1, iso-8859-1, cp1250, и т.д.) для SOAP-сообщений.

  • SOAPAction Header: you can use this to send an empty or filled SOAPAction header. Set to "No" and the SOAPAction header on the SOAP message will be an empty string, or set to "Yes" to send the soap action in Namespace#Action format and define the separator (typically "/" for .Net web services and "#" for the rest).

  • Аутентификация: установить механизм аутентификации, установлено в "-" чтобы не использовать любую проверку подлинности или выбрать ее из списка, после чего появится поле с подробной информацией.

Note

Currently only the "BasicAuth" (HTTP) authentication mechanism is implemented. You can decide whether or not to use it depending on the Remote System configuration. If used, you must provide the User Name and the Password to access the remote system.

Warning

Если вы используете пароль для аутентификации, то при экспорте настроек веб-сервиса в YAML-файл этот пароль будет раскрыт и записан в виде простой текстовой строки внутри файла YAML. Знайте об этом и примите меры предосторожности в случае необходимости.

Figure: Web service requester network transport (HTTP::SOAP).

In the case of HTTP::Rest, this configuration also grows dynamically depending on the configured invokers by adding "Controller mapping for Invoker '<InvokerName>':" and "Valid request command for Invoker '<InvokerName>':" for each invoke. Authentication and SSL options are similar to the ones in HTTP::SOAP

  • Сервер

    Имя хоста/сервера или IP адрес и порт удаленной системы, если порт не задан, по умолчанию используется порт 80.

  • Controller mapping for Invoker '<InvokerName>':

    In this setting a resource path is set. This path must be defined according to the needs of the remote web service and following its definition.

    Path can contain variables in the form of ':<VariableName>' for each variable name that matches the current data (to be sent), will be replaced by the corresponding data value. This matched variable names and values will be remove from the current data. Depending on the HTTP request command the remaining data could be sent as a JSON string in the request body or as query parameters within the URI.

    Примеры:

    Для данных: Var1 = One, Var2 = Two, Var3 = Three and Var4 = Four.

    Controller mapping: /Resource

    • После замен:

      /Resource

    • Оставшиеся данные:

      Var1 = One, Var2 = Two, Var3 = Three and Var4 = Four

    Controller mapping: /Resource/:Var1

    • После замен:

      /Resource/One

    • Оставшиеся данные:

      Var2 = Two, Var3 = Three and Var4 = Four

    Controller mapping: /Resource/:Var1?Param1=:Var2&Var3=:Var3

    • После замен:

      /Resource/One?Param1=Two&Var3=Three

    • Оставшиеся данные:

      Var4 = Four

  • Допустимая команда запроса для Вызова '<ИмяВызова>':

    This determine the HTTP request method to use, possible options: CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT and TRACE. If no command is selected, Default command is used.

  • Команда по умолчанию

    Used as a fall-back for all Invokers with out a defined request command

Figure: Web service provider network transport HTTP::REST.

Вызов веб-сервиса:

The actions that can be performed when you are using OTRS as a requester are called "Invokers". Each invoker belongs to a controller (controllers are collections of operations or invokers). Usually invokers from the same controller need similar settings and share the same configuration dialogs. Each invoker can have independent configuration dialogs if needed.

Name, Description, Backend, and Mappings are fields that normally appear on every invoker. Additionally the list of event triggers and other special fields can appear on non default configuration dialogs to fulfill special needs of the invoker.

Normally there are two mapping configuration sections for each invoker, one for the incoming data and another one for the outgoing data. You can choose different mapping types (backends) for each mapping direction, since their configuration is independent from each other and also independent from the invoker backend. The normal and most common practice is that the invoker uses the same mapping type in both cases, with inverted configuration. The complete mapping configuration is done in a separate screen, which depends on the mapping type.

The invoker backend is pre-populated and can not be edited. You will see this parameter when you choose the invoker on the web service edit screen. The field is only informative.

Event triggers are events within OTRS such as "TicketCreate", "ArticleSend", etc. These can act as triggers to execute the invoker. Each invoker needs to have at least one event trigger registered, or the invoker will be useless, because it will never be called. The asynchronous property of the event triggers define if the OTRS process will handle the invoker or if it will be delegated to the OTRS Scheduler.

Note

The OTRS Scheduler is a separate process that executes tasks in the background. Using this the OTRS process itself will not be affected if the Remote System takes a long time to respond, if it is not available or if there are network problems. If you don't use the scheduler using web services can make OTRS slow or non-responsive. Therefore it is highly recommend to use asynchronous event triggers as often as possible.

To add an Event trigger, first select the event family from the first list, then the event name from the second list, then set the asynchronous property (if unchecked means that the event trigger will not be asynchronous) and finally click on the plus button. A new event trigger will be created and it will be listed on the invoker "Event Triggers" list.

To delete an Event trigger, simply locate the event trigger to be deleted in the "Event Triggers" list and click on the trash icon at the end of the row. This will open a dialog that asks you if you are sure to delete the event trigger. Click "Delete" to remove the event trigger from the list, or "Cancel" to close the dialog.

In the left part of the screen on the action column you have the options: "Go back to web service" (discarding all changes since the last save) and "Delete". If you click on the last one, a dialog will emerge and ask you if you like to remove the invoker. Click on the "Delete" button to confirm the removal of the invoker and its configuration or "Cancel" to close the delete dialog.

Рисунок: Web service invoker.

Веб Сервис

There are cases where you need to transform the data from one format to another (map or change data structure), because normally a web service is used to interact with a Remote System, that is highly probable that is not another OTRS system and / or could not understand the OTRS data structures and values. In these cases some or all values have to be changed, and sometimes even the names of the values (keys) or even the complete structure, in order to match with the expected data on the other end. To accomplish this task the Generic Interface Mapping Layer exists.

Each Remote System has it own data structures and it is possible to create new mapping modules for each case (e.g. there is a customized mapping module for SAP Solution Manager shipped with OTRS), but it is not always necessary. The module Mapping::Simple should cover most of the mapping needs.

Note

When Mapping::Simple does not cover all mapping needs for a web service, a new mapping module should be created. To learn more about how to create new mapping modules please consult the OTRS Development Manual.

Этот модуль дает возможность установить значение для отображения по умолчанию для каждого ключа или значения для всех передаваемых данных.

At the beginning of the screen you will see a general section where you can set the default rules that will apply for all the unmapped keys and values. There are three options available, these options are listed below:

  • Не изменять: не касается ключей и значений в любом случае.

  • Ignore (drop key/value pair): when this is applied to the key it deletes the key and value, because when a key is deleted then in consequence its associated value is deleted too. When this is applied to the value, only the value is deleted, keeping the key, that now will be associated to an empty value.

  • MapTo (use provided key or value as default): all keys and / or values without a defined map rule, will use this as default, when you select this option a new text field will appear to set this default.

Clicking on the "+" button for new key map, will display a new box for a single mapping configuration. You can add as many key mappings as needed. Just click on the "+" button again and a new mapping box will appear below the existing one. From this mapping boxes you can define a map for a single key, with the next options:

  • Точное значение(я): строка со старым значением будет заменена новой в случае полного совпадения "старого" ключа.

  • Регулярное выражение: строки будут изменены с помощью правила преобразования.

Pressing the new value map "+" button will display a new row for a value map. Here it is also possible to define rules for each value to be mapped with the same options as for the key map (Exact value and Regular expression). You can add as many values to map as needed, and if you want to delete one of them, just click on the "-" button for each mapping value row.

Удаление целого раздела ключей отображения возможно, просто нажмите на кнопку "-", расположеную в верхнем правом углу каждого окна, для которого вы хотите удалить.

If you need to delete a complete mapping configuration: go back to the corresponding operation or invoker screen, look for the mapping direction that you select before and set its value to "-", and save the configuration to apply changes.

Рисунок: Web service mapping.

Интерфейс командной строки Веб-Сервиса

Интерфейс командной строки (CLI) это быстрый путь для работы с веб-сервисами. Он состоит из набора инструментов, которые можно использовать для выполнения основных операций, таких как:

  • Создать, Обновить, Читать, Просматривать и Удалить веб-сервисы основаные основаные на YAML-файлах.

  • Чтение журнала Отладчика с опциями фильтрации.

Note

Нет нужды в использовании интерфейса командной строки для работы с веб-сервисами.Интерфейс администратора содержит полный набор экранов/разделов для взаимодействия с каждой из составляющих веб-сервисов. Читайте раздел описания по работе этого интерфейса/GUI, включенный в это руководство.

Конфигурация Веб-сервиса

Файл "WebserviceConfig.pl" был разработан для того чтобы создать простой, но в то же время быстрый и мощный инструмент для работы с настройками веб-сервиса. Он предоставляет возможность выполнять следующие действия:

  • Add: для создания веб-сервисов с использованием YAML-файлов в качестве источника конфигурации.

  • Update: изменить существующий веб-сервис, конфигурация может быть изменена с использованием других или измененных YAML-файлов.

  • Read: для вывода на экран текущих настроек веб-сервиса.

  • List: чтобы получить полный список всех веб-сервисов, зарегистрированных в системе.

  • Delete: для удаления веб-сервиса из системы. Будьте осторожны при выполнении этой операции, ее невозможно отменить.

Warning

Операция веб-сервиса READ будет отображать на экране все настройки в виде простого текста, включаяя сохраненные пароли. Помните об этом и соблюдайте необходимые меры предосторожности!

Пример: Создание новой конфигурации веб-сервиса:

shell> OTRS_HOME/bin/otrs.WebserviceConfig.pl -a write -n <webservice_name> -f /path/to/yaml/file
            

Также можно использовать файл 'otrs.WebserviceConfig.pl' со следующими опциями:

  • -a read -i <webservice_id> - Для чтения сохраненной конфигурации.

  • -a write -n <webservice_name> -f /path/to/yaml/file - Для создания нового веб-сервиса.

  • -a write -i <webservice_id> -f /path/to/yaml/file - Для обновления веб-сервиса.

  • -a list - Для просмотра списка доступных веб-сервисов.

  • -a delete -i <webservice_id> - Для удаления веб-сервиса.

Отладчик веб-сервиса:

Еще одним доступным инструментом командной строки является скрипт "otrs.GenericInterfaceDebugRead.pl", который предоставляет интерфейс для для поиска записей в журнале отладчика веб-сервиса.

Пример: Поиск записей в журнале отладчика:

                shell> bin/otrs.GenericInterfaceDebugRead.pl
            

Дополнительные параметры могут быть использованы для сценария "otrs.GenericInterfaceDebugRead.pl":

  • -c - для фильтрации по Communication ID (md5sum формат).

  • -t - для фильтрации по CommunicationType ('Provider' или 'Requester').

  • -a - для фильтрации по дате (На текущую дату или После нее).

  • -b - для фильтрации по дате (на текущую дату или До нее).

  • -i - для фильтрации по IP-адресу (должен быть правильный IPv4 или IPv6 адрес).

  • -w - для фильтрации по ID веб-сервиса.

  • -d - включить подробные передаваемые данные.

Пример: Поиск записей журнала отладчика со всеми параметрами:

shell> ./otrs.GenericInterfaceDebugRead.pl -c a7cc4d9f5c70387a9bfbe1351bc88966 -t Provider -a '2011-07-22 00:00:00' -b '2011-07-26 00:00:00' -i 127.0.0.1 -w 123 -d 1
            

Note

Настоятельно рекомендуем включать, как минимум один из параметров фильтрации, перечисленных выше, или даже больше, еслы выбран ключ "-d", т.к. большое количество информации может быть получено и отображаться на экране, что приведет в большому времени ожидания и получению избыточной информации.

Конфигурация Веб-сервиса

From its design the web services were conceived to be portable from one OTRS system to another, e.g. from a test or development environment to a production system. Therefore it was needed to have an easy way to extract the web service configuration from the database, and import it to another. To accomplish this task the Generic Interface uses YAML files as the web services configuration basis.

Почему YAML? YAML это язык разметки, разработанный специально человекочитаемым и удобным для написания (он более понятен чем JSON), не имеет некоторых ограничений XML, таких как числовые тэги, он открыт, стандартизован и полностью удовлетворяет задаче хранения всех настроек веб-сервисов.

Note

Чтобы узнать больше о YAML пожалуйста посетите ссылку http://www.yaml.org/.

Ниже приводится конфигурация веб-сервера на основе файла конфигурации в форматеYAML:

---
Debugger:
  DebugThreshold: debug
Description: This an example of a web service configuration
Provider:
  Operation:
    CloseIncident:
      Description: This is a test operation
      MappingInbound: {}
      MappingOutbound: {}
      RemoteSystemGuid: ''
      Type: Test::Test
    Test:
      Description: This is a test operation
      MappingInbound:
        Config:
          KeyMapDefault:
            MapTo: ''
            MapType: Keep
          KeyMapExact:
            Prio: Priority
          ValueMap:
            Priority:
              ValueMapExact:
                Critical: 5 Very High
                Information: 1 Very Low
                Warning: 3 Normal
          ValueMapDefault:
            MapTo: 3 Normal
            MapType: MapTo
        Type: Simple
      MappingOutbound:
        Config:
          KeyMapDefault:
            MapTo: ''
            MapType: Ignore
          KeyMapExact:
            Priority: Prio
          ValueMap:
            Prio:
              ValueMapExact:
                1 Very Low: Information
                3 Normal: Warning
                5 Very High: Critical
          ValueMapDefault:
            MapTo: ''
            MapType: Ignore
        Type: Simple
      Type: Test::Test
  Transport:
    Config:
      MaxLength: 10000000
      NameSpace: http://www.example.com/actions
    Type: HTTP::SOAP
RemoteSystem: remote.system.description.example.com
Requester:
  Invoker:
    Test:
      Description: This is a test invoker
      Events:
        - Asynchronous: 1
          Event: TicketCreate
        - Asynchronous: 0
          Event: ArticleUpdate
      MappingInbound:
        Type: Simple
      MappingOutbound:
        Type: Simple
      Type: Test::Test
  Transport:
    Config:
      Authentication:
        Password: '*******'
        Type: BasicAuth
        User: otrs
      Encoding: utf-8
      Endpoint: http://www.example.com:8080/endpoint
      NameSpace: http://www.example.com/actions
      SOAPAction: Yes
      SOAPActionSeparator: '#'
    Type: HTTP::SOAP
            
        

Описание Конфигурации

Общий
  • Описание: краткий текст, описывающий веб-сервис.

  • RemoteSystem: краткое описание Удаленной Системы.

  • Debugger: хранилище для хранения настроек отладчика.

  • Provider: хранилище для хранения настроек поставщика.

  • Requester: хранилище для хранения настроек о запрашивающей стороне.

Отладчик
  • DebugThreshold: уровень отладчика

    Возможные значения

    • debug: все журналы хранятся в базе данных.

    • info: информация, уведомления и журнал ошибкок хранятся в базе данных.

    • notice: ошибки уровня уведомление (notice) и ошибка (error) хранятся в базе данных.

    • error: только ошибки уровня error хранятся в базе данных.

Поставщик
  • Operation: хранилище для настроек каждой операции.

  • Transport: хранилище для настроек поставщика транспортой сети.

Операция
  • <OperationName>: Уникальное название операции, хранилище для своих собственных настроек (от 0..n, но без повторений).

<OperationName>

Этот раздел основан на операция с типом "Test::Test" другие операции могут содержать больше или другие настройки.

  • Описание: краткий текст, описывающий операцию.

  • MappingInbound: хранилище для настроек отображаемых данных для данных из входящего запроса.

  • MappingOutbound: хранилище для отображающихся настроек для исходящих данных.

  • Тип бэкэнд операция в формате Controller::Operation.

MappingInbound

Этот раздел основан на отображаемых значениях с типом "Simple". Другие отображаемые значения могут содержать больше или другие настройки.

  • Config: хранилище настроек для этих отображаемых значений.

  • Тип: mapping backend.

Config
  • KeyMapDefault: хранилище для всех не отображаемых значений ключей.

  • ValueMapDefault: хранилище для всех не отображаемых значений настроек.

  • KeyMapExact: хранилище для всех ключей точных отображаемых значений(от 0 .. 1).

  • KeyMapRegEx: хранилище для отображаемых значений всех регулярных выражений.

  • ValueMap: хранилище для всех значений отображений (mapping-a).

KeyMapDefault
  • MapTo: новое значение, которое будет использоваться (применима только если параметр MapType установлен в значение MapTo).

  • MapType: правило для отображения.

    Возможные значения

    • Keep: оставить без изменений.

    • Ignore: понизить.

    • MapTo: заменить на значение MapTo.

ValueMapDefault

Тоже что и KeyMapDefault.

KeyMapExact
  • <oldkey>: <newkey> (от 0 .. n но без повторений).

KeyMapRegEx
  • <oldkey(RegEx)>: <newkey> ( от 0 .. n но без повторений).

ValueMap
  • <newkey>: контейнер для отображаемых значений для этого нового ключа (зависит от новых ключей от KeyMapExact и KeyMapRegEx).

<newkey>
  • ValueMapExact: хранилище для всех точных отображаемых значений (от 0 .. 1).

  • ValueMapRegEx: хранилище для отображаемых значений всех регулярных выражений (от 0 .. 1).

valueMapExact
  • <oldvalue>: <newvalue> ( cardinality 0 .. n без повторений).

ValueMapRegEx
  • <oldvalue(RegEx)>: <newvalue> ( от 0 .. n без повторений).

MappingOutbound

Тоже что и MappingInbound.

Передача

Этот раздел основана на сетевом поставщике HTTP::SOAP, другие поставщики могут содержать больше или другие настройки.

  • Config: хранилище для конкретных параметров конфигурации транспортной сети.

  • Тип: бэкэнд транспортной сети поставщика.

Config
  • MaxLength: максимальная длина в байтах для чтения SOAP-сообщений системой OTRS.

  • NameSpace: URI , который дает контекст для всех операций, принадлежащих этому веб-сервису.

Запрашиваемая сторона
  • Invoker: хранилище для настроек каждой метки.

  • Transport: хранилище для настроек транспортной сети запрашивающей стороны.

Запрашивающая сторона
  • <InvokerName>: Уникальное имя для вызывающей стороны, хранилище для своих собственых настроек (от 0..n, без повторов).

<InvokerName>

Этот раздел основан на типе "Test::Test", другие invoker-ры могут иметь больше или другие настройки.

  • Описание: короткий текст для описания вызывающей стороны

  • События: хранилище настроек не именованного списка действий.

  • MappingInbound: хранилище для настроек отображаемых значений для данных поступающих от ответов.

  • MappingOutbound: хранилище для настроек отображаемых значений для исходящих данных запроса.

  • Тип: invoker backend, в формате Controller::Invoker.

События
  • List Element: (от 0 .. n)

    • Asynchronous: установить если вызов вызывающей стороны будет возложен на Планировщика

      Возможные значения

      • 0: не обрабатывается Планировщиком (Scheduler).

      • 1: Обрабатывается Планировщиком (Scheduler).

    • Event: имя события триггера.

      Возможные Значения (для событий заявки)

      • TicketCreate

      • TicketDelete

      • TicketTitleUpdate

      • TicketUnlockTimeoutUpdate

      • TicketQueueUpdate

      • TicketTypeUpdate

      • TicketServiceUpdate

      • TicketSLAUpdate

      • TicketCustomerUpdate

      • TicketFreeTextUpdate

      • TicketFreeTimeUpdate

      • TicketPendingTimeUpdate

      • TicketLockUpdate

      • TicketArchiveFlagUpdate

      • TicketStateUpdate

      • TicketOwnerUpdate

      • TicketResponsibleUpdate

      • TicketPriorityUpdate

      • HistoryAdd

      • HistoryDelete

      • TicketAccountTime

      • TicketMerge

      • TicketSubscribe

      • TicketUnsubscribe

      • TicketFlagSet

      • TicketFlagDelete

      • TicketSlaveLinkAdd

      • TicketSlaveLinkDelete

      • TicketMasterLinkDelete

      Возможные Значения (для действий над статьями)

      • Действия над статьями

      • ArticleCreate

      • ArticleFreeTextUpdate

      • ArticleUpdate

      • ArticleSend

      • ArticleBounce

      • ArticleAgentNotification

      • ArticleCustomerNotification

      • ArticleAutoResponse

      • ArticleFlagSet

      • ArticleFlagDelete

      • ArticleAgentNotification

      • ArticleCustomerNotification

MappingInbound

То же что и Действие MappingInbound

MappingOutbound

Тоже что и Действие MappingInbound.

Передача

Этот раздел основан на транспортной сети запрашивающей стороны HTTP::SOAP, транспортные сети могут содержать больше или другие настройки.

  • Config: хранилище для конкретных параметров конфигурации транспортной сети.

  • Тип: бэкэнд транспортной сети запрашивающей стороны.

Config
  • Аутентификация: хранилище для настроек аутентификации.

  • Encoding: кодирование сообщения SOAP-запроса

  • Endpoint: URI Уаделнного Сервера веб-службы для приема запросов OTRS.

  • NameSpace: URI который предоставлят связь для всех invoker-ов, которые принадлежат этому веб-серверу.

  • SOAPAction: для отправки пустого или заполненого SOAPAction-заголовка в формате SOAP сообщения (in "<NameSpace> <Separator> <Action>" format).

    Возможные значения

    • YES: для отправки заполненого заголовка SOAPAction.

    • No: для отправки пустого обработчика SOAP-действия.

  • SOAPActionSeparator: для установки <Separator> из заполненых SOAPAction заголовков.

    Возможные значения

    • '/': используется для .net веб-сервисов.

    • '#': используется для всех веб-сервисов на базе протокола REST.

Authentication
  • User: имя привилегированого пользователя, который имеет доступ к удаленному веб-сервису.

  • Пароль: пароль для привелигированого пользователя в формате обычного текста.

  • Тип: тип аутентификации.

Коннекторы (Connectors)

A Connector is in essence a set of actions that are either called Operations if OTRS acts as a web service provider or Invokers if OTRS acts as a web service requester. But it can also include special Mappings or Transports.

One Connector can either have only Operations, Only Invokers or both. A connector can even use parts of other connectors like the Mappings or Transports if they are not to specific for the Connector that is trying to implement them.

In other words a Connector is not limited to just the Controller layer but it can be extended to Data Mapping or Network Transport layers if needed.

Due to the modular design of the Generic Interface a Connector can be seen as a plug-in; this means that by adding Connectors the capabilities of the generic interface can be extended using: OTRS Feature add ons, OTRS Custom modules, 3rd Party modules, and so on.

Комплект Коннекторов (Connectors)

В комплекте с этой версией OTRS следующие коннекторы готовы к использованию.

  • Session

  • Заявк

Коннектор сессии

Этот коннектор может создать действительный SessionID, который в дальнейшем может быть использован в любой другой операции.

Поставщики:

  • Операции:

    • SessionCreate

Операции
SessionCreate

Creates a new new valid SessionID to be used in other operations from other connectors like TicketCreate.

Note

To use the SessionID in other operations from other connectors it is necessary that the operation implements authentication by SessionID. All the rest of the bundled operations are capable of accepting a valid SessionID as an authentication method.

Возможные Атрибуты:

                            
      <SessionCreate>
         <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <Password>?</Password>
      </SessionCreate>
                            
                        

Коннектор Заявки

Этот коннектор использует базовую функциональность для взаимодействия с заявками

Поставщики:

  • Операции:

    • TicketCreate

    • TicketUpdate

    • TicketGet

    • TicketSearch

Операции
TicketCreate

Предоставляет интерфейс для создания заявки в OTRS. Заявка должна содержать сообщение и может содержать несколько вложений, все заданные динамические поля, также могут получить значения при операции "Создать заявку/TicketCreate"

Возможные Атрибуты:

                            
      <TicketCreate>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <Ticket>
            <Title>?</Title>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <QueueID>?</QueueID>
            <!--Optional:-->
            <Queue>?</Queue>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <TypeID>?</TypeID>
            <!--Optional:-->
            <Type>?</Type>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ServiceID>?</ServiceID>
            <!--Optional:-->
            <Service>?</Service>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SLAID>?</SLAID>
            <!--Optional:-->
            <SLA>?</SLA>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <StateID>?</StateID>
            <!--Optional:-->
            <State>?</State>
            <!--You have a MANDATORY CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <PriorityID>?</PriorityID>
            <!--Optional:-->
            <Priority>?</Priority>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <OwnerID>?</OwnerID>
            <!--Optional:-->
            <Owner>?</Owner>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ResponsibleID>?</ResponsibleID>
            <!--Optional:-->
            <Responsible>?</Responsible>
            <CustomerUser>?</CustomerUser>
            <!--Optional:-->
            <CustomerID>?</CustomerID>
            <!--Optional:-->
            <PendingTime>
               <Year>?</Year>
               <Month>?</Month>
               <Day>?</Day>
               <Hour>?</Hour>
               <Minute>?</Minute>
            </PendingTime>
         </Ticket>
         <Article>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ArticleTypeID>?</ArticleTypeID>
            <!--Optional:-->
            <ArticleType>?</ArticleType>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SenderTypeID>?</SenderTypeID>
            <!--Optional:-->
            <SenderType>?</SenderType>
            <!--Optional:-->
            <From>?</From>
            <Subject>?</Subject>
            <Body>?</Body>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ContentType>?</ContentType>
            <Charset>?</Charset>
            <MimeType>?</MimeType>
            <!--Optional:-->
            <HistoryType>?</HistoryType>
            <!--Optional:-->
            <HistoryComment>?</HistoryComment>
            <!--Optional:-->
            <AutoResponseType>?</AutoResponseType>
            <!--Optional:-->
            <TimeUnit>?</TimeUnit>
            <!--Optional:-->
            <NoAgentNotify>?</NoAgentNotify>
            <!--Zero or more repetitions:-->
            <ForceNotificationToUserID>?</ForceNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeNotificationToUserID>?</ExcludeNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeMuteNotificationToUserID>?</ExcludeMuteNotificationToUserID>
         </Article>
         <!--Zero or more repetitions:-->
         <DynamicField>
            <Name>?</Name>
            <!--1 or more repetitions:-->
            <Value>?</Value>
         </DynamicField>
         <!--Zero or more repetitions:-->
         <Attachment>
            <Content>cid:61886944659</Content>
            <ContentType>?</ContentType>
            <Filename>?</Filename>
         </Attachment>
      </TicketCreate>
                            
                        

TicketUpdate

Операция "Изменение заявки/TicketUpdate" добавляет возможность изменения атрибутов существующей заявки или добавить новое сообщение/заметку, включая вложения и все определенные динамические поля для заявки и нового сообщения.

Note

Нет необходимости создавать новое сообщение/заметку для изменения атрибутов заявки.

Возможные Атрибуты:

                            
      <TicketUpdate>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--You have a CHOICE of the next 2 items at this level-->
         <TicketID>?</TicketID>
         <TicketNumber>?</TicketNumber>
         <!--Optional:-->
         <Ticket>
            <!--Optional:-->
            <Title>?</Title>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <QueueID>?</QueueID>
            <!--Optional:-->
            <Queue>?</Queue>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <TypeID>?</TypeID>
            <!--Optional:-->
            <Type>?</Type>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ServiceID>?</ServiceID>
            <!--Optional:-->
            <Service>?</Service>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SLAID>?</SLAID>
            <!--Optional:-->
            <SLA>?</SLA>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <StateID>?</StateID>
            <!--Optional:-->
            <State>?</State>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <PriorityID>?</PriorityID>
            <!--Optional:-->
            <Priority>?</Priority>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <OwnerID>?</OwnerID>
            <!--Optional:-->
            <Owner>?</Owner>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ResponsibleID>?</ResponsibleID>
            <!--Optional:-->
            <Responsible>?</Responsible>
            <!--Optional:-->
            <CustomerUser>?</CustomerUser>
            <!--Optional:-->
            <CustomerID>?</CustomerID>
            <!--Optional:-->
            <PendingTime>
               <Year>?</Year>
               <Month>?</Month>
               <Day>?</Day>
               <Hour>?</Hour>
               <Minute>?</Minute>
            </PendingTime>
         </Ticket>
         <!--Optional:-->
         <Article>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ArticleTypeID>?</ArticleTypeID>
            <!--Optional:-->
            <ArticleType>?</ArticleType>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <SenderTypeID>?</SenderTypeID>
            <!--Optional:-->
            <SenderType>?</SenderType>
            <!--Optional:-->
            <From>?</From>
            <Subject>?</Subject>
            <Body>?</Body>
            <!--You have a CHOICE of the next 2 items at this level-->
            <!--Optional:-->
            <ContentType>?</ContentType>
            <Charset>?</Charset>
            <MimeType>?</MimeType>
            <!--Optional:-->
            <HistoryType>?</HistoryType>
            <!--Optional:-->
            <HistoryComment>?</HistoryComment>
            <!--Optional:-->
            <AutoResponseType>?</AutoResponseType>
            <!--Optional:-->
            <TimeUnit>?</TimeUnit>
            <!--Optional:-->
            <NoAgentNotify>?</NoAgentNotify>
            <!--Zero or more repetitions:-->
            <ForceNotificationToUserID>?</ForceNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeNotificationToUserID>?</ExcludeNotificationToUserID>
            <!--Zero or more repetitions:-->
            <ExcludeMuteNotificationToUserID>?</ExcludeMuteNotificationToUserID>
         </Article>
         <!--Zero or more repetitions:-->
         <DynamicField>
            <Name>?</Name>
            <!--1 or more repetitions:-->
            <Value>?</Value>
         </DynamicField>
         <!--Zero or more repetitions:-->
         <Attachment>
            <Content>cid:166861569966</Content>
            <ContentType>?</ContentType>
            <Filename>?</Filename>
         </Attachment>
      </TicketUpdate>
                            
                        

TicketGet

Эта операция используется для получения всех атрибутов заявки, включая динамические поля, все сообщения и все вложения принадлежащие заявке.

Возможные Атрибуты:

                            
      <TicketGet>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--1 or more repetitions:-->
         <TicketID>?</TicketID>
         <!--Optional:-->
         <DynamicFields>?</DynamicFields>
         <!--Optional:-->
         <Extended>?</Extended>
         <!--Optional:-->
         <AllArticles>?</AllArticles>
         <!--Optional:-->
         <ArticleSenderType>?</ArticleSenderType>
         <!--Optional:-->
         <ArticleOrder>?</ArticleOrder>
         <!--Optional:-->
         <ArticleLimit>?</ArticleLimit>
         <!--Optional:-->
         <Attachments>?</Attachments>
         <!--Optional:-->
         <HTMLBodyAsAttachment>?</HTMLBodyAsAttachment>
      </TicketGet>
                            
                        

TicketSearch

Операция "ПоискЗаявки/TicketSearch" возвращает список всех Ticket IDs/Идентификаторов заявок, удовлетворяющих заданному критерию.

Возможные Атрибуты:

                            
      <TicketSearch>
         <!--You have a MANDATORY CHOICE of the next 3 items at this level-->
         <!--Optional:-->
         <UserLogin>?</UserLogin>
         <!--Optional:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Optional:-->
         <SessionID>?</SessionID>
         <!--Optional:-->
         <Password>?</Password>
         <!--Optional:-->
         <Limit>?</Limit>
         <!--Zero or more repetitions:-->
         <TicketNumber>?</TicketNumber>
         <!--Zero or more repetitions:-->
         <Title>?</Title>
         <!--Zero or more repetitions:-->
         <Queues>?</Queues>
         <!--Zero or more repetitions:-->
         <QueueIDs>?</QueueIDs>
         <!--Optional:-->
         <UseSubQueues>?</UseSubQueues>
         <!--Zero or more repetitions:-->
         <Types>?</Types>
         <!--Zero or more repetitions:-->
         <TypeIDs>?</TypeIDs>
         <!--Zero or more repetitions:-->
         <States>?</States>
         <!--Zero or more repetitions:-->
         <StateIDs>?</StateIDs>
         <!--Zero or more repetitions:-->
         <StateType>?</StateType>
         <!--Zero or more repetitions:-->
         <StateTypeIDs>?</StateTypeIDs>
         <!--Zero or more repetitions:-->
         <Priorities>?</Priorities>
         <!--Zero or more repetitions:-->
         <PriorityIDs>?</PriorityIDs>
         <!--Zero or more repetitions:-->
         <Services>?</Services>
         <!--Zero or more repetitions:-->
         <ServiceIDs>?</ServiceIDs>
         <!--Zero or more repetitions:-->
         <SLAs>?</SLAs>
         <!--Zero or more repetitions:-->
         <SLAIDs>?</SLAIDs>
         <!--Zero or more repetitions:-->
         <Locks>?</Locks>
         <!--Zero or more repetitions:-->
         <LockIDs>?</LockIDs>
         <!--Zero or more repetitions:-->
         <OwnerIDs>?</OwnerIDs>
         <!--Zero or more repetitions:-->
         <ResponsibleIDs>?</ResponsibleIDs>
         <!--Zero or more repetitions:-->
         <WatchUserIDs>?</WatchUserIDs>
         <!--Zero or more repetitions:-->
         <CustomerID>?</CustomerID>
         <!--Zero or more repetitions:-->
         <CustomerUserLogin>?</CustomerUserLogin>
         <!--Zero or more repetitions:-->
         <CreatedUserIDs>?</CreatedUserIDs>
         <!--Zero or more repetitions:-->
         <CreatedTypes>?</CreatedTypes>
         <!--Zero or more repetitions:-->
         <CreatedTypeIDs>?</CreatedTypeIDs>
         <!--Zero or more repetitions:-->
         <CreatedPriorities>?</CreatedPriorities>
         <!--Zero or more repetitions:-->
         <CreatedPriorityIDs>?</CreatedPriorityIDs>
         <!--Zero or more repetitions:-->
         <CreatedStates>?</CreatedStates>
         <!--Zero or more repetitions:-->
         <CreatedStateIDs>?</CreatedStateIDs>
         <!--Zero or more repetitions:-->
         <CreatedQueues>?</CreatedQueues>
         <!--Zero or more repetitions:-->
         <CreatedQueueIDs>?</CreatedQueueIDs>
         <!--Zero or more repetitions:-->
         <DynamicFields>
            <!--You have a MANDATORY CHOICE of the next 6 items at this level-->
            <!--Optional:-->
            <Equals>?</Equals>
            <!--Optional:-->
            <Like>?</Like>
            <!--Optional:-->
            <GreaterThan>?</GreaterThan>
            <!--Optional:-->
            <GreaterThanEquals>?</GreaterThanEquals>
            <!--Optional:-->
            <SmallerThan>?</SmallerThan>
            <!--Optional:-->
            <SmallerThanEquals>?</SmallerThanEquals>
         </DynamicFields>
         <!--Optional:-->
         <Ticketflag>
            <!--Optional:-->
            <Seen>?</Seen>
         </Ticketflag>
         <!--Optional:-->
         <From>?</From>
         <!--Optional:-->
         <To>?</To>
         <!--Optional:-->
         <Cc>?</Cc>
         <!--Optional:-->
         <Subject>?</Subject>
         <!--Optional:-->
         <Body>?</Body>
         <!--Optional:-->
         <FullTextIndex>?</FullTextIndex>
         <!--Optional:-->
         <ContentSearch>?</ContentSearch>
         <!--Optional:-->
         <ConditionInline>?</ConditionInline>
         <!--Optional:-->
         <ArticleCreateTimeOlderMinutes>?</ArticleCreateTimeOlderMinutes>
         <!--Optional:-->
         <ArticleCreateTimeNewerMinutes>?</ArticleCreateTimeNewerMinutes>
         <!--Optional:-->
         <ArticleCreateTimeNewerDate>?</ArticleCreateTimeNewerDate>
         <!--Optional:-->
         <ArticleCreateTimeOlderDate>?</ArticleCreateTimeOlderDate>
         <!--Optional:-->
         <TicketCreateTimeOlderMinutes>?</TicketCreateTimeOlderMinutes>
         <!--Optional:-->
         <ATicketCreateTimeNewerMinutes>?</ATicketCreateTimeNewerMinutes>
         <!--Optional:-->
         <TicketCreateTimeNewerDate>?</TicketCreateTimeNewerDate>
         <!--Optional:-->
         <TicketCreateTimeOlderDate>?</TicketCreateTimeOlderDate>
         <!--Optional:-->
         <TicketLastChangeTimeOlderMinutes>?</TicketLastChangeTimeOlderMinutes>
         <!--Optional:-->
         <TicketLastChangeTimeNewerMinutes>?</TicketLastChangeTimeNewerMinutes>
         <!--Optional:-->
         <TicketLastChangeTimeNewerDate>?</TicketLastChangeTimeNewerDate>
         <!--Optional:-->
         <TicketLastChangeTimeOlderDate>?</TicketLastChangeTimeOlderDate>
         <!--Optional:-->
         <TicketChangeTimeOlderMinutes>?</TicketChangeTimeOlderMinutes>
         <!--Optional:-->
         <TicketChangeTimeNewerMinutes>?</TicketChangeTimeNewerMinutes>
         <!--Optional:-->
         <TicketChangeTimeNewerDate>?</TicketChangeTimeNewerDate>
         <!--Optional:-->
         <TicketChangeTimeOlderDate>?</TicketChangeTimeOlderDate>
         <!--Optional:-->
         <TicketCloseTimeOlderMinutes>?</TicketCloseTimeOlderMinutes>
         <!--Optional:-->
         <TicketCloseTimeNewerMinutes>?</TicketCloseTimeNewerMinutes>
         <!--Optional:-->
         <TicketCloseTimeNewerDate>?</TicketCloseTimeNewerDate>
         <!--Optional:-->
         <TicketCloseTimeOlderDate>?</TicketCloseTimeOlderDate>
         <!--Optional:-->
         <TicketPendingTimeOlderMinutes>?</TicketPendingTimeOlderMinutes>
         <!--Optional:-->
         <TicketPendingTimeNewerMinutes>?</TicketPendingTimeNewerMinutes>
         <!--Optional:-->
         <TicketPendingTimeNewerDate>?</TicketPendingTimeNewerDate>
         <!--Optional:-->
         <TicketPendingTimeOlderDate>?</TicketPendingTimeOlderDate>
         <!--Optional:-->
         <TicketEscalationTimeOlderMinutes>?</TicketEscalationTimeOlderMinutes>
         <!--Optional:-->
         <TTicketEscalationTimeNewerMinutes>?</TTicketEscalationTimeNewerMinutes>
         <!--Optional:-->
         <TicketEscalationTimeNewerDate>?</TicketEscalationTimeNewerDate>
         <!--Optional:-->
         <TicketEscalationTimeOlderDate>?</TicketEscalationTimeOlderDate>
         <!--Optional:-->
         <ArchiveFlags>?</ArchiveFlags>
         <!--Zero or more repetitions:-->
         <OrderBy>?</OrderBy>
         <!--Zero or more repetitions:-->
         <SortBy>?</SortBy>
         <!--Zero or more repetitions:-->
         <CustomerUserID>?</CustomerUserID>
      </TicketSearch>
                            
                        

Примеры:

Конфигурация Веб-сервиса

The following is a basic but complete web service configuration file in YAML format to use all the Ticket Connector operations with the SOAP network transport. In order to use it in OTRS you need to copy the content, save it into a file and call it GenericTicketConnectorSOAP.yml, and import it into OTRS in the Web Services screen in the Admin panel by clicking in the "Add web service" action from the overview screen and then clicking in the "Import web service" action in the add screen.

                    
---
Debugger:
  DebugThreshold: debug
  TestMode: 0
Description: Ticket Connector SOAP Sample
FrameworkVersion: 3.4.x git
Provider:
  Operation:
    SessionCreate:
      Description: Creates a Session
      MappingInbound: {}
      MappingOutbound: {}
      Type: Session::SessionCreate
    TicketCreate:
      Description: Creates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketCreate
    TicketUpdate:
      Description: Updates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketUpdate
    TicketGet:
      Description: Retrieve Ticket data
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketGet
    TicketSearch:
      Description: Search for Tickets
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketSearch
  Transport:
    Config:
      MaxLength: 100000000
      NameSpace: http://www.otrs.org/TicketConnector/
    Type: HTTP::SOAP
RemoteSystem: ''
Requester:
  Transport:
    Type: ''
                    
                

Similar example can be done for the REST network transport, REST web services uses HTTP operations such as "POST", "GET", "PUT", "PATCH" etc. This operations in conjunction with a URI path called resource defines a OTRS Generic Interface Operation or Invoker (depending on the communication way).

The following example uses /Session resource for SessionCreate, /Ticket resource for TicketSearch and TicketCreate and resource /Ticket/{TicketID} for TicketGet and TicketUpdate (Where {TicketID} is the actual TicketID value of a ticket e.g. /Ticket/123). In order to use it in OTRS you need to copy the content, save it into a file and call it GenericTicketConnectorREST.yml, and import it into OTRS in the Web Services screen in the Admin panel by clicking in the "Add web service" action from the overview screen and then clicking in the "Import web service" action in the add screen.

                    
---
Debugger:
  DebugThreshold: debug
  TestMode: '0'
Description: Ticket Connector REST Sample
FrameworkVersion: 3.4.x git
Provider:
  Operation:
    SessionCreate:
      Description: Creates a Session
      MappingInbound: {}
      MappingOutbound: {}
      Type: Session::SessionCreate
    TicketCreate:
      Description: Creates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketCreate
    TicketGet:
      Description: Retrieves Ticket data
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketGet
    TicketSearch:
      Description: Search for Tickets
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketSearch
    TicketUpdate:
      Description: Updates a Ticket
      MappingInbound: {}
      MappingOutbound: {}
      Type: Ticket::TicketUpdate
  Transport:
    Config:
      KeepAlive: ''
      MaxLength: '100000000'
      RouteOperationMapping:
        SessionCreate:
          RequestMethod:
          - POST
          Route: /Session
        TicketCreate:
          RequestMethod:
          - POST
          Route: /Ticket
        TicketGet:
          RequestMethod:
          - GET
          Route: /Ticket/:TicketID
        TicketSearch:
          RequestMethod:
          - GET
          Route: /Ticket
        TicketUpdate:
          RequestMethod:
          - PATCH
          Route: /Ticket/:TicketID
    Type: HTTP::REST
RemoteSystem: ''
Requester:
  Transport:
    Type: ''
                    
                

Запрашивающая сторона Perl SOAP

The following code is a Perl script that can connect to OTRS via the generic interface. In order to perform the operations provided by the Ticket Connector, it uses two Perl CPAN modules SOAP::Lite and Data::Dumper. Please make sure that your environment is capable to use these modules before you try to run the script.

                    
#!/usr/bin/perl -w
# --
# otrs.SOAPRequest.pl - sample to send a SOAP request to OTRS Generic Interface Ticket Connector
# Copyright (C) 2001-2018 OTRS AG, https://otrs.com/
# --
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see https://www.gnu.org/licenses/gpl-3.0.txt.
# --

use strict;
use warnings;

# use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use SOAP::Lite;
use Data::Dumper;

# ---
# Variables to be defined.

# this is the URL for the web service
# the format is
# <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl/Webservice/<WEB_SERVICE_NAME>
# or
# <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl/WebserviceID/<WEB_SERVICE_ID>
my $URL = 'http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector';

# this name space should match the specified name space in the SOAP transport for the web service.
my $NameSpace = 'http://www.otrs.org/TicketConnector/';

# this is operation to execute, it could be TicketCreate, TicketUpdate, TicketGet, TicketSearch
# or SessionCreate. and they must to be defined in the web service.
my $Operation = 'TicketCreate';

# this variable is used to store all the parameters to be included on a request in XML format. Each
# operation has a determined set of mandatory and non mandatory parameters to work correctly. Please
# check the OTRS Admin Manual in order to get a complete list of parameters.
my $XMLData = '
<UserLogin>some user login</UserLogin>
<Password>some password</Password>
<Ticket>
    <Title>some title</Title>
    <CustomerUser>some customer user login</CustomerUser>
    <Queue>some queue</Queue>
    <State>some state</State>
    <Priority>some priority</Priority>
</Ticket>
<Article>
    <Subject>some subject</Subject>
    <Body>some body</Body>
    <ContentType>text/plain; charset=utf8</ContentType>
</Article>
';

# ---

# create a SOAP::Lite data structure from the provided XML data structure.
my $SOAPData = SOAP::Data
    ->type( 'xml' => $XMLData );

my $SOAPObject = SOAP::Lite
    ->uri($NameSpace)
    ->proxy($URL)
    ->$Operation($SOAPData);

# check for a fault in the soap code.
if ( $SOAPObject->fault ) {
    print $SOAPObject->faultcode, " ", $SOAPObject->faultstring, "\n";
}

# otherwise print the results.
else {

    # get the XML response part from the SOAP message.
    my $XMLResponse = $SOAPObject->context()->transport()->proxy()->http_response()->content();

    # deserialize response (convert it into a perl structure).
    my $Deserialized = eval {
        SOAP::Deserializer->deserialize($XMLResponse);
    };

    # remove all the headers and other not needed parts of the SOAP message.
    my $Body = $Deserialized->body();

    # just output relevant data and no the operation name key (like TicketCreateResponse).
    for my $ResponseKey ( keys %{$Body} ) {
        print Dumper( $Body->{$ResponseKey} );
    }
}
                    
                

Perl REST Requester

The following code is a Perl script that can connect to OTRS via the generic interface. In order to perform the operations provided by the Ticket Connector, it uses three Perl CPAN modules JSON, REST::Client and Data::Dumper. Please make sure that your environment is capable to use these modules before you try to run the script.

                    
#!/usr/bin/perl
# --
# otrs.RESTRequest.pl - sample to send a REST request to OTRS Generic Interface Ticket Connector
# Copyright (C) 2001-2018 OTRS AG, https://otrs.com/
# --
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see https://www.gnu.org/licenses/gpl-3.0.txt.
# --

use strict;
use warnings;

## nofilter(TidyAll::Plugin::OTRS::Perl::Dumper)

# use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use JSON;
use REST::Client;

# ---
# Variables to be defined

# This is the HOST for the web service the format is:
# <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl
my $Host = 'http://localhost/otrs/nph-genericinterface.pl';

my $RestClient = REST::Client->new(
    {
        host => $Host,
    }
);

# This is the Controller and Request the format is:
# /Webservice/<WEB_SERVICE_NAME>/<RESOURCE>/<REQUEST_VALUE>
# or
# /WebserviceID/<WEB_SERVICE_ID>/<RESOURCE>/<REQUEST_VALUE>
# This example will retrieve the Ticket with the TicketID = 1 (<REQUEST_VALUE>)
my $ControllerAndRequest = '/Webservice/GenericTicketConnectorREST/Ticket/1';

my $Params = {
    UserLogin     => "some user login",       # to be filled with valid agent login
    Password      => "some user password",    # to be filled with valid agent password
    DynamicFields => 1,                       # optional, if set to 1,
                                              # ticket dynamic fields included in response
    AllArticles   => 1,                       # optional, if set to 1,
                                              # all ticket articles are included in response
                                              # more options to be found in
         # /Kernel/GenericInterface/Operation/Ticket/TicketGet.pm's
         # Run() subroutine documentation.
};

my @RequestParam;

# As sample web service configuration for TicketGet uses HTTP method GET all other parameters needs
# to be sent as URI query parameters

# ----
# For GET method
my $QueryParams = $RestClient->buildQuery( %{ $Params } );

$ControllerAndRequest .= $QueryParams;

# The @RequestParam array on position 0 holds controller and request
@RequestParam = ($ControllerAndRequest);

$RestClient->GET(@RequestParam);
# ----

# # ----
# # For POST method
# my $JSONParams = encode_json $Params;

# # The @RequestParam array on position 0 holds controller and request
# # on position 1 it holds the JSON data string that gets posted
# @RequestParam = (
#   $ControllerAndRequest,
#   $JSONParams
# );

# $RestClient->POST(@RequestParam);
# # ----

# If the host isn't reachable, wrong configured or couldn't serve the requested page:
my $ResponseCode = $RestClient->responseCode();
if ( $ResponseCode ne '200' ) {
    print "Request failed, response code was: $ResponseCode\n";
    exit;
}

# If the request was answered correctly, we receive a JSON string here.
my $ResponseContent = $RestClient->responseContent();

my $Data = decode_json $ResponseContent;

# Just to print out the returned Data structure:
use Data::Dumper;
print "Response was:\n";
print Dumper($Data);

                    
                

cURL Примеры для REST запросов

В приведенном выше примере настройки REST для Generic Ticket Connector имеем следующее:

Для Ticket Create: используйте POST метод в /Ticket path.

Для Ticket Search: используйте GET метод в /Ticket path.

Для Ticket Update: используйте метод PATCH в /Ticket/{TicketID} пути (где {TicketID} является шаблоном представленным :TicketID в настройке транспорта)

Для Ticket Get: используйте метод Get в /Ticket/{TicketID} пути (где {TicketID} является шаблоном представленным :TicketID в настройке транспорта)

Создать новую заявку

cURL Command:


shell> curl "http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket?UserLogin=agent&Password=123" -H "Content-Type: application/json" -d "{\"Ticket\":{\"Title\":\"REST Create Test\", \"Type\": \"Unclassified\", \"Queue\":\"Raw\",\"State\":\"open\",\"Priority\":\"3 normal\",\"CustomerUser\":\"customer\"},\"Article\":{\"Subject\":\"Rest Create Test\",\"Body\":\"This is only a test\",\"ContentType\":\"text/plain; charset=utf8\"}}"  -X POST

                    

Ответ:

{
  "ArticleID":5484,
  "Номер заявки":"1001936",
  "TicketID":"1686"
}
                    

Получить подробности заявки

cURL Command:


curl "http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/1686?UserLogin=agent&Password=123"

                    

Ответ:

{
  "Ticket": [
    {
      "Age": 777,
      "PriorityID": 3,
      "ServiceID": "",
      "Type": "Unclassified",
      "Responsible": "root@localhost",
      "StateID": 4,
      "ResponsibleID": 1,
      "ChangeBy": 2,
      "EscalationTime": 0,
      "Changed": "2014-06-30 19:08:14",
      "OwnerID": 2,
      "RealTillTimeNotUsed": 0,
      "GroupID": 1,
      "Owner": "agent",
      "CustomerID": "OTRS",
      "TypeID": 1,
      "Created": "2014-06-30 19:08:12",
      "Priority": "3 normal",
      "UntilTime": 0,
      "EscalationUpdateTime": 0,
      "QueueID": 2,
      "Queue": "Raw",
      "State": "open",
      "Title": "REST Create Test",
      "CreateBy": 2,
      "TicketID": 1686,
      "StateType": "open",
      "EscalationResponseTime": 0,
      "UnlockTimeout": 0,
      "EscalationSolutionTime": 0,
      "LockID": 1,
      "TicketNumber": "1001936",
      "ArchiveFlag": "n",
      "Lock": "unlock",
      "CreateTimeUnix": 1404173292,
      "SLAID": "",
      "CustomerUserID": "customer"
    }
  ]
}
                    

Обновить заявку

cURL Command:


curl "http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/1686?UserLogin=agent&Password=123" -H "Content-Type: application/json" -d "{\"Ticket\":{\"Queues\":\"Postmaster\"}}"  -X PATCH

                    

Ответ:

{
  "TicketNumber":"1001936",
  "TicketID":"1686"
}
                    

Поиск заявок

cURL Command:


curl "http://localhost/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket?UserLogin=agent&Password=123&Queue=Postmaster"

                    

Ответ:

{
  "TicketID": [
    "1686",
    "102",
    "100",
    "1"
]
}