Сравнение версий

Ключ

  • Эта строка добавлена.
  • Эта строка удалена.
  • Изменено форматирование.

Image Added

Оглавление

Общая работа с OTAPI

The use of OTAPI methods in the documentation is described for OT Box and mobile application for it as an example.

OTAPI methods can be used and varied in the operation of any sites on various CMS.

General work with OTAPI

All methods are available on documentation pageВсе методы можно увидеть на странице с документациейhttp://docs.otapi.net/en.

Send Для получения ответа от api в формате xml нужно отправить GET/POST запрос на адрес request to http://otapi.net/service/Для получения ответа от api в формате json нужно отправить GET/POST запрос на адрес  to get response from api in xml format.

Send GET/POST request to http://otapi.net/service-json/

К адресу нужно добавить имя метода, и параметры в GET/POST виде, в зависимости от запроса и его размера. Некоторые параметры могут не поместиться в GET-запрос, поэтому проще сделать всегда POST.

В ответе от api обязательно приходит узел ErrorCode, если он не равен 'Ok' и не равен 'BatchError' - необходимо обработать ошибку. Ошибки необходимо разделять по значению в узлах ErrorCode и/или SubErrorCode.

Некоторые ErrorCode которые можно обрабатывать глобально на уровне приложения:

  • SessionExpired - сессия покупателя или администратора истекла, необходимо предложить пользователю авторизоваться и повторить свои действия.
  • AccessDenied - для данного пользователя доступ к этому методу запрещен.
  • InstanceKeyBan - ключ приложения заблокирован, обратитесь к менеджерам в ваш скайп чат за подробностями. Пользователю приложения, в таком случае, желательно показать заглушку, например "На сайте ведутся технические работы".

В некоторых случаях, необходимо показать пользователю само сообщение об ошибке. Оно хранится в узле ErrorDescription и приходит уже с переводом для языка, который указан при запросе в параметре 'language'.

Старт приложения

 to get response from api in json format.

Add method name and parameters in GET/POST form to the address depending on query and its size. Some parameters may nootherwiset fit in GET query, so it is always easier to make POST.

The ErrorCode node necessarily comes in the response from api, if it is not equal to 'Ok' and not equal to 'BatchError' - it is necessary to process the error. Errors must be separated by value in the ErrorCode and / or SubErrorCode nodes.

Some ErrorCode that can be processed globally at the application level:

  • SessionExpired - buyer's or administrator's session has expired, it's necessary to offer user log in and repeat his actions.
  • AccessDenied - access to this method is forbidden for this user.
  • InstanceKeyBan - application key is blocked, contact managers in your skype chat for details. It's advisable to show "Technical work is done on the site" for application user.

In some cases, the error message must be shown to the user. It is stored in the Errordescription node and comes with the translation for the language specified when querying in the 'language' parameter.

Application start

You need to get application settings when you start itПри старте приложения, необходимо получить настройки приложенияhttp://docs.otapi.net/ruen/Documentations/Method?name=GetCommonInstanceOptionsInfo с передачей параметра applicationType with parameter applicationType=MobileApplication/Android or applicationType=MobileApplication.

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

/iOS depends on system.

Application should get a list of available languages from the settings and provide user with an interface to choose application language (if there is more than one language in the list). Further queries to api are called with this language. When starting, the application should take the first language from the list in the settings, check user session (anonymous or authorized) with this language and get application language from the user’s preferences (for more details see working with the user block).

It is also necessary to request a list of translations for application interface at the startНа старте так же нужно запросить список переводов для интерфейса приложенияhttp://docs.otapi.net/ru/Documentations/Method?name=GetApplicationUITranslations с передачей языка и параметра applicationType=MobileApplication.

Список успешно полученных настроек необходимо кэшировать. Обновлять кэш настроек стоит в фоновом режиме, не замедляя этим запросом работу приложения. Обновлять кэш в фоне стоит или раз в N часов или при каждом старте приложения. Настройки одни на всё приложение и не различаются для разных пользователей.

 with language and parameter passing applicationType=MobileApplication/Android or applicationType=MobileApplication/iOS depends on system.

The list of successfully received settings must be cached. It is worth clearing settings cache in the background without slowing down application’s operation with this request. It’s worth clearing cache in background either every N hours or every time the application starts. Settings are the same for the entire application and do not differ for different users.

The first time mobile application starts, it must ask user for permission to receive push notifications. It is necessary to send application push token to the services Мобильное приложение при первом запуске должно запросить у пользователя разрешение на получение push-уведомлений. Если пользователь согласился получать push-уведомления, необходимо отправить push-токен приложения в сервисы  http://docs.otapi.net/ru/Documentations/Method?name=SetUserPushNotificationToken. В будущем, приложение должно следить за актуальностью push-токена и при необходимости обновлять его.

Получение сессии (авторизация пользователя)

Работа с пользователем - основные моменты

 if the user agreed to receive push notifications. Application should monitor relevance of the push token and update it if necessary in the future.

Receiving session (user authorization)

Working with the user - highlights

Some otapi methods require customer's session parameter. It's necessary to get a session before working with logic for users. Initially, you need to get an anonymous session using Часть методов otapi требует параметр сессии покупателя. Перед тем как работать с логикой для пользователей, необходимо получить сессию. Изначально нужно получить анонимную сессию методом http://docs.dev.otapi.net/ruen/Documentations/Method?name=GetAnonymousSession, чтобы например по ней могли уже сохраняться корзина, предпочтения, и прочее. Если при авторизации была передана предыдущая анонимная сессия, все данные автоматом перенесутся.

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

Любой метод, использующий сессию пользователя, может вернуть ошибку SessionExpired, это означает что сессия истекла. В этом случае нужно перекинуть пользователя снова на авторизацию с соответствующим сообщением, а когда новая сессия будет успешно получена, вернуть пользователя в то место, где возникла ошибка.

 method so that the shopping cart, preferences (for example) and so on could be saved on it. All data will be automatically transferred if the previous anonymous session was transferred during authorization. Obtained session must be saved in the application memory and used later for all requests.

Any method using user session may return SessionExpired error, which means that session has expired. In this case you need to transfer user to authorization with the corresponding message, and return user to the place where the error occurred when new session is successfully received.

The easiest way to force session verification by Принудительно проверить сессию проще всего методом http://docs.otapi.net/ruen/Documentations/Method?name=GetUserStatusInfo. Он наименее затратен по времени method. It is the least time consuming.

Регистрация

Registration

User registration is carried out by Регистрация пользователей осуществляется методом http://docs.otapi.net/ruen/Documentations/Method?name=RegisterUser
Перед вызовом этого метода нужно выполнить проверку входных данных method
Check input data before calling this method:

  • Email, Login, Password - обязательные параметры
  • Длина строки Password не менее 6 символов
  • Строка с Email действительно является email адресом

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

После успешной регистрации методом RegisterUser проверить в ответе поле Result->IsEmailVerificationUsed. Если IsEmailVerificationUsed = "true" то показать пользователю сообщение "Для активации учетной записи Вам на почту было выслано письмо со ссылкой на активацию". Если IsEmailVerificationUsed = "false" нужно сразу авторизовать пользователя (установить для него новый SessionId полученный в ответ от сервисов).

Активация после регистрации

  • obligatory parameters;
  • Password length must be at least 6 characters;
  • Email line is really an email address.

Additional obligatory flag field "I accept the user agreement" should be in the registration form. Registration without this flag is not allowed.

Check Result-> IsEmailVerificationUsed field in the response after successful registration using RegisterUser method. Show message to user "An email was sent to your mail with a link to activation to activate account" if IsEmailVerificationUsed = "true". You need to authorize user immediately (set a new SessionId for him received in response to services) if IsEmailVerificationUsed = "false".

Activation after registration

Together with the message that email was sent, you need to display input field for activation code. You should call http://Вместе с сообщением про то что было отправлено письмо, нужно вывести поле ввода кода активации. Когда пользователь проверит почту, введет код в приложении, нужно вызвать http://docs.otapi.net/ruen/Documentations/Method?name=ConfirmEmail. В ответе ConfirmEmail есть поле when user checks email and enters the code in the application. There is a field Result->SessionId->Value которое содержит сессию авторизованного пользователя. На основе этой сессии нужно сразу авторизовать пользователя в приложении.

Авторизация

in response ConfirmEmail which contains authorized user session. Based on this session, you must immediately authorize user in the application.

Authorization

Users' authorization is carried out by Авторизация пользователей осуществляется методом http://docs.otapi.net/ruen/Documentations/Method?name=Authenticate
На форме авторизации должно быть поля логин method.
Authorization form should contain the following fields: login (userLogin), поле парольpassword (userPassword) и флаг запомнитьand remember me flag (rememberMe). Перед вызовом метода Authenticate нужно выполнить проверку входных данныхCheck input data before calling Authenticate method:

  • userLogin, userPassword - обязательные параметры

Параметр sessionId в методе Authenticate - идентификатор сессии не авторизованного покупателя.

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

Авторизация через социальные сети

Авторизация через соцсети (OT API)

Список социальных сетей надо брать в настройках от GetCommonInstanceOptionsInfo в зависимости от текущего языка, так как например админ может оставить ВКонтакт для русского, и убрать для английского. Смотреть в TranslatableOptions->выбор по языку->ExternalAuthentications.

Восстановление пароля

  • are obligatory parameters

sessionId parameter in Authenticate method is the session identifier of an unauthorized customer.

Login as well as user's email can be transferred as userLogin. Probably it is worthwhile to somehow suggest this in the interface.

Social networks authorization

Social Networks Authorization (OT API)

Get the list of available social networks in settings from GetCommonInstanceOptionsInfo depending on current language, since for example admin can leave VKontakte for Russian and remove for English. Check in TranslatableOptions->choice by language->ExternalAuthentications.

Password recovery

Password recovery is done by Восстановление пароля осуществляется методом http://docs.otapi.net/ruen/Documentations/Method?name=RequestPasswordRecovery  method.  
Поле userIdentifier может содержать логин или email пользователя. После вызова RequestPasswordRecovery показать пользователю сообщение "На Ваш email высланы дальнейшие инструкции" и отобразить форму с кодом подтверждения и двумя текстовыми полями для ввода пароля. Пользователь смотрит код в почте, возвращается в приложение, вводит код и новый пароль. Если оба поля с паролем совпадают, далее нужно вызвать Field userIdentifier may contain user login or email. After calling RequestPasswordRecovery, show user the message "Further instructions were sent to your email" and display a form with confirmation code and two text fields for entering the password. User checks code in the email, returns to the application, enters the code and new password. If both fields with password match, then you need to call http://docs.otapi.net/ruen/Documentations/Method?name=ConfirmNewPassword. В ответе ConfirmNewPassword есть поле  ConfirmNewPassword response has Result->SessionId->Value которое содержит сессию авторизованного пользователя. На основе этой сессии нужно сразу авторизованного пользователя в приложении.

Главная страница приложения

Получение подборок

> SessionId-> Value field that contains an authorized user session. Based on this session, you need to authorize user in the application immediately.

Application home page

Social networks authorization

Get collections

Use Для получения подборок, используем метод http://docs.otapi.net/ruen/Documentations/Method?name=BatchSearchRatingLists . При первом запросе передаем параметры:  method to get collections. We pass the following parameters at the first request:

Блок кода
languagexml
<BatchRatingListSearchParameters><UseDefaultParameters>true</UseDefaultParameters></BatchRatingListSearchParameters>

и параметр and parameter applicationType=MobileApplication/Android or applicationType=MobileApplication. В полученных данных для каждой подборки имеется порядковый номер для сортировки <Order>0</Order> , нужно отобразить на экране приложения подборки согласно этой сортировке.Рекомендуется показывать подборки покупателю только из кэша. В кэше подборки необходимо обновлять в фоновом режиме: раз в 60 минут запрашивать метод BatchSearchRatingLists и сохранять результат в кэш. При получении ответа, нужно проверить узел HasTranslateErrors /iOS depends on system. Received data for each collection has a serial number for sorting <Order> 0 </Order>, you need to display collections on the application screen according to this sorting. It is recommended to show collections only from cache. Collections in cache must be updated in background: every 60 minutes, request BatchSearchRatingLists method and save result in the cache. When receiving a response, you need to check HasTranslateErrors node (http://docs.dev.otapi.net/ruen/Documentations/Type?name=BatchRatingListsSearchResultAnswer), если узел равен if the node is "true", то кэшировать ответ ну нужно. Для каждого элемента RatingList в ответе необходимо проверить узел HasError then you do not need to cache the response. You must check HasError node (http://docs.dev.otapi.net/ruen/Documentations/Type?name=RatingListSearchResult), если узел равен "true", то этот элемент подборки кэшировать не нужно.

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

Получение баннеров

 for each RatingList element in the response, if the node is true, then this collection item does not need to be cached.

Thus, we get a situation when buyer sees collections from cache. At the same time, collections in the cache have no errors. Situation is possible when we show user outdated information, while we are sure that this information is error-free.

Get banners

Open "Demonstration MetaUI" plugin:

Image Added

Choose "Banner settings" in dropdown list and press "Open" button:

Image Added

Fill in the data and add website (website is required):

Image Added

After that follow next steps:

You can get a full list of banners configured for application by Полный список баннеров, настроенных для приложения, можно получить методом http://docs.otapi.net/ruen/Documentations/Method?name=/GetBanners  method, передав параметр applicationType=MobileApplication.

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

Тип действияПараметр

Url

Абсолютный адрес ссылки, которую нужно открыть при нажатии на баннер

Category

Идентификатор категории, которую нужно открыть при нажатии на баннер

...

passing parameter applicationType=WebSite (applicationType=MobileApplication/Android or applicationType=MobileApplication/iOS depends on system), instanceKey and language. Send request and get the link:

Image Added

Each banner will have its name, image address, type of action, and action parameter. The current types of actions and the meaning of their parameters are listed below.

The current types of actions and their parameters purpose are listed below:

Action typeParameter

Url

Absolute address of the link to open when you click banner

Category

ID of the category that should be opened when clicking the banner


Short categories menu

TODO:

Social networks

TODO:

User Preferences

  • Currencies. The list of available currencies must be shown from application settings GetCommonInstanceOptionsInfo Currencies node.
  • Delivery country. The list of available countries must be shown from application settings GetCommonInstanceOptionsInfo DeliveryCountries node. The list of countries must be displayed taking into account current language of application (all translations can be found in TranslatableOptions node).
  • Application language. Show the list of available application languages from application settings GetCommonInstanceOptionsInfo Languages node.

Customer may have a number of preferences-settings on which otapi answers or behavior of the system / application depend on in the future.

You can get currently selected preferences using 

TODO:

Социальные сети

TODO:

Предпочтения пользователя

  • Валюты. Список доступных валют необходимо показать из настроек приложения GetCommonInstanceOptionsInfo узел Currencies.
  • Страна доставки. Список доступных стран необходимо показать из настроек приложения GetCommonInstanceOptionsInfo узел DeliveryCountries. Список стран необходимо отображать с учетом текущего языка приложения (все переводы можно найти в узле TranslatableOptions).
  • Язык приложения. Список доступных языков приложения показать из настроек приложения GetCommonInstanceOptionsInfo узел Languages.

Покупатель может иметь ряд предпочтений-настроек, от которых зависят в будущем ответы otapi или поведение системы/приложения.

Получить текущие выбранные предпочтения можно с помощью метода http://docs.otapi.net/ruen/Documentations/Method?name=GetUserPreferencesИзменить предпочтение пользователя можно с помощью метода  method.

User preference can be changed using http://docs.otapi.net/ruen/Documentations/Method?name=UpdateUserPreferences

Интерфейс приложения должен предоставить пользователю возможность изменять свои предпочтения.

Список категорий

method.

Application interface should allow users to change their preferences.

Categories list

Send a request firstДля начала отправляем запросhttp://docs.otapi.net/ruen/Documentations/Method?name=GetRootCategoryInfoList - получаем список корневых категорий сайта. Этот список можно кэшировать на 24 часа. Далее при попытке развернуть каждую категорию - делаем отдельный запрос we get a list of website root categories. This list can be cached for 24 hours. Then make a separate request for attempt to expand each category - http://docs.otapi.net/ruen/Documentations/Method?name=GetCategorySubcategoryInfoList. Каждый список тоже можно кэшировать на 24 часа, используя в ключе идентификатор родительской категории.

Категория содержит другие категории (т.е. её можно развернуть), если для неё пришел флаг <IsParent>true</IsParent>.

Если категория скрыта <IsHidden>true</IsHidden> - её нужно не показывать в каталоге.

Флаг <IsVirtual>true</IsVirtual> означает что в категории нет товаров (только другие подкатегории).

Each list can be also cached for 24 hours using parent category identifier in the key.

category contains other categories (that is it can be expanded) if the flag <IsParent> true </IsParent> has come for it.

Don't show category in catalog if it is hidden <IsHidden>true</IsHidden>.

Flag <IsVirtual>true</IsVirtual> means that category doesn't contain goods (only other subcategories).

Absolute image address for category can be returned (image is set by administrator in admin panel) in the optional <IconImageUrl> node В необязательном узле <IconImageUrl> http://open-demo.otcommerce.com/uploaded/category/zh_odezhda.jpg < </IconImageUrl> может придти абсолютный адрес изображения для категории (изображение устанавливается администратором в админке).

Страница рекомендуемых продавцов

.

Recomended vendors page

Метод http://docs.otapi.net/ruen/Documentations/Method?name=BatchSearchRatingLists  method, xmlSearchParameters=

<BatchRatingListSearchParameters><RatingLists><RatingList><CategoryId>0</CategoryId><ItemRatingType>Best</ItemRatingType><IsRandomSearch>false</IsRandomSearch><ContentType>Vendor</ContentType><FramePosition>0</FramePosition><FrameSize>20</FrameSize></RatingList></RatingLists></BatchRatingListSearchParameters>

FrameSize - количество продавцов на странице, в ответе придет TotalCount - общее количество рекомендуемых продавцов. На основе TotalCount и FrameSize можно нарисовать пагинацию.

Страница рекомендуемых брендов

number of vendors on the page, TotalCount will be returned in the response - the total number of recommended vendors. You can draw pagination based on TotalCount and FrameSize.

Recomended brands page

Метод http://docs.otapi.net/ruen/Documentations/Method?name=BatchSearchRatingLists  method, xmlSearchParameters=

<BatchRatingListSearchParameters><RatingLists><RatingList><CategoryId>0</CategoryId><ItemRatingType>Best</ItemRatingType><IsRandomSearch>false</IsRandomSearch><ContentType>Brand</ContentType><FramePosition>0</FramePosition><FrameSize>20</FrameSize></RatingList></RatingLists></BatchRatingListSearchParameters>

FrameSize - количество брендов на странице, в ответе придет TotalCount - общее количество рекомендуемых брендов. На основе TotalCount и FrameSize можно нарисовать пагинацию.

Отображение продавцов

Как на странице рекомендуемых продавцов, так и в карточке товара в блоке продавца, так и при просмотре всех товаров продавца, для отображения информации о продавце нужно использовать следующие свойства:

Свойство
Описание
Где отображать
Комментарии
DisplayNameимя продавцавездеБлагодаря этому позже админ магазина сможет менять имена, а для МП ничего не поменяется в логике.
DisplayPictureUrlкартинка продавцавезде

Только если есть, иначе в рекомендуемых продавцах заглушках, в остальных местах не отображать.
Благодаря этому позже админ магазина сможет менять картинки, а для МП ничего не поменяется в логике.

Credit/Levelрейтинг продавца от 1 до 20в карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.
Credit/TotalFeedbacksчисло отзывовв карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.
Credit/PositiveFeedbacksчисло положительных отзывовв карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.
Если есть, отображать в виде % от числа общих отзывов.
Scores/DeliveryScoreоценка доставки от 1.0 до 5.0в карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.
Scores/ItemScoreоценка товаров от 1.0 до 5.0в карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.
Scores/ServiceScoreоценка услуг (или сервиса) от 1.0 до 5.0в карточке товара
на странице продавца
Только если есть и не равно 0, иначе отображать не нужно.

Поиск

Основная документация по поиску.

number of brands on the page, TotalCount will be returned in the response - the total number of recommended brands. You can draw pagination based on TotalCount and FrameSize.

Vendors display

The following properties should be used on recommended vendors page, in product card in vendor's block, for viewing all goods of vendor and for displaying information about the vendor:

Property
Description
Where to show
Comments
DisplayNamevendor nameeverywhere

Thanks to this, website admin will be able to change names later, but nothing will change in Mobile Application logic.

DisplayPictureUrlvendor imageeverywhere

Only if available, otherwise there is an image stub in recommended vendors, do not display in other places.

Thanks to this, website admin will be able to change images but nothing will change in Mobile Application logic.

 

Credit/Levelvendor rating from 1 to 20

in product card
on vendor's page

Only if available and more than 0, otherwise it does not need to be displayed.
Credit/TotalFeedbacksnumber of feedbacksin product card
on vendor's page
Only if available and more than 0, otherwise it does not need to be displayed.
Credit/PositiveFeedbacksnumber of positive feedbacksin product card
on vendor's page
Only if available and more than 0, otherwise it does not need to be displayed.
Display as% of total reviews if available.
Scores/DeliveryScoredelivery scrore from 1.0 to 5.0in product card
on vendor's page

Only if available and more than 0, otherwise it does not need to be displayed.

Scores/ItemScoreitem score from 1.0 to 5.0in product card
on vendor's page

Only if available and more than 0, otherwise it does not need to be displayed.

Scores/ServiceScore
service score from 1.0 to 5.0
in product card
on vendor's page

Only if available and more than 0, otherwise it does not need to be displayed.

Basic documentation on search.

Use only one convenient search method to search for goodsДля поиска товаров используем только один удобный метод поискаhttp://docs.otapi.net/ruen/Documentations/Method?name=BatchSearchItemsFrame

При первом открытии категории/продавца/бренда или поискового запроса, вызываем метод BatchSearchItemsFrame с параметром blockListTo open a category / seller / brand or search query for the first time, call BatchSearchItemsFrame method with the blockList parameter: SubCategories,HintCategories,Vendor,Brand,Category,RootPath,SearchProperties,AvailableSearchMethods. В xmlParameters передаем параметры поиска (например ид категории Send search parameters in xmlParameters (for example, category ID <CategoryId>otc-3</CategoryId> или поисковый запрос or search or search query <ItemTitle>dress</ItemTitle>). Мы рекомендуем с параметрами поиска передать: <UseOptimalFrameSize>true</UseOptimalFrameSize>, это позволит получить в ответе оптимальное количество товаров на странице для данного запроса.

Отображаем информацию полученную в ответе.

В узле AvailableSearchMethods приходят все способы поиска, доступные для текущего запроса. Если способов поиска больше чем один - нужно дать возможность покупателю изменять способ поиска.

В узле Items по значениям из узлов Provider и SearchMethod (например: <Provider>Taobao</Provider> <SearchMethod>Extended</SearchMethod>) в AvailableSearchMethods находим подробную информацию о текущем способе поиска, которым сейчас сделан запрос. По этой информации предоставляем пользователю фильтры доступные на текущей странице поиска. О соответствии полей из информации о способе поиска и параметрами поиска можно найти в основной документации.

Показываем пользователю SubCategories (Подкатегории), HintCategories (Возможно вас заинтересует). В узле Items - Categories приходят категории подходящие под текущий поисковый запрос (Уточните категорию).

Показываем товары из узла Items - Items . Проверяем у товара флаг IsSellAllowed=true и SellDisallowReason="IsFiltered" - то показываем заглушку для товара - товар запрещен к покупке. Если ErrorCode товара не равен "Ok" - вместо картинки товара, показываем ошибку: NotFound - Товар удален, NotAvailable - Товар недоступен, все остальные коды ошибок просто слово "Ошибка".

Хорошей практикой является менять отображение в зависимости от того, какие узлы вернулись в ответе на запрос BatchSearchItemsFrame. Если:

  • пришел узел Vendor, показываем пользователю страницу продавца с описанием продавца;
  • пришел узел Brand, показываем страницу бренда с описанием бренда;
  • пришел узел Category, показываем страницу категории с описанием категории;
  • иначе - обычную страницу поиска по фразе.

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

Карточка товара

We recommend sending <UseOptimalFrameSize>true</UseOptimalFrameSize> with search parameters. This will allow to get optimal number of products per page for this request.

Display information received in the response.

AvailableSearchMethods node contains all search methods available for current query. Allow customer to change search method if there are more than one search methods.

Find detailed information about the current search method that the query is now made in Items node, using values from Provider and SearchMethod nodes (for example: <Provider> Taobao </Provider> <SearchMethod> Extended </SearchMethod>) in AvailableSearchMethods. Using this information we provide user with filters available on the current search page. The correspondence of fields from information about search method and search parameters can be found in basic documentation.

Show SubCategories (Subcategories), HintCategories (You may be interested) to user. Categories that match current search query (Specify category) come up in Items - Categories node. Show goods from Items - Items node. Check the flag IsSellAllowed = true and SellDisallowReason = "IsFiltered" for the product - then we show the stub for the product - product is not allowed for purchase. Show error: NotFound - product was deleted, NotAvailable - product is unavailable instead of product image if product ErrorCode is not equal to "OK". For all other error codes just show the word "Error".

It is a good practice to change display depending on which nodes are returned in response to BatchSearchItemsFrame request. If:

  • Vendor node has arrived, show user vendor's page with vendor description;
  • Brand node has arrived, show brand page with brand description;
  • Category node has arrived, show category page with category description;
  • Otherwise, a regular search page by phrase.

This approach will allow you to localize search logic and services will be responsible for page display logic.

Product card

Use При первом открытии карточки, нужно использовать метод: http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemFullInfo , нужно передавать следующие blockList when you open the card for the first time, it's necessary to send the following parameters: RootPath,Vendor,MostPopularVendorItems16,Description

Отображаем карточку товара:

Show product card:

  • Breadcrumbs categories for this product Хлебные крошки категорий для данного товара (RootPath).
  • Название Title (Item.Title).Видео
  • Video (Item.Videos) и фото (фото представлены в трех размерах: маленький, средний, большой), в качестве главного фото, всегда показываем первое изображение из списка.and photo (photos are available in 3 sizes: small, middle, big), always show the first image from the list as the main photo.
  • Optionally, you can show product features (show all Item.Features that have DisplayName) and weight По желанию можно показать особенности товара (показываем все Item.Features у которых есть DisplayName) и вес товара (Item.Weight).
  • По желанию можно показать информацию о продавце Vendor и его несколько товаров VendorItems.
  • Optionally, you can show vendor information Vendor and his several products VendorItems.
  • All product properties Все характеристики товара (Item.Properties) и описание товара and product description (Description) занимают большую часть экрана, их обычно отображают в конце карточки.occupy most of the screen, they are usually displayed at the bottom of the card.
  • Display a list of all product configurations Отображаем список всех конфигураций товара (Item.Configurators, где where Item.Configurators.Property - это свойство, а is a property and Item.Configurators.Property.Value - значение свойстваis the value of the property).Если есть атрибут MultiInputPropertyId узла Item
  • If there is MultiInputPropertyId attribute of Item.Configurators.Property , данное свойство необходимо нарисовать в виде таблицы, с возможностью выбрать количество каждого значения этого свойства, пример:node, this property must be presented as a table with the ability to select the amount of each value of this property, for example, https://www.screencast.com/t/Ye5kaULlmWJ .

Отображаем цену товараShow product price:

используем метод: use http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemConfigurationInfo , нужно передавать следующие blockList: AdditionalPrices (первый раз запрос можно сделать с пустым xmlRequest) method, it's necessary to send the following parameters: AdditionalPrices (the first request can be made with an empty xmlRequest)

  • Check ability to buy this product and the reason to cancel purchase Проверяем возможность купить данный товар и причину отказа от покупки (Configuration.Availability). 
  • Note which properties are selected by user Отмечаем какие свойства выбраны пользователем (Configuration.Configurators.Property.Value - Selected = "true"), а какие не доступны для выбора and which are not available for selection (Configuration.Configurators.Property.Value -  DisabledDisabled = "true").
  • Отображаем зависимость цены от количества (если пришел узел QuantityRanges).
  • Если пришел узел MultiInputConfigurations, то показываем цену каждой конфигурации из MultiInputConfigurations, иначе показываем цену из узла Current:
    • Price - цена за 1шт. (если есть атрибуты Min и Max - то нужно показать не одну цену, а диапазон цен)
    • OldPrice - цена без скидки за 1шт. (если скидки нет, узел отсутствует)
    • DiscountPercent - процент скидки для OldPrice. (если скидки нет, узел отсутствует)
    • InternalDelivery - цена внутренней доставки (если узел отсутствует, показывать не надо)
    • AvailableQuantity - доступное количество для покупки.
  • Выводим итоговую стоимость из узла TotalCost.
  • Добавляем информацию о возможной добавочной стоимости (AdditionalPrices).
  • Display dependence of price on quantity (if QuantityRanges node has arrived).
  • If MultiInputConfigurations node has arrived, then show price of each configuration from MultiInputConfigurations, otherwise show price from Current node:
    • Price - price for 1 item (show price range instead of one price if there are Min and Max attributes);
    • OldPrice - price without discount for 1 item (node is absent if there is no discount);
    • DiscountPercent - discount % for OldPrice (node is absent if there is no discount);
    • InternalDelivery - internal delivery price (don't show if there is no node);
    • AvailableQuantity - available quantity for purchase.
  • Display total cost from TotalCost node.
  • Add information about possible added price (AdditionalPrices).
Allow buyer to choose configuration and its quantity (input field is one if there is no MultiInputPropertyId, enter quantity for each value of MultiInputPropertyId property if there is MultiInputPropertyId). Send a new BatchGetSimplifiedItemConfigurationInfo request with selected configuration and quantity after each "property change" and "quantity change". Examples of Предоставляем покупателю возможность выбирать конфигурацию и её количество (если MultiInputPropertyId нет - то поле для ввода количество одно, если MultiInputPropertyId есть - для каждого значения свойства MultiInputPropertyId можно ввести своё количество). После каждого "изменения свойства" и "изменения количества", отправляем новый запрос BatchGetSimplifiedItemConfigurationInfo с указанием выбранной пользователем конфигурации и количества, примеры xmlRequest:

 

Раскрыть
titleПокупатель ничего не выбралCustomer did not choose anything
<Request />
равнозначенequal to
<Request>
    <Current />
</Request>
equal to

равнозначен
<Request>
    <Current Quantity="1" />
</Request>
Раскрыть
titleЗапрос с количеством в товаре без опций вовсе или без выбранных опцийRequest with quantity in a product without options at all or without selected options
<Request>
    <Current Quantity="5" />
</Request>
ЗапросRequest наto текущиеcurrent опцииoptions:
<Request>
    <Current ConfigurationId="идКонфигурацииidconfiguration" />
</Request>
илиor
<Request>
    <Current ConfigurationId="идКонфигурацииidconfiguration" Quantity="5" />
</Request>
илиor
<Request>
    <Current>
        <Property Id="идЦветаidcolor" ValueId="идКрасногоidRed"
    </Current>
</Request>
илиor
<Request>
    <Current>
        <Property Id="идЦветаidcolor" ValueId="идКрасногоidRed"
        <Property Id="идРазмераidSize" ValueId="идСреднегоidMiddle"
    </Current>
</Request>
илиor
<Request>
    <Current Quantity="5">
        <Property Id="идЦветаcolorid" ValueId="идКрасногоidRed"
        <Property Id="идРазмераidSize" ValueId="идСреднегоidMiddle"
        <Property Id="идМоделиidModel" ValueId="идНекойМоделиidSomeModel"
    </Current>
</Request>
Раскрыть
titleЗапрос с выбранными другими конфигурациямиRequest with selected other configurations
<Request>
    <Selected ConfigurationId="идКонфигурацииidConfiguration" Quantity="1" />
    <Selected ConfigurationId="идКонфигурацииidConfiguration" Quantity="2" />
    ...
</Request>
илиor
<Request>
    <Selected Quantity="1">
        <Property Id="идЦветаidColor" ValueId="идКрасногоidRed"
        <Property Id="идРазмераidSize" ValueId="идСреднегоidMiddle"
    </Selected>
    <Selected Quantity="2">
        <Property Id="идЦветаidColor" ValueId="идЗеленогоidGreen"
        <Property Id="идРазмераidSize" ValueId="идСреднегоidMiddle"
    </Selected>
    ...
</Request>

Запрос со всем вместе может быть любой комбинацией других видов запросов, напримерA query with everything together can be any combination of other types of queries, for example:
<Request>
    <Current Quantity="5">
        <Property Id="идЦветаidColor" ValueId="идКрасногоidRed"
    </Current>
    <Selected Quantity="2">
        <Property Id="идЦветаidColor" ValueId="идЗеленогоidGreen"
        <Property Id="идРазмераidSize" ValueId="идСреднегоidMiddle"
    </Selected>
</Request>


Что такое What's Current/Selected - и как правильноand what's correct? Current или or Selected?
Если нужен только 1 одновременно выбранный конфиг, то про Selected можно вообще не думать.
Если нужно несколько (как на 1688), то в Selected шлем всё где введено количество.

Избранные товары

If you need only 1 simultaneously selected config, then you can not think about Selected at all.
If you need several (as in 1688), then in Selected send everything where the quantity is entered.

 

Favourite goods

Get list of itemsПолучить список товаров: Метод http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetUserData , blockList=Note.

Добавить товар в избранное Add item to favorites: http://docs.otapi.net/ruen/Documentations/Method?name=AddItemToNote , fieldParameters=<Fields/>

Удалить товар из избранного Remove item from favorites: http://docs.otapi.net/ruen/Documentations/Method?name=RemoveItemFromNote , перед удалением требуется подтверждение удаления. confirmation to delete is required before removing.

Move item into cart:Переместить в корзину http://docs.otapi.net/ruen/Documentations/Method?name=MoveItemFromNoteToBasket

Изменить кол-во товара в избранном Change item quantity in favorites: http://docs.otapi.net/ruen/Documentations/Method?name=EditNoteItemQuantity

Изменить комментарийChange commenthttp://docs.otapi.net/ruen/Documentations/Method?name=EditNoteItemFields , <Fields><FieldInfo Name="Comment" Value="Текст комментарияText for comment"/></Fields>

Изменить конфигурацию товараChange item configuration:
1. доступные конфигурации получить методами you can get available configurations by the following methods http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemFullInfo и  and http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemConfigurationInfo - так же, как и в карточке товараsimilar to item card.
2. сохранение новой конфигурации осуществляется добавлением новой и удалением старой, т.е. последовательными вызовами new configuration is saved by adding a new one and deleting the old one, i.e. consecutive calls http://docs.otapi.net/ruen/Documentations/Method?name=AddItemToNote (важно передать в метод все fieldParameters от старой записи, иначе можно потерять часть информации, например комментарий пользователя к товару) и it is important to pass all fieldParameters from the old record into the method, otherwise you may lose some of information, for example, user’s comment on a product) and http://docs.otapi.net/ruen/Documentations/Method?name=RemoveItemFromNote 

Избранные продавцы

Favourite sellers

Vendors listСписок продавцовМетод http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetUserData , blockList=FavoriteVendors

Добавить продавца в избранное Add vendor to favorites: http://docs.otapi.net/ruen/Documentations/Method?name=AddVendorToFavorites , fieldParameters=<Fields/>

Удалить продавца из избранного Remove vendor from favorites: http://docs.otapi.net/ruen/Documentations/Method?name=RemoveVendorFromFavorites Требуется подтверждение удаления , confirmation to delete is required before removing.

Корзина

Cart

Get list of itemsПолучить список товаров: Метод http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetUserData , blockList=Basket.Список товаров должен быть разделен по провайдерам,

т.к. в один заказ можно оформить товары только одного провайдера. Пользователя нужно уведомить о минимальной сумме заказа (если она установлена в конфигурации), получить её можно с помощью метода: The list of goods should be divided by providers, as you can order goods of only one provider in one order. User should be notified about minimum order amount (if it is set in configuration), you can get it using http://docs.otapi.net/ruen/Documentations/Method?name=GetCommonInstanceOptionsInfo  method (Result->Order->MinOrderCost)

Удалить товар из корзины Remove item from cart: http://docs.otapi.net/ruen/Documentations/Method?name=RemoveItemFromBasket ,  перед удалением требуется подтверждение удаления.confirmation to delete is required before removing.

Empty cartПолная очистка корзины http://docs.otapi.net/ruen/Documentations/Method?name=ClearBasket ,  перед очисткой требуется подтверждение.confirmation to delete is required before removing.

Move selected item from cart to favorites:Перенести товар из корзины в избранное http://docs.otapi.net/ruen/Documentations/Method?name=MoveItemFromCartToNote для переноса нескольких отмеченных товаров делается несколько вызовов MoveItemFromCartToNote several calls are made to transfer several marked products MoveItemFromCartToNote

Change quantity of items in the cart: Изменение количества товара в корзине http://docs.otapi.net/ruen/Documentations/Method?name=EditBasketItemQuantity

Добавление/изменение комментария к товару Add/edit comment to item: http://docs.otapi.net/ruen/Documentations/Method?name=EditBasketItemFields <Fields><FieldInfo Name="Comment" Value="Текст комментарияComment text"/></Fields>

Редактирование веса товараEdit item weight: http://docs.otapi.net/ruen/Documentations/Method?name=EditBasketItemFields <Fields><FieldInfo Name="Weight" Value="Число нового веса товараNew weight of an item"/></Fields>

Изменить конфигурацию товараEdit item configuration:
1. доступные конфигурации получить методами you can get available configurations by http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemFullInfo и  and http://docs.otapi.net/ruen/Documentations/Method?name=BatchGetSimplifiedItemConfigurationInfo - так же, как и в карточке товара methods - similar to item card.
2. сохранение новой конфигурации осуществляется добавлением новой и удалением старой, т.е. последовательными вызовами new configuration is saved by adding a new one and deleting the old one, i.e. consecutive calls http://docs.otapi.net/ruen/Documentations/Method?name=AddItemToBasket (важно передать в метод все fieldParameters от старой записи, иначе можно потерять часть информации, например комментарий пользователя к товару) и  it is important to pass all fieldParameters from the old record into the method, otherwise you may lose some of information, for example, user’s comment on a product) and http://docs.otapi.net/ruen/Documentations/Method?name=RemoveItemFromBasket 

Профиль

Profile

Get basic information about user (name, email, etc.Получение основной информации о пользователе (Имя, email и т.п.): http://docs.otapi.net/ruen/Documentations/Method?name=GetUserInfo , редактирование этой информации возможно с помощью метода you can edit this information with http://docs.otapi.net/ruen/Documentations/Method?name=UpdateUser method.

Адрес доставки. Адрес доставки создается и редактируется отдельно от основной информации о пользователе. Всего возможно N адресов доставки, где N берется из настройки Delivery address. Delivery address is created and edited separately from basic information about the user. N delivery addresses are possible in total where N is taken from the setting http://docs.otapi.net/ruen/Documentations/Method?name=GetCommonInstanceOptionsInfo UserProfile->MaxProfilesCount. Методы для работы с адресом доставкиMethods for working with delivery address:

Для пользователя, необходим интерфейс, который позволяет выбрать профиль используемый по умолчанию Interface is required for user that allows to select default profile https://www.screencast.com/t/1fZ9HuauBjf . Выбранный профиль необходимо сохранить в предпочтения пользователяSelected profile must be saved in user preferenceshttp://docs.otapi.net/ruen/Documentations/Method?name=UpdateUserPreferences , поле ProfileId.ProfileId field.

Get a list of content pages for profile screenПолучение списка контентных страниц для экрана профиляhttp://docs.otapi.net/ruen/Documentations/Method?name=GetContentMenuItemTree , параметрыparameters:

applicationType=MobileApplication/Android or applicationType=MobileApplication/iOS depends on system
menuList=Profile
includeContent=true

Список стран, в которые возможна доставка, нужно получить с помощью методаGet list of countries for deliveryhttp://docs.otapi.net/ruen/Documentations/Method?name=GetDeliveryCountryInfoList .

Get list of citiesСписок городов нужно получать методомhttp://docs.otapi.net/ruen/Documentations/Method?name=SearchCities  (пока пользователь вводить символы для поиска города, т.е. параметр QueryText пуст, нужно отправить IsMainCity=true для получения списка городов по умолчанию). В момент когда пользователь выбрал город из списка, сохраняем в профиле City и CityCode и автоматически заполняем поле Region.

Важно: CountryCode - обязательно поле для оформления заказа, CityCode - не обязательное поле, если пользователь выбрал город из списка, то система должна передать код в сервисы, если же пользователь ввёл город, которого нет в списке SearchCities, сохраняем только узле City.

Список заказов

while user enters characters to search for the city, i.e. QueryText parameter is empty, you need to send IsMainCity = true to get a list of default cities). When user selects city from the list, save it in the City profile and CityCode profile and automatically fill in the Region field.

Important: CountryCode - obligatory field for placing an order, CityCode - optional field, system must transfer the code to the services if user selected a city from the list. Save only City node if user entered city that is not in SearchCities list.

Orders list

http://docs.otapi.net/ruen/Documentations/Method?name=SearchOrdersForUser

АктивныеActive: <OrderSearchParametersForUser><IsCancelled>false</IsCancelled><IsCompleted>false</IsCompleted></OrderSearchParametersForUser>

ОтмененныеCancelled: <OrderSearchParametersForUser><IsCancelled>true</IsCancelled></OrderSearchParametersForUser>

ЗакрытыеCompleted: <OrderSearchParametersForUser><IsCompleted>true</IsCompleted></OrderSearchParametersForUser>

Список полей для отображенияThe list of fields to display:

ID заказа, который передается в API во все возможные методы: Id
Номер заказа, отображаемый покупателю: DisplayId
Дата заказа: CreatedDateTime
Статус: StatusName
Сумма: TotalAmount
Уже оплачено: TotalAmount минус RemainAmount
К оплате: RemainAmount
Стоимость товаров: GoodsAmount
Позиций товаров: такой информации нет - не показываем это поле

Заказ. Подробная информация

  • Order ID passed in API into all possible methods: Id
  • Order number displayed to buyer: DisplayId
  • Order date: CreatedDateTime
  • Statusс: StatusName
  • Sum: TotalAmount
  • Already paid: TotalAmount minus RemainAmount
  • For payment: RemainAmount
  • Goods price: GoodsAmount
  • Items positions: do not show this field if there is no such information

Order. Detailed information

Get order informationПолучить информацию о заказеhttp://docs.otapi.net/ruen/Documentations/Method?name=GetSalesOrderDetails

Отображаем для пользователя информацию о заказе (узел OrderInfo, подробнее здесь Display order information for user (OrderInfo node, details here http://docs.otapi.net/ruen/Documentations/Type?name=OtapiOrderInfo), особенностиproperties:

  • DisplayId - идентификатор заказаorder ID.
  • Id - идентификатор заказа, покупателю показывать не надо, этот Id передается в другие методы OTApiorder ID, don't show to the buyer, this Id is passed to other OTApi methods.
  • CanCancel - если заказ можно отменить, показываем кнопку "Отменить заказ" display "Cancel order" button if order can be canceled http://docs.otapi.net/ruen/Documentations/Method?name=CancelSalesOrder
  • Для отображения состояния заказа (выбор цветовой гаммы и т.п.), нужно использовать флаги: IsPaid, IsCancelled, IsCompleted
  • Use flags: IsPaid, IsCancelled, IsCompleted to display order status (choice of color scheme, etc.)

Display goods list in the order (SalesLinesList node, details about each line is here Отображаем список товаров в заказе (узел SalesLinesList, подробнее о каждой строке здесь http://docs.otapi.net/ruen/Documentations/Type?name=SalesLine)

Shippings list Список посылок http://docs.otapi.net/ruen/Documentations/Method?name=GetSalesOrderShippings

Заказ. Оформление заказа и выбор способа доставки

В один заказ можно оформить товары только одного провайдера.

При оформлении заказа, потребуется форма выбора адреса доставки или, если адрес ранее на создавался, форма создания адреса/ов доставки (якорь на документацию по профилям доставки).

Order. Placing an order and choosing delivery method

You can place goods of only one provider into one order.

When placing an order, you will need a form for choosing delivery address or, if an address was previously created, a form for creating delivery address / s (delivery profile documentation anchor).

When placing an order, you will need to select a delivery method from provided list: При оформлении заказа, потребуется выбрать способ доставки из предоставленного списка: запрос http://docs.otapi.net/ruen/Documentations/Method?name=SearchDeliveryModes  request, параметры xmlSearchParametersxmlSearchParameters parameters:

  • ProviderType - ид провайдераprovider ID;
  • Weight - вес товаров, в случае оформления из корзины, потребуется получить список товаров методом goods weight, you will need to get a list of goods by http://docs.otapi.net/ruen/Documentations/Method?name=GetPartialBasket , получить сумму веса каждой позиции (для каждого товара нужно умножить вес товара на заказываемое количество method in case of making order from the cart, get the sum of each item weight (for each product you need to multiply item weight by ordered quantity);
  • CountryCode - код страны доставки из выбранного адреса доставкиdelivery country code from selected delivery address;
  • CityCode - код города доставки из выбранного адреса доставки. delivery city code from selected delivery address.

Parameters exampleПример параметров: <DeliveryModeSearchParameters><CountryCode>RU</CountryCode><CityCode>7700000000000</CityCode><Weight>75.000</Weight><ProviderType>Taobao</ProviderType></DeliveryModeSearchParameters>.

При отображении способов доставки, необходимо учесть флаг IsPickupPointMode.

IsPickupPointMode flag must be considered when displaying delivery methods.

  • Show user Delivery address and zip code fields (take field values from selected delivery address) if flag = false.
  • Take delivery address and zip code from selected pickup location if flag = true. Provide user with an interface for choosing a pick-up point: show all available pick-up points for current delivery method 
  • Если флаг = false, показываем пользователю поля Адрес доставки и Индекс (значения полей берем из выбранного адреса доставки).
  • Если флаг = true, Адрес доставки и Индекс берем из выбранного пункта выдачи. Предоставляем пользователю интерфейс по выбору пункта выдачи: показываем все доступные пункты выдачи для текущего способа доставки http://docs.otapi.net/ruen/Documentations/Method?name=SearchDeliveryPickupPoints (по умолчанию должен быть выбран пункт выдачи, который сохранен в выбранном адресе/профиле доставки).by default, the pick-up point must be selected, which is stored in selected address / delivery profile).

Save ExternalDeliveryId to user preferences after successful order После успешного оформления заказа, нужно сохранить ExternalDeliveryId в предпочтения пользователя (http://docs.otapi.net/ruen/Documentations/Method?name=UpdateUserPreferences) , а так же обновить параметры адреса доставки, если интерфейс сразу этого не сделал as well as update delivery address parameters, if the interface has not done it immediately (http://docs.otapi.net/ruen/Documentations/Method?name=UpdateUserProfile).

Из корзины

Перед тем как оформить заказ из корзины, необходимо "проверить" актуальность цен и возможность оформления:

From cart

"check" relevance of prices and possibility to buy before placing an order from the cart:

  • call после того как клиент выбрал галочками товары которые он хочет оформлять, вызываем метод http://docs.otapi.net/ruen/Documentations/Method?name=RunBasketChecking с выбранными идентификаторами корзины, в ответ получаем и запоминаем "идентификатор активности"
  • показываем клиенту оверлей, фразу "Пожалуйста, подождите. Товары в корзине проходят проверку на наличие. Время проверки зависит от количества товаров в корзине" и прогресс бар
  • method with selected cart identifiers after customer checked off goods that he wants to buy, we get and save "activity identifier" in response;
  • show overlay to client and a phrase "Please wait. Products in the cart are checked for availability. Verification time depends on quantity of goods in the cart" and progress bar;
  • call function вызываем функцию http://docs.otapi.net/ruen/Documentations/Method?name=GetBasketCheckingResult передав в нее идентификатор активности
    • если в ответе нет ошибки и IsFinished != true, показываем прогресс клиенту из узла ProgressPercent и через одну секунду еще раз вызываем метод GetBasketCheckingResult 
    • из узла Messages для нужного элемента корзины показываем текст и статус (статус отображаем путем изменения цвета строки, Ok - зеленый, Warning - желтый, Error - красный)
    • если IsFinished == true, скрываем прогресс бар и
      • если в Messages есть хотя бы один Error - проматываем экран до первой ошибки и предоставляем пользователю возможность исправить ошибку (например выбрать другое количество товаров и по новой запустить проверку корзины)
      • если ошибок нет, но есть хотя бы один Warning - проматываем экран до первого предупреждения и предоставляем пользователю возможность повторно нажать на кнопку "оформить заказ", повторное нажатие должно сразу начать процедуру оформления заказа без повторной проверки корзины (важно: если пользователь изменил количество, конфигурацию или выбрал галочками другие товары - процесс проверки корзины должен начинаться заново)
      • если нет ни ошибок ни предупреждений, сразу открываем экран оформления заказа.

Важно при каждом изменении выбранных товаров запускать проверку корзины заново, а так же заново показывать сообщения об ошибке/успехе от сервисов.

  •  passing  activity identifier to it;
    • show the progress to the customer from ProgressPercent node and call GetBasketCheckingResult method in one second again if there is no error in the response and IsFinished! = true;
    • show text and status (display status by changing line color, Ok - green, Warning - yellow, Error - red) from Messages node for necessary item in the cart 
    • if IsFinished == true hide progress bar and 
      • scroll the screen to the first error and allow customer to correct the error (for example, select different quantity of products and run checking the cart again) if there is at least one Error in Messages;
      • scroll the screen up to the first warning and allow customer to click "place order" button again if there are no errors, but there is at least one Warning. Clicking again should immediately start the process of placing an order without checking the cart again (important: cart checking process should start again if customer changed quantity, configuration or ticked other products);
      • immediately open checkout screen if there are no errors or warnings.

It is important to start cart checking again each time customer changes selected products, as well as re-display error / success messages from the services.

You can place an order "from the cart" calling Заказ можно оформить "из корзины", для этого нужно вызвать метод http://docs.otapi.net/ruen/Documentations/Method?name=CreateOrder  method, передав в негоpassing:

  • элементы корзины (якорь на документацию по корзине)
  • способ доставки
  • профиль пользователя
  • не обязательно: можно предложить пользователю ввести комментарий к заказу.

Дозаказ

Follow-up Order

Allow customer to make a follow-up order (if customer has such an opportunity) when making an order. Get orders that allow to make a follow-up order, call При оформлении заказа, нужно предложить пользователю возможность сделать дозаказ (если такая возможность у пользователя имеется). Получаем заказы, в которые можно сделать дозаказ, вызов http://docs.otapi.net/ruen/Documentations/Method?name=SearchOrdersForUser с параметрами xmlSearchParameters=<OrderSearchParametersForUser><ProviderType>ИдПровайдера(например:  with parameters xmlSearchParameters= <OrderSearchParametersForUser><ProviderType>IDProvider(for example, Taobao)</ProviderType><IsAvailableForRecreation>true</IsAvailableForRecreation></OrderSearchParametersForUser>если такие заказы есть, предлагаем покупателю выбрать: оформляет он новый заказ или делает дозаказ. Для дозаказа нужно вызвать метод . Allow customer to choose if he makes a new order or a follow-up order if there are such orders. Call http://docs.otapi.net/ruen/Documentations/Method?name=RecreateOrder  method for follow-up order.

Быстрый заказ

Quick order

It is possible to make an order from item card by "Quick order" button. Call Заказ можно оформить из карточки товара, кнопка "Быстрый заказ", для этого нужно вызвать метод http://docs.otapi.net/ruen/Documentations/Method?name=AddOrder , передав в него:

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

Оплата заказа и пополнение лицевого счета

 method sending:

  • a list of ordered goods (for quick ordering from card from 1688.com, these are several products of different configurations). It is necessary to pass product ID, configuration ID and quantity for each product (no other parameters need to be passed);
  • delivery method
  • customer profle
  • optional: comment for the order.

Order payment and recharging personal account

If the order is not paid, be sure to offer customer to pay it. Call Если заказ не оплачен, обязательно предлагаем пользователю его оплатить. Если на лицевом счете клиента есть средства - запрос http://docs.otapi.net/ruen/Documentations/Method?name=GetAccountInfo , узле AvailableAmount (при отображении обязательно используем CurrencySign) , предлагаем пользователю кнопку, которая оплатит заказ с лицевого счета. На кнопке пишем сумму доступную для оплаты, это должна быть или RemainAmount из информации о заказе  method if there are funds in customer's personal account, AvailableAmount node (definitely use CurrencySign for display), offer customer a button that will pay for the order from personal account. Write available payment amount on the button, this should be RemainAmount from order information http://docs.otapi.net/ruen/Documentations/Method?name=GetSalesOrderDetails (при условии что на лицевом счете больше чем RemainAmount) или AvailableAmount (при условии что на лицевом счете меньше чем provided that personal account has more than RemainAmount) or AvailableAmount (provided that personal account is less than RemainAmount).

При нажатии на кнопку вызываем метод Call http://docs.otapi.net/ruen/Documentations/Method?name=PaymentPersonalAccount и обновляем страницу заказа. method when clicking the button and refresh order page.

Order can be paid through payment systems. Request a list of available payment systemsЗаказ можно оплатить и через платежные системы. Запрашиваем список доступных платежных системhttp://docs.otapi.net/ruen/Documentations/Method?name=GetPaymentModes . Картинка ПС - AbsoluteImageUrl, название ПС - Name. При клике на платежную систему, отображаем кнопку "Оплатить" и если узел CustomField Image of PS - AbsoluteImageUrl, name of PS - Name. Display "Pay" button after clicking payment system and display email input field if CustomField node == "Email" - отображаем поле ввода почты, если узел CustomField , display phone number input field if CustomField node == "Phone" - отображаем поле ввода номера телефона..

Call При клике на кнопку Оплатить, вызываем метод http://docs.otapi.net/ruen/Documentations/Method?name=GetPaymentParameters . Передаем параметры Amount (RemainAmount из информации о заказе after clicking "Pay" button. Pass the following parameters: Amount (RemainAmount from order information), CurrencyCode, PaymentSystemId, OrderId, в SuccessUrl и FailUrl адреса возврата, которые приложение сможет перехватить. По полученному ответу формируем http-форму, открывем её в браузере, и отправляем её.:and FailUrl return addresses that application can intercept.

Form http-form based on received response, open it in browser and submit it:

  • RequestUrl - url to send the form to;
  • RequestMethod, if it doesn’t come, send a POST form (sometimes you have to send GET, according to parameter);
  • IsNewWindow - you need to open the form in a new window or in the current one, parameter is apparently not relevant for a mobile application - we always open request in a new browser window;
  • IsIFrame - display iframe src
  • RequestUrl - url на который нужно отправить форму
  • RequestMethod , если не пришел отправляем POST форму (иногда приходится отправлять GET, согласно параметру)
  • IsNewWindow - нужно открыть форму в новом окне или в текущем, для мобильного приложения параметр видимо не актуален - всегда открываем запрос в новом окне браузера
  • IsIFrame - вместо form отображаем в браузере iframe src={RequestUrl}?{Parameters вида type param1=value1&param2=value2} in browser instead of form;
  • IsImmmediate - пока игнорируем в мобильном приложении
  • Parameters - список параметров платежа6 которыее надо обработать в зависимости от свойства IsUserData7
    • Если IsUserData==false, параметр нужно вставить в форму, для передачи в платежную систему.
    • Если IsUserData==true, параметр нужно просто вывести на экран.

Если в метод GetPaymentParameters не передать OrderId , то лицевой счет клиента пополнится на сумму Amount.

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

  • ignore in mobile application at the moment;
  • Parameters - list of payment parameters to be processed depending on property IsUserData7
    • parameter must be inserted into the form to pass to payment system if IsUserData==false;
    • display parameter on the screen if IsUserData==true.

Customer’s personal account will be replenished by Amount if you don't pass OrderId into GetPaymentParameters method.

Browser will return to one of the transmitted addresses after successful or unsuccessful payment, accordingly application should intercept them, close browser and show appropriate screen.