Wix Answers SDK Overview

Wix Answers provides several features for running your own code directly within the Wix Answers framework. The code that you run enables you to add or hide elements, change the size, position or color of elements, and so forth.
  • Backoffice SDK: Code run to support agent activities that runs when agents are managing Wix Answer using the Wix Answers App.
  • Help Center SDK: Code run to change the public experience of your Wix Answers Help Center (for users and guests).
  • Widget Client SDK: Code run on the web pages that host a Wix Answers widget to customize the widget.

Related Articles

Wix Answers API Overview

The WIX Answers REST API enables you to use code to interact with the Wix Answers back-end. You can use the API to create webhooks that interact with the Wix Answers front and back-ends, or create a new front-end app that works with the Wix Answers back-end. You can also use the API to get information about your customers and their Wix Answers history.The API documentation assumes that you are familiar with Wix Answers features and have read the knowledge base articles about these features.The API documentation includes articles with the following subcategories in the Developers category:API Overview: This documentAPI Reference: All public Wix Answers APIs, as well as common objects returned by APIs. Start with the API Reference Overview.Procedures: Frequently asked workflow questions, such as how to find information you might need or how to combine APIs or webhooks to perform common proceduresSDK: How and where to create code that works with the APIs and back-end. Start with the Wix Answers SDK Overview.Webhooks: How to create webhooks that may be called from the APIsNote: Keep a Debug LogWe highly recommend that you create a minimum 3-day log of responses from Wix Answers. This will ease your debugging process in the case of any issues.You can test API calls using cURL or any similar software.Wix API methods accept HTTPS requests in JSON content-type with UTF-8 character set (application/json; charset=utf-8). Parameters are case-sensitive: for example, ID is not accepted when id is expected.Successful responses are returned by HTTPS in JSON format (application/json) with status headers that include codes in the 200-300 range. For example:Status: 200 { "id": "bd948e62-a3fd-4cf0-87f3-ee6a0ae7f3fa", "name": "Article Title", ... "creationDate": 1568180889000 }API EndpointAll URLs referenced in the API documentation have the following endpoint: https://<tenant_subdomain>.wixanswers.comAuthorizationSome API endpoints do not require authorization. Most endpoints require a JWT authorization token. The token is valid for one hour and must be sent on every request using an Authorization header:Authorization: Bearer <token>App Settings, Roles, and PermissionsWix Answers uses app settings, roles, and permissions to determine whether you are allowed to access an endpoint.You can configure app settings to restrict access to specific endpoints. The token retrieved by an app with these settings cannot access these endpoints, regardless of your role/permissions.Any user can access some endpoints without any permissions. However, see Token Types, below. For all other endpoints, a user must be an agent with a specific role. An agent is a user that is assigned any role.Roles are collections of permissions. Wix Answers comes with three out-of-the-box roles: Viewer, Agent, and Admin. Viewers have read-only access to Wix Answers endpoints and the Wix Answers app. Agents can do anything Viewers can do, but they also can manage users, tickets, articles, calls, and other non-administrative areas of the app. An Admin(istrator) can do anything an Agent can do, and can also manage other agents and perform other administrative tasks.  An admin can define other roles in the Wix Answers App.You can access any endpoints that are enabled for any permissions of your role, as long as these permissions are also enabled by the app settings. In addition, some endpoints simply require you to be an agent; you can access these endpoints as long as you are an agent, with any role.For more information, see Roles and Permissions.Token TypesA user-specific authorization token has the authorization for that user. This token not only has the permissions of the user, it also contains the user's ID. A general authorization token (not specific to a user) has all of the permissions enabled by the app settings, but does not contain a user ID.Some endpoints require a user-specific authorization token. For these endpoints, a general authorization token does not work, even though the general token has the required permissions. For example, adding a ticket as a specific user requires a user-specific token; see Add a Ticket as Authenticated User.For all other endpoints, you can use a general token or a user-specific token with the required permissions. If you use the general token, Wix Answers records the activity as done by the default admin user for your tenant, which appears as "System User" in the Wix Answers UI.In some cases, such as reading articles on a public website, no authorization token is required.Help Center Authorization OverrideYou can configure your help center to require users to register before they can access any contents. In this case, all API calls require an authorization token, even if no authorization is indicated in the documentation.Tokens with no User SpecifiedIf you request a token without specifying the user that the token is for, the token is a general token with admin privileges, but will not work for endpoints that require a token associated with a specific user.Authenticated UsersTo be an authenticated user means that Wix Answers has authenticated the user's email and the user has a unique ID (GUID).Chat Unauthenticated User HeaderWhen calling a chat API without an authenticated user token, you must add an additional header to the API request. For more information, see Chat Unauthenticated User Header in the Chats API page.Requesting an Authorization Token (Without Specifying a User)Requesting an Authorization Token Must be Made as a Server-Side RequestYou send the tenant secret in order to obtain an authorization token. This secret is extremely sensitive and must be kept private. Therefore, requests to obtain an authorization token must be made from your servers as server-side requests, NOT from a client.The authorization token is also sensitive, since it enables its holder to act on behalf of the user that it represents. It is important to ensure that the token is kept secure (from everyone except the client/user who will use it). Therefore, Wix Answers recommends that all client requests be made to your servers, which in turn send the token as server-side requests to the Wix Answers API.To obtain an API token without specifying a user:In the Wix Answers app, navigate to Settings > Webhooks & API Keys (https://<tenant_subdomain>.wixanswers.com/app/settings/tools/webhooks-and-api/webhooks) and copy Key ID (Public) and Secret (Private).Make a request to the token generator endpoint, with the parameters key and secret (both are required).POST https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/tokenContent type: application/json; charset=utf-8Accept: application/jsonPayload Structure:POST https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/token { "keyId":"<key_id>", "secret":"<secret>" }Request Example Using cURL:curl -XPOST 'https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/token' -d '{ "keyId":"<key_id>", "secret":"<secret>" }' -H 'Content-Type: application/json; charset=utf-8' -H 'Accept: application/json'Response Example:{ "token":"eyJlbmMiOiJBMTI0NNIiwiYWxnIjoiZGlyIn0..9-fRNeE8J3SspYg9.3eaSroE6kEIpLfdgmhg0fvOxMUs1YAHZC6dHacAkZOOjD1EA-1pApV863H1fxqCVoGbq2163PnE--83rFqU4RxbH33tTbfw0kE-baf1YEnbVt5MOWoQ_F59FzY.BiTX-Ao-OcaDeRuEDIuaeA" }Requesting a Specific User's Authorization Token POST https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/tokenIf you have the required permission (users with the agent or admin roles have this permission), you can get a token for a specific user. This kind of token is required where noted in the documentation. You must have the user's GUID.Content type: application/json; charset=utf-8Accept: application/jsonPayload Structure:POST https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/token { "keyId":"<key_id>", "secret":"<secret>", "userId":"<GUID>" }Request Example Using cURL:curl -XPOST 'https://<tenant_subdomain>.wixanswers.com/api/v1/accounts/token' -d '{ "keyId":"<key_id>", "secret":"<secret>", "userId":"77bc8694-5ccf-436c-ab2b-543563a5f425" }' -H 'Content-Type: application/json; charset=utf-8' -H 'Accept: application/json'Response Example:{ "token":"eyJlbmMiOiJBMTI0NNIiwiYWxnIjoiZGlyIn0..9-fRNeE8J3SspYg9.3eaSroE6kEIpLfdgmhg0fvOxMUs1YAHZC6dHacAkZOOjD1EA-1pApV863H1fxqCVoGbq2163PnE--83rFqU4RxbH33tTbfw0kE-baf1YEnbVt5MOWoQ_F59FzY.BiTX-Ao-OcaDeRuEDIuaeA" }Requesting a Specific User's Authorization Token from a Widget POST https://<tenant_subdomain>.wixanswers.com/api/v1/widgets/{widget GUID}/authIf you have the required permission (users with the agent or admin roles have this permission), you can get a token for a specific user from a widget using the user's email address. If the user is not registered as authenticated in Wix Answers, Wix Answers registers the user as authenticated before returning the token.This is a shorter process than adding the user, receiving the user's GUID, and then requesting a token using the GUID.Content type: application/json; charset=utf-8Accept: application/jsonPayload Structure:POST https://<tenant_subdomain>.wixanswers.com/api/v1/widgets/{widget GUID}/auth { "email":"<email_address>", "keyId":"<key_id>", "secret":"<secret>", "externalId":"<external_SSO_ID>",// String. If provided, and the tenant // uses SSO, then this value is used // to identify the user, instead of // the email address. // If Wix Answers registers this user as an authenticated user, // it will add the following optional parameters to the user record. // If the tenant uses SSO, it will also add the email address (above). // If the user is already registered, these parameters are ignored. "firstName":"<first_name>", // If not provided, the username // of the email address is used. "lastName":"<last_name>" }Request Example Using cURL:curl -XPOST 'POST https://<tenant_subdomain>.wixanswers.com/api/v1/widgets/77bc8694-5ccf-436c-ab2b-543563a5f425/auth' -d '{ "keyId":"<key_id>", "secret":"<secret>", "email":"user@yourdomain.com" }' -H 'Content-Type: application/json; charset=utf-8' -H 'Accept: application/json'Response Example:{ "token":"eyJlbmMiOiJBMTI0NNIiwiYWxnIjoiZGlyIn0..9-fRNeE8J3SspYg9.3eaSroE6kEIpLfdgmhg0fvOxMUs1YAHZC6dHacAkZOOjD1EA-1pApV863H1fxqCVoGbq2163PnE--83rFqU4RxbH33tTbfw0kE-baf1YEnbVt5MOWoQ_F59FzY.BiTX-Ao-OcaDeRuEDIuaeA" }Important Information about Updating Structures Using the APIFields in a PUT request entirely replace the fields in the Wix Answers back-end. Unless noted, you cannot append information to an existing field.To modify the existing contents of a field:Get the structure using the relevant GET request.Extract the relevant field.Modify the field as required.PUT the modified field back to Wix Answers.Common Elements in API Payloads / ObjectsThe following formats or values repeatedly appear in the requests you make to, or in the structures returned by, Wix Answers.Note About Undocumented ParametersMost return structures include additional parameters not documented in this guide. These parameters are irrelevant and can be safely ignored.Global IDs (GUID)Many records, such as users, tickets, labels, and so forth, are uniquely identified by a global ID, also known as a GUID. A GUID looks something like e932c0a3-6e9b-43cf-b3a9-90f6ee6a5b07.Unix Time StringsUnix time strings are integers indicating the number of seconds since Jan 1, 1970 00:00:00. Unix time strings are commonly used to indicate the creation or last modified time of a record.Languages / LocalesClick here to see the list of supported languages.Import IDDuring the Wix Answers on-boarding process, Wix Answers can help you load your initial data by importing users, companies, articles, categories, tickets, and replies. These items are tagged during the import process with an import ID (importId).You can use your own code (such as in a webhook) to filter these items based on their import ID.API Request Rate LimitThe Wix Answers APIs have a rate limit. We reserve the right to adjust the rate limit for given endpoints so we can provide a high quality of service for all clients. If you need to make more requests than the limit, please contact us and we will try to accommodate your request.API Usage Legal NoticeYour use and access to the API are expressly conditioned on your compliance with the policies, restrictions, and other provisions related to the API set forth in our Terms of Use and our Privacy Policy. If we believe that you have or attempted to violate any term, condition, or the spirit of these policies or agreements, your right to access and use the API may be temporarily or permanently revoked.

9 min read

Widget Client SDK

ImportantImproperly applying customizations with the widget client SDK can impact the Wix Answers widget experience.The Widget Client SDK enables you to add JavaScript code to customize a Wix Answers widget that appears on your page (see Installing a Widget on Your Website), including the widget icon, tooltip, and badge, general screen appearance, user authentication, and chat. You use this SDK by adding JavaScript on the page on which the widget appears, after the widget is loaded: add the relevant JavaScript to the callback function sent as a parameter to AnswersWidget.onLoaded.You can test the code in your browser console before entering it on your page.The SDK enables you to access various events, such as chat started or ended, and receive the relevant info to add custom functionality.NoteIf you have specific integration needs not met using the existing SDK, contact us at help@wixanswers.com with your request.Methods By SubjectMethodDescriptionPage InteractionAnswersWidget.onLoadedExecute a callback when the widget is loaded.This is the only method available before the widget is loaded. Add all of your other code to the listener configured for this function.AnswersWidget.showDisplay the widget.AnswersWidget.hideHide the widget.AnswersWidget.setOffsetSet the location of the widget on the page, relative to the widget's initial X and Y position.AnswersWidget.onDragEndExecute a callback function immediately after the user finishes dragging the widget.AnswersWidget.openOpen the widget screen.AnswersWidget.onWidgetOpenedExecute a callback when the widget screen is opened.AnswersWidget.closeClose the widget screen.AnswersWidget.onWidgetClosedExecute a callback when the widget screen is closed.AnswersWidget.destroyDestroy the widget.Icon and Tooltip ConfigAnswersWidget.setLauncherIconSvgSet the launcher icon to the passed SVG content string.AnswersWidget.setTooltipConfigSet the contents and delay of the widget tooltip that appears when the page with the widget is first loaded.AnswersWidget.onTooltipClosedExecute a callback when the tooltip is closed.AnswersWidget.setUnreadMessageConfigConfigure the tooltip background, and whether to show the tooltip even when there are no unread messages.Widget ConfigAnswersWidget.addHtmlToHomePageHeaderAdd HTML to the end of header of the widget home page.AnswersWidget.addHtmlToKbHeaderAdd HTML to the end of header of every category, article list, and article pages.AnswersWidget.featuredArticlesSearchDisplay only the featured articles that match a search term.AnswersWidget.setLabelsSet the labels that are automatically added to all new tickets, chats, and callbacks.AnswersWidget.ejectFromElementByIdEject the widget view from a DOM element, by ID.AnswersWidget.injectToElementByIdInject the widget view into a DOM element.AnswersWidget.setCustomFieldsSet custom fields for a chat, ticket, or callback.AnswersWidget.setOverrideTextsOverride texts in the widget.Authentication and Initial ContentsAnswersWidget.addAuthenticationFnAdd an authentication function (make this an authenticated widget).AnswersWidget.fillContactFormPrefill the email contact form with contents.AnswersWidget.identifyUserSet the user's email address, for chat, email, or callbacks.AnswersWidget.goToArticleOpen an article in the widget screen.AnswersWidget.goToCategoryOpen a category in the widget screen.AnswersWidget.goToCallbackOpen the callback contact form in the widget screen.AnswersWidget.goToChatOpen the chat contact form in the widget screen.AnswersWidget.goToContactOpen the email contact form in the widget screen.Chat ConfigAnswersWidget.hasActiveChatConversationGet whether the user started a chat that was not finished and closed.AnswersWidget.onChatMessageReceivedExecute a callback when a chat message is received.AnswersWidget.onChatMessageSentExecute a callback when a chat message is sent.AnswersWidget.onChatStartedExecute a callback when a chat starts.AnswersWidget.sendChatMessageAdd a "bot message" to a chat.Methods ReferenceAnswersWidget.addHtmlToHomePageHeader(HTML:string)Add HTML to the end of header of the widget home page.Returns: NoneFor example, the following shows a home page with an embedded SVG file.AnswersWidget.addHtmlToHomePageHeader(html);AnswersWidget.addHtmlToKbHeader(HTML:string)Add HTML to the end of header of every category, article list, and article pages.Returns: NoneFor example, the following shows a page with a custom header.AnswersWidget.addHtmlToKbHeader(html);AnswersWidget.addAuthenticationFn(authFn:function)Add an authentication function. The function is called with no arguments and must return a Promise that resolves to a token string.To learn about authenticated widgets see here.Returns: NoneAnswersWidget.addAuthenticationFn(authenticationFunction);AnswersWidget.close()Close the widget screen.Returns: NoneAnswersWidget.close()AnswersWidget.destroy()Destroy the widget.Returns: NoneAnswersWidget.destroy()AnswersWidget.ejectFromElementById(DOM-ID:string)Eject the widget view from a DOM element, by ID.Returns: NoneAnswersWidget.ejectFromElementById(DOM_ELEMENT_ID)AnswersWidget.featuredArticlesSearch(searchTerm:string)Display only the featured articles that match the search term. You configure featured articles in the Wix Answers app when configuring the widget. This method enables you to display relevant articles only, based on the page topic (for example).Returns: NoneAnswersWidget.featuredArticlesSearch(searchTerm) // For example AnswersWidget.featuredArticlesSearch("electronics")AnswersWidget.fillContactForm({subject: subject:string, description: description:string})Prepopulate the email contact form with a subject and/or description. Also see AnswersWidget.goToContact.Returns: NoneAnswersWidget.fillContactForm({subject: subject, description: description}) // For example AnswersWidget.fillContactForm({subject: 'This is the subject', description: 'This is description'})AnswersWidget.goToArticle(article:GUID)Open an article in the widget screen.Returns: NoneAnswersWidget.goToArticle(ARTICLE_ID)AnswersWidget.goToCallback()Open the callback contact form in the widget screen.Returns: NoneAnswersWidget.goToCallback()AnswersWidget.goToCategory(category:GUID)Open a category in the widget screen.Returns: NoneAnswersWidget.goToCategory(CATEGORY_ID)AnswersWidget.goToChat()Open the chat contact form in the widget screen.Returns: NoneAnswersWidget.goToChat()AnswersWidget.goToContact()Open the email contact form in the widget screen. Also see AnswersWidget.fillContactForm.Returns: NoneAnswersWidget.goToContact()AnswersWidget.hasActiveChatConversation()Get whether the user started a chat that was not finished and closed. A return of false indicates that no chat was started, or any chats have been closed.Returns: Promise that resolves to a Booleanvar result = await AnswersWidget.hasActiveChatConversation(); // or AnswersWidget.hasActiveChatConversation().then(function(result){ // do something with result })AnswersWidget.hide()Hide the widget.Returns: NoneAnswersWidget.hide()AnswersWidget.identifyUser({name: username:string, email: email-address:string})Set the user's email address, for chat, email, or callbacks.Returns: NoneAnswersWidget.identifyUser({email: 'iknowyouremail@gmail.com'});AnswersWidget.injectToElementById(DOM-ID:string)Inject the widget view into a DOM element. The DOM element must be empty.Returns: NoneAnswersWidget.injectToElementById(DOM_ELEMENT_ID)AnswersWidget.onChatMessageReceived(listener:function)Execute a callback when a chat message is received.Returns: NoneAnswersWidget.onChatMessageReceived(callback);The callback is called with the following parameters:{ messageId: <GUID>, ticketId: <GUID>, agentMessageIdx: <integer>, // The number message from the agent agentId: <GUID> }AnswersWidget.onChatMessageSent(listener:function)Execute a callback when a chat message is sent.Returns: NoneAnswersWidget.onChatMessageSent(callback);The callback is called with the following parameters:{ messageId: <GUID>, ticketId: <GUID>, userMessageIdx: <integer>, // The number message from the user isFile: <Boolean> // Whether the message is a file }AnswersWidget.onChatStarted(listener:function)Execute a callback when a chat starts.Returns: NoneAnswersWidget.onChatStarted(callback);The callback is called with the following parameters:{ ticketId: <GUID> }AnswersWidget.onDragEnd(listener:function)Execute a callback function immediately after the user finishes dragging the widget.Returns: NoneAnswersWidget.onDragEnd(callback)The callback is called with the following parameters:{ x: <integer>, // Target X offset from its initial location, in pixels y: <integer> // Target Y offset from its initial location, in pixels }AnswersWidget.onLoaded(listener:function)Execute a callback when the widget is loaded.This is the only method available before the widget is loaded. Add all of your other code to the listener configured for this function.Returns: Nonewindow.AnswersWidget.onLoaded(function() { window.AnswersWidget.goToArticle('1324-13425-13542-1r4526'); } );AnswersWidget.onTooltipClosed(listener:function)Execute a callback when the tooltip is closed.Returns: NoneAnswersWidget.onTooltipClosed(callback);AnswersWidget.onWidgetClosed(listener:function)Execute a callback when the widget screen is closed.Returns: NoneAnswersWidget.onWidgetClosed(callback);AnswersWidget.onWidgetOpened(listener:function)Execute a callback when the widget screen is opened.Returns: NoneAnswersWidget.onWidgetOpened(callback);AnswersWidget.open()Open the widget screen.Returns: NoneAnswersWidget.open()AnswersWidget.sendChatMessage({content: message:string})Add a "bot message" to a chat.Returns: NoneAnswersWidget.sendChatMessage({content: 'Your message goes here'});AnswersWidget.setCustomFields({field-name:string : value:*, ...})Set custom fields for a chat, ticket, or callback. * The value types depend on the custom field.Returns: NoneAnswersWidget.setCustomFields({firstFieldName: 'first field value', secondFieldName: 'second field value'});AnswersWidget.setLabels([label:GUID, ...])Set the labels that are automatically added to all new tickets, chats, and callbacks.Returns: NoneAnswersWidget.setLabels(["bd948e62-a3fd-4cf0-87f3-ee6a0ae7f3fa","e932c0a3-6e9b-43cf-b3a9-0ae790f6ee6a"])AnswersWidget.setLauncherIconSvg(SVG:string)Set the launcher icon to the passed SVG content string.Returns: NoneAnswersWidget.setLauncherIconSvg(svg)AnswersWidget.setOffset(X-pos:integer,Y-pos:integer)Set the location of the widget on the page, relative to the widget's initial X and Y position. X and Y can be positive or negative.Returns: NoneAnswersWidget.setOffset(300,500)AnswersWidget.setOverrideTexts({text-field-name:string : value:string, ...})Override texts in the widget.You can find the text field names in the Help Center at Settings > New Widgets; select the Help row; select the Advanced tab; in Language Text Settings, select Edit (or navigate to https://<tenant_subdomain>.wixanswers.com/app/settings/widgets/{GUID}/advanced/{locale}/texts).The input structure is a map of field names to values.Returns: NoneAnswersWidget.setOverrideTexts({ "widget-v3.widget-launcher.icon-message": "Hi!", "widget-v3.widget-home.contact-button.contact-title": "Contact Us!" })AnswersWidget.setTooltipConfig(tooltip-text:string, delay-in-seconds:integer)Set the contents and delay of the widget tooltip that appears when the page with the widget is first loaded. The default delay is 0.Returns: NoneAnswersWidget.setTooltipConfig(tt_content,2)AnswersWidget.setUnreadMessageConfig(background-color:string,show-on-no-unread:Boolean)A badge with the unread message count may appear when the user closes the widget when there is an active chat in progress. Use this to configure the tooltip background, and whether to show the tooltip even when there are no unread messages (the default is false}.Returns: NoneAnswersWidget.setUnreadMessageConfig("#ffffff",true)The default background color is #389eec.For example, the closed widget appears as follows if there are no unread messages, and the second argument is set to true.The closed widget appears as follows if there are two unread messages.AnswersWidget.show()Display the widget.Returns: NoneAnswersWidget.show()

7 min read

Help Center SDK

ImportantImproperly applying customizations with the Help Center SDK can impact the Wix Answers Help Center experience.Because our Help Center is a single page application, it can be challenging to add customization based on the visible page.The Help Center SDK enables you to add JavaScript code to customize the Wix Help Center, which is used by guests and users. You manage this SDK by adding JavaScript on the Custom Scripts page (Settings > Help Center > Advanced and select Custom Scripts; or navigate to https://<tenant_subdomain>.wixanswers.com/app/settings/helpcenter/advanced/custom-scripts). You can test the code in your browser console before entering it on the Custom Scripts page. The SDK enables you to access various events such as page load and receive the relevant info to add custom functionality.ImportantExcept where noted, methods must be called only after the SDK is loaded.NoteIf you have specific integration needs not met using the existing SDK, contact us at help@wixanswers.com with your request.MethodsanswersSdk.addListener(eventType:EventType, listener:function)Add an event listener to a Help Center event.Returns: NoneThe event types are as follows:EventDescriptionanswersSdk.events.contactFieldsChangedTriggered when the contact form (default fields or custom fields) changes.answersSdk.events.pageLoadTriggered when the user navigates to a page.For example, to add a listener that runs when the page loads:answersSdk.addListener(answersSdk.events.pageLoad, function (data) { if (data.pageType === answersSdk.pages.homePage) { console.log('Home page has loaded!'); }; });To add a listener that runs when the contact form (default fields or custom fields) changes:answersSdk.addListener(answersSdk.events.contactFieldsChanged, function (ticketFields) { console.info('Fields changed', ticketFields); }); answersSdk.getCurrentLanguage()Get the currently selected language of the Help Center.Returns: StringFor example:if (answersSdk.getCurrentLanguage() === 'fr') { alert('You are viewing this page in French!'); }answersSdk.getCurrentUser()Get the logged in user object, or null if the user is not logged in.Returns: User objectanswersSdk.getVisiblePageData()Get the data of the current visible page. The data structure depends on the page type.Returns: ObjectFor example:console.log('Page data', answersSdk.getVisiblePageData());answersSdk.getVisiblePageType()Get the type of the current page.Returns: PageTypeFor example:if (answersSdk.getVisiblePageType() === answersSdk.pages.article) { alert('You are inside an article'); }answersSdk.login()Redirect the user to the login page.Returns: NoneanswersSdk.onLoad(listener:function)Run a callback function after the Help Center is loaded.Returns: NoneFor example:answersSdk.onLoad(function () { // Answers has loaded! we can assume all dom // elements are visible now alert('Answers is fully loaded!'); });answersSdk.onUserLoaded(listener:function)Run a callback function after the user has loaded. If there is a user session, the callback function is passed the User object. Otherwise, the function is called with no parameters.Returns: NoneFor example:answersSdk.onUserLoaded(function (user) { // Current user is now available. if (user) { console.info('A user is logged in!', user); } else { console.info('This is an anonymous visit'); } });TipUse this combined with setContentFilters to control content based on attributes of the logged in user.answersSdk.setContentFilters(filters:object)Set content scope dynamically. For more information, see content scope settings. The filters can contain several options.The input is an object, as follows:{    categoryIds: [<list of categories to include if the article matches any of them>],    excludedCategoryIds: [<list of categories to exclude if the article matches any of them>],    hasAllOfLabelIds: [<list of labels to include if the article matches all of them>],    hasAnyOfLabelIds:  [<list of labels to include if the article matches any of them>],    notHasAnyOfLabelIds: [<list of labels to exclude if the article matches any of them>],}Returns: NoneExample filters object parameter:{ notHasAnyOfLabelIds: [premiumLabelId] }See Limit Article Scope Dynamically, below, for an example.ImportantYou can call this method before the SDK is loaded. To affect your homepage, this must be called before the SDK is loaded.NoteExcluded content is not visible in the Help Center, and is not indexed by search engines, but is still visible by users arriving using a direct URL.answersSdk.setTicketFields(fields:object)Pre-fill contact forms with data. This applies to both the contact page and the contact form that appears in the article page.Returns: NoneExample field object:{ fullname: "Bob Bobson", email: "bob@bobcorp.com", title: "Upgrade Request", description: "some text here", customFields: {} // object containing custom fields }NoteAll fields are optional. Only fields included in the parameters are prefilled.PageType EnumerationThe following page types are available:TypeDescriptionanswersSdk.pages.userProfileanswersSdk.pages.ticketanswersSdk.pages.articleanswersSdk.pages.submitTicketContact pageanswersSdk.pages.categoryanswersSdk.pages.searchResultsanswersSdk.pages.homePageExamplesHere are some examples of customization that can be applied using the SDK.Add a Banner to the Home Pagefunction addBanner() { var bannerHtml = '<marquee><h3>Welcome to our Help Center</h3><p>We hope you enjoy it!</p></marquee>'; document.querySelector('hero').insertAdjacentHTML('afterend', bannerHtml); } answersSdk.onLoad(function () { // Listen to the page event to ensure that if the user navigates back to the home page it will render the banner again. answersSdk.addListener(answersSdk.events.pageLoad, function (data) { if (data.pageType === answersSdk.pages.homePage) { addBanner(); } }); });Show Alert on Specific Articlesvar specialArticleIds = [ '1ad262da-d909-11e7-9296-cec278b6b50a', '1ad26578-d909-11e7-9296-cec278b6b50a', '1ad268de-d909-11e7-9296-cec278b6b50a', '1ad26a28-d909-11e7-9296-cec278b6b50a' ]; answersSdk.onLoad(function () { answersSdk.addListener(answersSdk.events.pageLoad, function (eventData) { if (eventData.pageType === answersSdk.pages.article) { var isSpecialArticle = specialArticleIds.indexOf(answersSdk.getVisiblePageItemId()) !== -1; if (isSpecialArticle) { alert('Hi there! You just found one of our special articles'); } } }); }); Hide Components on Specific Articles function hideComponents() { $('.search-box').hide(); // hides search $('.breadcrumbs').hide(); // hides breadcrumbs } answersSdk.onLoad(function () { var articleIds = [ '1ad262da-d909-11e7-9296-cec278b6b50a', '1ad26578-d909-11e7-9296-cec278b6b50b', '1ad268de-d909-11e7-9296-cec278b6b50c', '1ad26a28-d909-11e7-9296-cec278b6b50d' ]; answersSdk.addListener(answersSdk.events.pageLoad, function (eventData) { if (eventData.pageType === answersSdk.pages.article) { var shouldHideComponents = articleIds.indexOf(answersSdk.getVisiblePageItemId()) !== -1; if (shouldHideComponents) { hideComponents(); } } }); });Limit Article Scope DynamicallyYou might want to filter the content visible to users depending on their status. The following is a simplistic example on how to achieve this.var premiumLabelId = '843487b1-e98b-4d0d-ba93-666c4339c23e'; var freeLabelId = '143487b1-e44b-4444-ba93-666c4339c234'; /* This might do an HTTPS request to your server assuming your Help Center is under the same domain. You can check this using an auth cookie. */ checkServiceForUserStatus() .then(function (userType) { if (userType === 'free') { // if the user is free, exclude all articles that have the "premium" label. answersSdk.setContentFilters({ notHasAnyOfLabelIds: [premiumLabelId] }); } else { // And vice versa answersSdk.setContentFilters({ notHasAnyOfLabelIds: [freeLabelId] }); } });Auto Log In UsersIn combination with SSO, you might want to keep your users always logged in to Wix Answers.answersSdk.onLoad(function () { if (!answersSdk.getCurrentAgent()) { // You might want to check if the user is logged in by querying a client-side cookie or calling an API. answersSdk.login(); } });

5 min read

Backoffice SDK

ImportantImproperly applying customizations with the backoffice SDK can impact the Wix Answers App experience.The Backoffice SDK enables you to add JavaScript code to customize the Wix Answers App, which is used by agents and administrators. You manage this SDK by adding JavaScript to the Custom JS pane on the Backoffice Custom Code page (https://<tenant_subdomain>.wixanswers.com/app/settings/custom-code).You can test the code in your browser console before entering it on the Backoffice Custom Code page.The following are some examples of what you can do using the SDK.NoteIf you have specific integration needs not met using the existing SDK, contact us at help@wixanswers.com with your request.MethodsaddListener(eventType:EventType, listener:function)Add a listener for an event. Different payload are sent for different events.Returns: NoneThe event types are as follows:TypeDescriptionPayloadeventTypes.appLoadedApp LoadedNoneeventTypes.ticketLoadedTicket page loaded{ticket: Ticket object, timeline: Ticket timeline object}eventTypes.ticketWillLoadTicket page is about to be loaded{ticket: Ticket object, timeline: Ticket timeline object}eventTypes.ticketInfoSectionAddedAn info section was added to a ticket??eventTypes.ticketRelationAddedArticle relation added to a ticket{ticket: Ticket, articleIds: [list of article GUIDs]}eventTypes.ticketRepliedAgent replied to a ticket (not internal note){ticket: Ticket, replyContent: string}eventTypes.ticketCustomFieldsUpdatedTicket's custom field value added or modified{ticket: Ticket, customFields: Map of {<field-name>: <value>}}value format varies according to field type.eventTypes.multipleTicketsRepliedAgent replied in bulk to multiple tickets (not internal notes){tickets: [list of ticket objects], replyContent: string}eventTypes.multipleTicketsRelationAddedArticle relation added in bulk to multiple tickets{tickets: [list of ticket objects], articleIds: [list of article GUIDs]}addTicketInfoSection(title:string, HTML:string, isOpen:Boolean)Add information section to the right sidebar when viewing a ticket. Set the third parameter to true to configure that the new section is open by default.Returns: NoneforceSavedRepliesSearchLocale(locale:two-letter locale string)Configure that saved replies are searched only in the specified locale.Returns: NonegetCurrentAgentGet list current agent.Returns: Agent objectinsertHtmlToReplyArea(HTML:string)Append HTML to the reply area without sending the reply.Returns: Nonenotify({content: string})Pop up a UI notification on the bottom right of the screen.Returns: None.notify({'content': 'Something wonderful happened!'})setTicketRelatedArticlesFilter(filters:object)Filter articles available to select in the related articles picker.The input is an object, as follows:{    categoryIds: [<list of categories to include if the article matches any of them>],    excludeCategoryIds: [<list of categories to exclude if the article matches any of them>],    hasAllOfLabelIds: [<list of labels to include if the article matches all of them>],    hasAnyOfLabelIds:  [<list of labels to include if the article matches any of them>],    notHasAnyOfLabelIds: [<list of labels to exclude if the article matches any of them>],}Returns: NoneExamplesAdding a Custom Section in the User Information SidebarTo create a custom section in the user's information side bar inside a ticket page, add two methods: answersBackofficeSdk.addListeneranswersBackofficeSdk.addTicketInfoSectionThe first method enables Wix Answers to listen to the "ticket page loaded" event and receive the ticket's data. The second enables Wix Answers to add custom sections to the side bar.Here is an example of a snippet that queries some service, checks if the user that opened the ticket is a "premium" user or not, and adds a custom section to the ticket page side bar.function isPremiumUserByEmail(email, cb) { var isPremium = Math.random() > 0.5; //dummy check, replace this with an AJAX call to an external service, or any other meaningful action cb(isPremium); } function addPremiumUserSidebarItem(isPremium) { answersBackofficeSdk.addTicketInfoSection('Custom Data', '<p>Premium: ' + isPremium + '</p>'); } answersBackofficeSdk.addListener(answersBackofficeSdk.eventTypes.ticketLoaded, function (ticketData) { console.info(ticketData); isPremiumUserByEmail(ticketData.user.email, function (isPremium) { addPremiumUserSidebarItem(isPremium); }); });Test this script by adding it in the developers console and then navigating to a ticket page. To add this to your site, enter the script in the Custom JS pane on the Backoffice Custom Code page.When the script is active, your sidebar includes the following:Hide Widgets from the Settings MenuAdd the function answersBackofficeSdk.setHiddenWidgetIds to make widgets accessible only using a direct link. This is useful if you want to prevent accidental changes to your widget's settings.answersBackofficeSdk.setHiddenWidgetIds([ 'a601657c-d618-be0f-a943-e6181512073f', 'b342347a-1528-4fed-2323-234234ababa2' ]);

3 min read