FastComments.com

The FastComments API

FastComments предоставя API за взаимодействие с множество ресурси. Създавайте интеграции с нашата платформа или дори изграждайте свои собствени клиенти!

В тази документация ще намерите всички поддържани ресурси от API, документирани с техните типове заявки и отговори.

За корпоративни клиенти, целият достъп до API се записва в дневника на одита.

Generated SDKs

FastComments вече генерира един API Spec от нашия код (това все още не е пълно, но включва много APIs).

Също така вече разполагаме със SDK за популярни езици:

Authentication

API-то се удостоверява чрез подаване на вашия api key като или X-API-KEY хедър, или като API_KEY query параметър. Също така ще ви е необходим вашият tenantId за извършване на API повиквания. Той може да бъде получен от същата страница като вашия api key.

Security Note

Тези рутове са предназначени да се вика от сървър. НЕ ги викайте от браузър. Правенето на това ще изложи вашия API key - това ще предостави пълен достъп до вашия акаунт на всеки, който може да види изходния код на страница!

Authentication Option One - Headers

  • Хедър: X-API-KEY
  • Хедър: X-TENANT-ID

Authentication Option Two - Query Parameters

  • Параметър на заявката: API_KEY
  • Параметър на заявката: tenantId

Структура на AuditLog Internal Link

AuditLog е обект, който представлява одитирано събитие за наематели, които имат достъп до тази функция.

Структурата на обекта AuditLog е следната:

Структура на AuditLog
Copy Copy
1
2interface AuditLog {
3 id: string;
4 userId?: string;
5 username?: string;
6 resourceName: string;
7 crudType: 'c' | 'r' | 'u' | 'd' | 'login';
8 from: string;
9 url?: string;
10 ip?: string;
11 when: string;
12 description?: string;
13 serverStartDate: string;
14 objectDetails?: object;
15}
16

Одитният дневник е неизменяем. Също така не може да се записва ръчно. Само FastComments.com може да реши кога да записва в одитния дневник. Въпреки това можете да четете от него чрез този API.

Събитията в одитния дневник изтичат след две години.

Структура на коментара Internal Link

Обектът Comment представлява коментар, оставен от потребител.

Връзката между родителски и дъщерни коментари се определя чрез parentId.

Структурата на обекта Comment е следната:

Структура на Comment
Copy Copy
1
2interface Comment {
3 /** READONLY: Set to true if the spam engine determined the comment was spam. **/
4 aiDeterminedSpam?: boolean
5 /** Whether the comment is approved to show. Set to true when saving the comment, else it will be hidden. **/
6 approved?: boolean
7 /** The user's avatar. **/
8 avatarSrc?: string
9 /** Child comments. Not populated in all scenarios. Used when asTree is set to true via the API. **/
10 children: Comment[]
11 /** The commenter's raw comment. **/
12 comment: string
13 /** READONLY: The commenter's comment parsed into HTML. **/
14 commentHTML?: string
15 /** The commenter's email. Required if anonymous commenting is off. **/
16 commenterEmail?: string
17 /** The commenter's link (for example, their blog). **/
18 commenterLink?: string
19 /** The commenter's name. Always required. If not available, set to something like "Anonymous". **/
20 commenterName: string
21 /** The date the comment was left, in UTC epoch. **/
22 date: number
23 /** The "display label" for the comment - for example "Admin", "Moderator", or something like "VIP User". **/
24 displayLabel?: string
25 /** The domain the comment was posted on. **/
26 domain?: string
27 /** READONLY: The number of times the comment was flagged. **/
28 flagCount?: number
29 /** The #hashtags written in the comment that were successfully parsed. You can also manually add hashtags, for querying, but they won't display in the comment text automatically. **/
30 hashTags?: CommentHashTag[]
31 /** READONLY: Does the comment contain images? **/
32 hasImages?: boolean
33 /** READONLY: Does the comment contain links? **/
34 hasLinks?: boolean
35 /** READONLY: The unique comment id. **/
36 id: string
37 /** Only on create! This is hashed for storage. **/
38 ip?: string
39 /** READONLY: Did the current user block the user that wrote this comment? **/
40 isBlocked?: boolean
41 /** READONLY: Is the comment by an admin? Automatically set based on userId. **/
42 isByAdmin?: boolean
43 /** READONLY: Is the comment by a moderator? Automatically set based on userId. **/
44 isByModerator?: boolean
45 /** Set to true if the comment was soft deleted (placeholder had to be left due to some other configuration). **/
46 isDeleted?: boolean
47 /** Set to true if the user's account was deleted and the comment had to be retained. **/
48 isDeletedUser?: boolean
49 /** READONLY: Is the flagged by the currently logged-in user (contextUserId)? **/
50 isFlagged?: boolean
51 /** Is the comment pinned? **/
52 isPinned?: boolean
53 /** Is the comment locked for new replies (moderators still can reply)? **/
54 isLocked?: boolean
55 /** Is the comment spam? **/
56 isSpam?: boolean
57 /** READONLY: Is the comment voted down for the current user (contextUserId)? **/
58 isVotedDown?: boolean
59 /** READONLY: Is the comment voted up for the current user (contextUserId)? **/
60 isVotedUp?: boolean
61 /** The locale the comment is in. If not provided, will be derived from the language accept HTTP header. **/
62 locale?: 'de_de' | 'en_us' | 'es_es' | 'fr_fr' | 'it_it' | 'ja_jp' | 'ko_kr' | 'pl_pl' | 'pt_br' | 'ru_ru' | 'tr_tr' | 'zh_cn' | 'zh_tw'
63 /** READONLY: The @mentions written in the comment that were successfully parsed. **/
64 mentions?: CommentUserMention[]
65 /** Optional metadata associated with the comment. **/
66 meta?: Record<string, string | number | boolean>
67 /** The optional list of moderation group ids associated with this comment. **/
68 moderationGroupIds?: string[]|null
69 /** READONLY: The id of the vote object that corresponds to the vote from the current user (contextUserId) on this comment. **/
70 myVoteId?: string
71 /** Whether notifications were sent for this comment for commenters. To prevent notifications being sent on imports, set this to true. **/
72 notificationSentForParent?: boolean
73 /** Whether notifications were sent for this comment for tenant users. To prevent notifications being sent on imports, set this to true. **/
74 notificationSentForParentTenant?: boolean
75 /** The title of the page this comment was on. **/
76 pageTitle?: string
77 /** If we're replying to a comment, this is the ID that we are replying to. **/
78 parentId?: string|null
79 /** Whether the comment is marked reviewed. **/
80 reviewed: boolean
81 /** The tenant id where the comment belongs. **/
82 tenantId: string
83 /** The user that wrote the comment. Created automatically when saving a comment with a name/email. **/
84 userId?: string|null
85 /** The URL to the location that this comment is visible, like a blog post. **/
86 url: string
87 /** A "cleaned" version of the urlId you passed us. When saving, you specify this field, but when you fetch the comment back this will be "cleaned" and your original value moved to "urlIdRaw". **/
88 urlId: string
89 /** READONLY: The original urlId you passed us. **/
90 urlIdRaw?: string
91 /** Is the user and this comment verified? **/
92 verified: boolean
93 /** Number of votes up. **/
94 votesUp?: number
95 /** Number of votes down. **/
96 votesDown?: number
97 /** The "karma" of the comment (= votes up - votes down). **/
98 votes?: number
99}
100

Някои от тези полета са маркирани като READONLY - те се връщат от API, но не могат да бъдат зададени.

Структура на текста на коментара

Коментарите се пишат във FastComments вариант на markdown, който е просто markdown плюс традиционни bbcode стилови тагове за изображения, като [img]path[/img].

Текстът се съхранява в две полета. Текстът, въведен от потребителя, се съхранява непроменен в полето comment. Той се обработва и съхранява в полето commentHTML.

Позволените HTML тагове са b, u, i, strike, pre, span, code, img, a, strong, ul, ol, li, и br.

Препоръчително е да визуализирате HTML, тъй като е много малко подмножество от HTML, изграждането на визуализатор е доста лесно. Има множество библиотеки за React Native и Flutter, например, които да помогнат с това.

Можете да изберете да визуализирате ненормализираната стойност на полето comment. Примерен парсер е тук..

Примерният парсер може също да бъде адаптиран да работи с HTML и да трансформира HTML таговете в очакваните елементи за визуализация за вашата платформа.

Отбелязване

Когато потребителите са отбелязани в коментар, информацията се съхранява в списък, наречен mentions. Всеки обект в този списък има следната структура.

Обектът Comment Mentions
Copy CopyRun External Link
1
2interface CommentUserMention {
3 /** The user id. For SSO users, this will have your tenant id prefixed. **/
4 id: string
5 /** The final @mention tag text, including the @ symbol. **/
6 tag: string
7 /** The original @mention tag text, including the @ symbol. **/
8 rawTag: string
9 /** What type of user was tagged. user = FastComments.com account. sso = SSOUser. **/
10 type: 'user'|'sso'
11 /** If the user opts out of notifications, this will still be set to true. **/
12 sent: boolean
13}
14

Хаштагове

Когато се използват хаштагове и са успешно обработени, информацията се съхранява в списък, наречен hashTags. Всеки обект в този списък има следната структура. Хаштаговете могат също да бъдат ръчно добавени към масива hashTags на коментара за заявки, ако retain е зададен.

Обектът Comment HashTag
Copy CopyRun External Link
1
2interface CommentHashTag {
3 /** The hashtag id. **/
4 id: string
5 /** The final #hashtag tag text, including the # symbol. **/
6 tag: string
7 /** If the hashtag is associated with a custom URL, this will be defined. **/
8 url?: string
9 /** If we should retain the hashtag, even if it does not exist in the comment text, when the comment is updated. Useful for tagging comments without changing comment text. **/
10 retain?: boolean
11}
12

Структура на шаблон за имейл Internal Link

Обектът EmailTemplate представлява конфигурация за персонализиран имейл шаблон за tenant.

Системата ще избере имейл шаблона за използване чрез:

  • Неговия идентификатор на типа, наречен emailTemplateId. Това са константи.
  • domain. Първо ще се опитаме да намерим шаблон за домейна, към който е свързан съответният обект (като Comment), и ако не бъде намерено съвпадение, ще се опитаме да намерим шаблон, където domain е null или *.

Структурата на обекта EmailTemplate е следната:

Структура на Email Template
Copy Copy
1
2interface EmailTemplate {
3 id: string
4 tenantId: string
5 emailTemplateId: string
6 displayName: string
7 /** READONLY **/
8 createdAt: string
9 /** READONLY **/
10 updatedAt: string
11 /** READONLY **/
12 updatedByUserId: string
13 /** The domain the template should be associated with. **/
14 domain?: string | '*' | null
15 /** The email template content in EJS syntax. **/
16 ejs: string
17 /** A map of overridden translation keys to values, for each supported locale. **/
18 translationOverridesByLocale: Record<string, Record<string, string>>
19 /** An object that represents the render context of the template. **/
20 testData: object
21}
22

Забележки

  • Можете да получите валидните стойности на emailTemplateId от крайната точка /definitions.
  • Крайната точка /definitions също включва преводите по подразбиране и тестовите данни.
  • Шаблоните няма да се запазят с невалидна структура или тестови данни.

Структура на хаштаг Internal Link

Обектът HashTag представлява таг, който може да бъде оставен от потребител. HashTags могат да се използват за свързване към външно съдържание или за свързване на свързани коментари заедно.

Структурата на обекта HashTag е следната:

Структура на HashTag
Copy Copy
1
2interface HashTag {
3 /** Should start with the "#" or desired character. **/
4 tag: string
5 /** An optional URL that the hashtag can point to. Instead of filtering comments by hashtag, the UI will redirect to this upon click. **/
6 url?: string
7 /** READONLY **/
8 createdAt: string
9}
10

Забележки:

  • В някои API крайни точки ще видите, че хаштагът се използва в URL. Не забравяйте да URI-кодирате стойностите. Например # трябва вместо това да се представи като %23.
  • Някои от тези полета са маркирани като READONLY - те се връщат от API, но не могат да бъдат зададени.

Структура на броя известия Internal Link

Обектът NotificationCount представлява броя на непрочетените известия и метаданни за потребител.

Ако няма непрочетени известия, няма да има NotificationCount за потребителя.

Обектите NotificationCount се създават автоматично и не могат да бъдат създавани чрез API. Те също изтичат след една година.

Можете да изчистите броя на непрочетените известия на потребител, като изтриете неговия NotificationCount.

Структурата на обекта NotificationCount е следната:

Структура на NotificationCount
Copy Copy
1
2interface NotificationCount {
3 id: string // user id
4 count: number
5 createdAt: string // date string
6 expireAt: string // date string
7}
8

Структура на известие Internal Link

Обектът Notification представлява известие за потребител.

Обектите Notification се създават автоматично и не могат да бъдат създавани чрез API. Те също изтичат след една година. Известията не могат да бъдат изтривани. Въпреки това те могат да бъдат актуализирани, за да зададете viewed на false, и можете да търсите по viewed.

Потребителят може също да се откаже от известия за конкретен коментар, като зададе optedOut в известието на true. Можете да се включите отново, като го зададете на false.

Има различни типове известия - проверете relatedObjectType и type.

Начините, по които се създават известия, са доста гъвкави и могат да бъдат задействани от много сценарии (вижте NotificationType).

Към днешна дата съществуването на Notification всъщност не означава, че имейл е или трябва да бъде изпратен. По-скоро известията се използват за емисия от известия и свързани интеграции.

Структурата на обекта Notification е следната:

Структура на Notification
Copy Copy
1
2enum NotificationObjectType {
3 Comment = 0,
4 Profile = 1,
5 Tenant = 2
6}
7
8enum NotificationType {
9 /** If someone replied to you. **/
10 RepliedToMe = 0,
11 /** If someone replied anywhere in a thread (even children of children) of a thread you commented on. **/
12 RepliedTransientChild = 1,
13 /** If your comment was up-voted. **/
14 VotedMyComment = 2,
15 /** If a new comment is left on the root of a page you're subscribed to. **/
16 SubscriptionReplyRoot = 3,
17 /** If someone commented on your profile. **/
18 CommentedOnProfile = 4,
19 /** If you have a DM. **/
20 DirectMessage = 5,
21 /** TrialLimits is for tenant users only. **/
22 TrialLimits = 6,
23 /** If you were @mentioned. **/
24 Mentioned = 7
25}
26
27interface Notification {
28 id: string
29 tenantId: string
30 /** With SSO, the user id is in the format `<tenant id>:<user id>`. **/
31 userId?: string
32 /** When working with SSO, you only have to worry about `userId`. **/
33 anonUserId?: string
34 /** urlId is almost always defined. It is only optional for tenant-level notifications, which are infrequent. **/
35 urlId?: string
36 /** URL is cached for quick navigation to the source of the notification. **/
37 url?: string
38 /** Page Title is cached for quick reading of notification source. **/
39 pageTitle?: string
40 relatedObjectType: NotificationObjectType
41 /** For example, comment id. **/
42 relatedObjectId: string
43 viewed: boolean
44 createdAt: string // date string
45 type: NotificationType
46 fromCommentId?: string
47 fromVoteId?: string
48 /** fromUserName and fromUserAvatarSrc are cached here for quick displaying of the notification. They are updated when the user is updated. **/
49 fromUserName: string
50 fromUserId: string
51 fromUserAvatarSrc?: string
52 /** Set this to true to stop getting notifications for this object. **/
53 optedOut?: boolean
54}
55

Структура на страница Internal Link

Обектът Page представлява страницата, към която могат да принадлежат много коментари. Тази връзка се определя от urlId.

Page съхранява информация като заглавието на страницата, броя на коментарите и urlId.

Структурата на обекта Page е следната:

Структура на Page
Copy Copy
1
2interface Page {
3 id: string
4 urlId: string
5 url: string
6 title?: string
7 createdAt: string
8 commentCount: number
9 rootCommentCount: number
10 /** Setting this to null means all SSO users can see the page. An empty list means it is closed to all users. **/
11 accessibleByGroupIds?: string[] | null
12 /** Is this page closed for new comments? **/
13 isClosed?: boolean
14}
15

Структура на чакащо уебхук събитие Internal Link

Обектът PendingWebhookEvent представлява webhook събитие в опашката, което чака обработка.

Обектите PendingWebhookEvent се създават автоматично и не могат да бъдат създадени ръчно чрез API. Те също изтичат след една година. Могат да бъдат изтрити, което премахва задачата от опашката.

Има различни типове събития - проверете eventType (OutboundSyncEventType) и type (OutboundSyncType).

Често срещан случай на употреба за този API е внедряването на персонализиран мониторинг. Може да искате да извикате крайната точка /count периодично, за да проверявате броя на чакащите събития за дадени филтри.

Структурата на обекта PendingWebhookEvent е следната:

Структура на PendingWebhookEvent
Copy Copy
1
2enum OutboundSyncEventType {
3 Create: 0,
4 Delete: 1,
5 Update: 2
6}
7
8enum OutboundSyncType {
9 /** WordPress-specific sync task. **/
10 WP: 0,
11 Webhook: 1
12}
13
14interface PendingWebhookEvent {
15 id: string
16 /** The comment id associated with the event. **/
17 commentId: string
18 /** The comment object for the event at the time of the event. We started adding these in Nov 2023. **/
19 comment: Comment
20 /** An external id that may be associated with the comment. **/
21 externalId: string | null
22 createdAt: Date
23 tenantId: string
24 attemptCount: number
25 /** Set before first attempt, and after every failure. **/
26 nextAttemptAt: Date
27 /** Whether this is a creation, deletion, or update event... **/
28 eventType: OutboundSyncEventType
29 /** The type of sync to perform (WordPress, call API, etc). **/
30 type: OutboundSyncType
31 /** The domain that matched the comment. We use this domain to pick the API key. **/
32 domain: string
33 /** The last error that occurred. This type is untyped and is a "dump" of whatever happened. Usually it contains an object with statusCode, body, and a headers map. **/
34 lastError: object | null
35}
36

Структура на SSO потребител Internal Link

FastComments предоставя лесно за използване SSO решение. Актуализирането на информацията на потребител с интеграцията, базирана на HMAC, е толкова просто, колкото потребителят да зареди страницата с актуализиран payload.

Въпреки това може да е желателно да управлявате потребител извън този поток, за да подобрите последователността на вашето приложение.

API за SSO потребители предоставя начин за CRUD на обекти, които наричаме SSOUsers. Тези обекти са различни от обикновените Users и се съхраняват отделно за безопасност на типовете.

Структурата на обекта SSOUser е следната:

Структура на SSOUser
Copy Copy
1
2interface SSOUser {
3 id: string
4 username: string
5 email?: string
6 websiteUrl?: string
7 signUpDate: number
8 createdFromUrlId?: string
9 loginCount?: number
10 avatarSrc?: string
11 optedInNotifications?: boolean
12 optedInSubscriptionNotifications?: boolean
13 displayLabel?: string
14 displayName?: string
15 isAccountOwner?: boolean // Admin permission - SSO users with this flag are billed as SSO Admins (separate from regular SSO users)
16 isAdminAdmin?: boolean // Admin permission - SSO users with this flag are billed as SSO Admins (separate from regular SSO users)
17 isCommentModeratorAdmin?: boolean // Moderator permission - SSO users with this flag are billed as SSO Moderators (separate from regular SSO users)
18 /** If null, Access Control will not be applied to the user. If an empty list, this user will not be able to see any pages or @mention other users. **/
19 groupIds?: string[] | null
20 createdFromSimpleSSO?: boolean
21 /** Don't let other users see this user's activity, including comments, on their profile. Default is true to provide secure profiles by default. **/
22 isProfileActivityPrivate?: boolean
23 /** Don't let other users leave comments on the user's profile, or see existing profile comments. Default false. **/
24 isProfileCommentsPrivate?: boolean
25 /** Don't let other users send direct messages to this user. Default false. **/
26 isProfileDMDisabled?: boolean
27 karma?: number
28 /** Optional configuration for user badges. **/
29 badgeConfig?: {
30 /** Array of badge IDs to assign to the user. Limited to 30 badges. Order is respected. **/
31 badgeIds: string[]
32 /** If true, replaces all existing displayed badges with the provided ones. If false, adds to existing badges. **/
33 override?: boolean
34 /** If true, updates badge display properties from tenant configuration. **/
35 update?: boolean
36 }
37}
38

Фактуриране за SSO потребители

SSO потребителите се таксуват различно въз основа на техните флагове за права:

  • Обикновени SSO потребители: Потребители без администраторски или модераторски права се таксуват като обикновени SSO потребители
  • SSO администратори: Потребители с флагове isAccountOwner или isAdminAdmin се таксуват отделно като SSO администратори (същата ставка като обикновените tenant администратори)
  • SSO модератори: Потребители с флаг isCommentModeratorAdmin се таксуват отделно като SSO модератори (същата ставка като обикновените модератори)

Важно: За да се предотврати двойно таксуване, системата автоматично дедублира SSO потребители спрямо обикновени tenant потребители и модератори по имейл адрес. Ако SSO потребител има същия имейл като обикновен tenant потребител или модератор, той няма да бъде таксуван два пъти.

Контрол на достъпа

Потребителите могат да бъдат разделени на групи. За това служи полето groupIds и е незадължително.

@Споменавания

По подразбиране @споменаванията ще използват username за търсене на други sso потребители, когато се въведе символът @. Ако се използва displayName, тогава резултатите, съвпадащи с username, ще бъдат игнорирани, когато има съвпадение за displayName, и резултатите от търсенето на @споменаване ще използват displayName.

Абонаменти

С FastComments потребителите могат да се абонират за страница, като щракнат върху иконата на камбанката в уиджета за коментари и щракнат върху Абониране.

При обикновен потребител изпращаме имейли за известия въз основа на техните настройки за известия.

При SSO потребители разделяме това за обратна съвместимост. Потребителите ще получават тези допълнителни имейли за известия за абонамент само ако зададете optedInSubscriptionNotifications на true.

Значки

Можете да присвоявате значки на SSO потребители, като използвате свойството badgeConfig. Значките са визуални индикатори, които се появяват до името на потребителя в коментарите.

  • badgeIds - Масив от ID на значки за присвояване на потребителя. Те трябва да бъдат валидни ID на значки, създадени във вашия акаунт в FastComments. Ограничено до 30 значки.
  • override - Ако е true, всички съществуващи значки, показвани в коментарите, ще бъдат заменени с предоставените. Ако е false или е пропуснато, предоставените значки ще бъдат добавени към съществуващите значки.
  • update - Ако е true, свойствата за показване на значки ще бъдат актуализирани от конфигурацията на tenant всеки път, когато потребителят влезе.

Структура на абонамент Internal Link

Обектът Subscription представлява абонамент за потребител.

Обектите Subscription се създават, когато потребител кликне върху камбанката за известия в уиджета за коментари и щракне върху "Абониране за тази страница".

Абонаментите могат да бъдат създадени и чрез API.

Наличието на обект Subscription причинява генерирането на обекти Notification и изпращането на имейли, когато нови коментари са оставени в корена на асоциираната страница, за която е Subscription. Изпращането на имейли зависи от типа потребител. За обикновени потребители това зависи от optedInNotifications. За SSO потребители това зависи от optedInSubscriptionNotifications. Обърнете внимание, че някои приложения може да нямат концепцията за уеб достъпна страница, в този случай просто задайте urlId на id на елемента, за който се абонирате (същата стойност за urlId, която бихте подали на уиджета за коментари).

Структурата на обекта Subscription е следната:

Структура на Subscription
Copy Copy
1
2interface Subscription {
3 id: string
4 tenantId: string
5 /** With SSO, the user id is in the format `<tenant id>:<user id>`. **/
6 userId: string
7 anonUserId?: string
8 urlId: string
9 url?: string
10 pageTitle?: string
11 createdAt: string // date string
12}
13

Структура на дневната употреба на тенанта Internal Link

Обектът TenantDailyUsage представлява използването за tenant за даден ден. Ако няма активност за даден tenant за даден ден, този ден няма да има обект TenantDailyUsage.

Обектът TenantDailyUsage не е в реално време и може да е с минути назад от действителното използване.

Структурата на обекта TenantDailyUsage е следната:

Структура на TenantDailyUsage
Copy Copy
1
2export interface TenantDailyUsage {
3 yearNumber: number
4 monthNumber: number
5 dayNumber: number
6 commentFetchCount?: number
7 commentCreateCount?: number
8 conversationCreateCount?: number
9 voteCount?: number
10 accountCreatedCount?: number
11 userMentionSearch?: number
12 hashTagSearch?: number
13 gifSearchTrending?: number
14 gifSearch?: number
15 apiCreditsUsed?: number
16 createdAt: string
17 billed: boolean
18 /** Ignored for billing. **/
19 ignored: boolean
20}
21

Структура на тенант Internal Link

Tenant дефинира клиент на FastComments.com. Те могат да бъдат създадени чрез API от tenant-и с достъп до white labeling. White labeled tenant-и не могат да създават други white labeled tenant-и (позволено е само едно ниво на влагане).

Структурата на обекта Tenant е следната:

Структура на Tenant
Copy Copy
1
2export enum SiteType {
3 Unknown = 0,
4 WordPress = 1
5}
6
7/** This can also be handled via the DomainConfig API. **/
8export interface TenantDomainConfig {
9 domain: string
10 emailFromName?: string
11 emailFromEmail?: string
12 createdAt?: string,
13 siteType?: FastCommentsSiteType, // you probably want Unknown
14 logoSrc?: string, // raw image path
15 logoSrc100px?: string, // resized for thumbnails
16 footerUnsubscribeURL?: string,
17 emailHeaders?: Record<string, string>,
18 disableUnsubscribeLinks?: boolean,
19 dkim?: {
20 domainName: string,
21 keySelector: string,
22 privateKey: string
23 }
24}
25
26export interface TenantBillingInfo {
27 name: string
28 address: string
29 city: string
30 state: string
31 zip: string
32 country: string
33}
34
35export enum TenantPaymentFrequency {
36 Monthly = 0,
37 Annually = 1
38}
39
40export interface Tenant {
41 id: string
42 name: string
43 email?: string
44 signUpDate: number; // number due to "legacy" reasons
45 packageId?: string | null
46 paymentFrequency?: TenantPaymentFrequency
47 billingInfoValid?: boolean
48 billingHandledExternally?: boolean
49 createdBy?: string
50 isSetup?: boolean
51 domainConfiguration: FastCommentsAPITenantDomainConfig[]
52 billingInfo?: FastCommentsAPITenantBillingInfo
53 stripeCustomerId?: string
54 stripeSubscriptionId?: string
55 stripePlanId?: string
56 enableProfanityFilter?: boolean
57 enableSpamFilter?: boolean
58 lastBillingIssueReminderDate?: string
59 removeUnverifiedComments?: boolean
60 unverifiedCommentsTTLms?: number
61 commentsRequireApproval?: boolean
62 autoApproveCommentOnVerification?: boolean
63 sendProfaneToSpam?: boolean
64 /** @readonly - Is calculated based on packageId. **/
65 hasFlexPricing?: boolean
66 /** @readonly **/
67 flexLastBilledAmount?: number
68 /** @readonly - Is calculated based on packageId. **/
69 hasAuditing?: boolean
70 /** You can store a key value pair with the tenant which you can use to query. Keys cannot contain "." or "$", or be longer than 100 chars. Values may not be longer than 2k chars. **/
71 meta?: Record<string, string | null>
72}
73

Структура на потребителя Internal Link

User е обект, който представлява най-общ знаменател на всички потребители.

Имайте предвид, че във FastComments имаме множество различни случаи на употреба за потребители:

  • Сигурно SSO
  • Просто SSO
  • Tenant потребители (Например: Администратори)
  • Коментатори

Този API е за Коментатори и потребители, създадени чрез Просто SSO. По същество всеки потребител, създаден чрез вашия сайт, може да бъде достъпен чрез този API. Tenant потребители също могат да бъдат извлечени по този начин, но ще получите повече информация, като взаимодействате с API /tenant-users/.

За Сигурно SSO моля използвайте API /sso-users/.

Не можете да актуализирате тези типове потребители. Те са създали акаунта си чрез вашия сайт, така че предоставяме някакъв базов достъп само за четене, но не можете да правите промени. Ако искате да имате такъв тип поток - трябва да настроите Сигурно SSO.

Структурата на обекта User е следната:

Структура на User
Copy Copy
1
2export interface User {
3 /** This is also the id used as userId on comment objects. **/
4 id: string
5 username: string
6 /** A link to the commenter's blog, for example. **/
7 websiteUrl?: string
8 email: string
9 signUpDate: number
10 createdFromUrlId: string
11 createdFromTenantId: string
12 avatarSrc?: string
13 locale: FastCommentsLocale
14 displayLabel?: string
15 karma?: number
16}
17

Структура на глас Internal Link

Обектът Vote представлява глас, оставен от потребител.

Връзката между коментари и глас се дефинира чрез commentId.

Структурата на обекта Vote е следната:

Структура на Vote
Copy Copy
1
2interface Vote {
3 id: string
4 urlId: string
5 commentId: string
6 userId: string
7 direction: 1 | -1
8 createdAt: string
9}
10

Структура на конфигурация на въпрос Internal Link

FastComments предоставя начин за конструиране на въпроси и агрегиране на техните резултати. Пример за въпрос (наричан по-нататък QuestionConfig) може да бъде звездна оценка, плъзгач или NPS въпрос (определен чрез type).

Данните от въпросите могат да бъдат агрегирани индивидуално, заедно, във времето, общо, по страница и така нататък.

Рамката има всички възможности, необходими за изграждане на уиджети от клиентска страна (с вашия сървър пред този API), административни табла и инструменти за отчетност.

Първо трябва да дефинираме QuestionConfig. Структурата е следната:

Структура на QuestionConfig
Copy Copy
1
2type QuestionConfigType = 'nps' | 'slider' | 'star' | 'thumbs';
3
4interface QuestionConfig {
5 id: string
6 tenantId: string
7 name: string
8 question: string
9 helpText?: string
10 createdAt: string
11 createdBy: string
12 /** READONLY - incremented for each new response. **/
13 usedCount: number
14 /** A date string for when the configuration was last used (result left). **/
15 lastUsed?: string
16 type: QuestionConfigType
17 numStars?: number
18 min?: number
19 max?: number
20 defaultValue?: number
21 labelNegative?: string
22 labelPositive?: string
23 subQuestionIds?: string[]
24 alwaysShowSubQuestions?: boolean
25 reportingOrder: number
26}
27

Структура на резултат от въпрос Internal Link

За да запазите резултати от въпроси, създавате QuestionResult. След това можете да агрегирате резултатите от въпросите и също да ги свържете с коментари за целите на отчетността.

Структура на QuestionResult
Copy Copy
1
2interface QuestionResultMeta {
3 name: string
4 values: string[]
5}
6
7interface QuestionResult {
8 id: string
9 tenantId: string
10 urlId: string
11 anonUserId?: string
12 userId?: string
13 createdAt?: string
14 value: number
15 commentId?: string
16 questionId: string
17 meta?: QuestionResultMeta[]
18}
19

Структура на потребителска значка Internal Link

UserBadge е обект, който представлява значка, присвоена на потребител в системата FastComments.

Значки могат да бъдат присвоявани на потребители автоматично въз основа на тяхната активност (като брой коментари, време за отговор, ветерански статус) или ръчно от администраторите на сайта.

Структурата на обекта UserBadge е следната:

Структура на UserBadge
Copy Copy
1
2export interface UserBadge {
3 /** Unique identifier for this user badge assignment */
4 id: string
5 /** ID of the user this badge is assigned to */
6 userId: string
7 /** ID of the badge definition from the tenant's badge catalog */
8 badgeId: string
9 /** ID of the tenant that created/assigned this badge */
10 fromTenantId: string
11 /** When this badge was created (milliseconds since epoch) */
12 createdAt?: number
13 /** When this badge was received by the user (milliseconds since epoch) */
14 receivedAt?: number
15 /**
16 * The badge type:
17 * 0=CommentCount, 1=CommentUpVotes, 2=CommentReplies, 3=CommentsPinned,
18 * 4=Veteran, 5=NightOwl, 6=FastReplyTime, 7=ModeratorCommentsDeleted,
19 * 8=ModeratorCommentsApproved, 9=ModeratorCommentsUnapproved, 10=ModeratorCommentsReviewed,
20 * 11=ModeratorCommentsMarkedSpam, 12=ModeratorCommentsMarkedNotSpam, 13=RepliedToSpecificPage,
21 * 14=Manual
22 */
23 type: number
24 /** For threshold-based badges, the threshold value */
25 threshold?: number
26 /** The name/label of the badge */
27 name?: string
28 /** Detailed description of the badge */
29 description?: string
30 /** The text shown on the badge */
31 displayLabel?: string
32 /** URL to an image shown on the badge */
33 displaySrc?: string
34 /** Background color for the badge (hex code) */
35 backgroundColor?: string
36 /** Border color for the badge (hex code) */
37 borderColor?: string
38 /** Text color for the badge (hex code) */
39 textColor?: string
40 /** Additional CSS class for styling */
41 cssClass?: string
42 /** For veteran badges, the time threshold in milliseconds */
43 veteranUserThresholdMillis?: number
44 /** Whether this badge is displayed on the user's comments */
45 displayedOnComments: boolean
46 /** The display order of the badge */
47 order?: number
48}
49

Структура на напредъка на потребителска значка Internal Link

UserBadgeProgress е обект, който представлява напредъка на потребител към спечелване на различни значки в системата FastComments.

Това проследяване помага да се определи кога потребителите трябва да получат автоматични значки въз основа на тяхната активност и участие във вашата общност.

Структурата на обекта UserBadgeProgress е следната:

Структура на UserBadgeProgress
Copy Copy
1
2export interface UserBadgeProgress {
3 /** Unique identifier for this progress record */
4 id: string
5 /** ID of the tenant this progress record belongs to */
6 tenantId: string
7 /** ID of the user this progress record tracks */
8 userId: string
9 /** ID of the user's first comment in the system */
10 firstCommentId?: string
11 /** Date of the user's first comment (milliseconds since epoch) */
12 firstCommentDate?: number
13 /** Automatically calculated trust factor based on user activity */
14 autoTrustFactor?: number
15 /** Manually set trust factor by administrators */
16 manualTrustFactor?: number
17 /** Detailed progress object with various metrics, keys match BadgeType enum */
18 progress: {
19 /** 0: CommentCount - Count of comments the user has made */
20 '0'?: number
21 /** 1: CommentUpVotes - Count of upvotes the user has received */
22 '1'?: number
23 /** 2: CommentReplies - Count of replies the user has made */
24 '2'?: number
25 /** 3: CommentsPinned - Count of pinned comments the user has */
26 '3'?: number
27 /** 4: Veteran - User's account age */
28 '4'?: number
29 /** 5: NightOwl - Times user has posted during nighttime hours */
30 '5'?: number
31 /** 6: FastReplyTime - Average reply time in milliseconds */
32 '6'?: number
33 /** 7: ModeratorCommentsDeleted - For moderator badges, comments deleted count */
34 '7'?: number
35 /** 8: ModeratorCommentsApproved - For moderator badges, comments approved count */
36 '8'?: number
37 /** 9: ModeratorCommentsUnapproved - For moderator badges, comments unapproved count */
38 '9'?: number
39 /** 10: ModeratorCommentsReviewed - For moderator badges, comments reviewed count */
40 '10'?: number
41 /** 11: ModeratorCommentsMarkedSpam - For moderator badges, comments marked as spam count */
42 '11'?: number
43 /** 12: ModeratorCommentsMarkedNotSpam - For moderator badges, comments marked as not spam count */
44 '12'?: number
45 /** 13: RepliedToSpecificPage - For each page, count of replies */
46 '13'?: Record<string, number>
47 }
48}
49

В заключение

Надяваме се, че нашата API документация е била изчерпателна и лесна за разбиране. Ако откриете пропуски, уведомете ни по-долу.