@andrey4emk/npm-app-back-b24 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bitrix24/b24.js CHANGED
@@ -16,7 +16,7 @@ const APP_NAME = process.env.APP_NAME;
16
16
  async function makeAuthParams(AuthB24Model) {
17
17
  let authSql = await AuthB24Model.findOne({
18
18
  where: {
19
- domain: APP_B24_DOMEN,
19
+ name: `${APP_B24_DOMEN}_${APP_ENV}`,
20
20
  },
21
21
  raw: true,
22
22
  });
@@ -87,6 +87,7 @@ export async function save(req, res, AuthB24Model) {
87
87
  domain: domain,
88
88
  expires_in: expires_in,
89
89
  member_id: member_id,
90
+ name: `${domain}_${APP_ENV}`,
90
91
  });
91
92
  res.status(201).json({ status: "ok", message: "Сохранили токены" });
92
93
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrey4emk/npm-app-back-b24",
3
- "version": "0.4.4",
3
+ "version": "0.5.0",
4
4
  "description": "Bitrix24 OAuth helpers for Node.js projects",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -24,8 +24,7 @@
24
24
  "bitrix24/b24.js",
25
25
  "bitrix24/eventGet.js",
26
26
  "sendMessage/chatApp.js",
27
- "sendMessage/smsgold.js",
28
- "config.js"
27
+ "sendMessage/smsgold.js"
29
28
  ],
30
29
  "dependencies": {
31
30
  "@bitrix24/b24jssdk": "^0.5.1",
@@ -1,19 +1,130 @@
1
- import { config } from "../config.js";
2
1
  import dotEnv from "dotenv";
3
-
4
2
  dotEnv.config();
5
3
 
6
- class ChatApp {
7
- constructor() {
8
- this.accessToken = null;
9
- this.accessTokenEndTime = null;
10
- this.refreshToken = null;
11
- this.refreshTokenEndTime = null;
4
+ const APP_ENV = process.env.APP_ENV;
5
+ const CHATAPP_EMAIL = process.env.CHATAPP_EMAIL;
6
+ const CHATAPP_APP_ID = process.env.CHATAPP_APP_ID;
7
+
8
+ export class ChatApp {
9
+ constructor(makeParam, authParam, typeParam) {
10
+ /**
11
+ * @param {Object} makeParam - объект с параметрами для создания токена
12
+ * @param {string} makeParam.email - email для создания токена
13
+ * @param {string} makeParam.pass - пароль для создания токена
14
+ * @param {string} makeParam.appId - appId для создания токена
15
+ *
16
+ * @param {Object} authParam - объект с параметрами авторизации
17
+ * @param {string} authParam.accessToken - accessToken для авторизации
18
+ * @param {string} authParam.accessTokenEndTime - время окончания действия accessToken
19
+ * @param {string} authParam.refreshToken - refreshToken для обновления accessToken
20
+ * @param {string} authParam.refreshTokenEndTime - время окончания действия refreshToken
21
+ *
22
+ * @param {Object} typeParam - объект с типами мессенджеров и их параметрами
23
+ * @param {Object} typeParam.whatsApp - параметры для WhatsApp
24
+ * @param {string} typeParam.whatsApp.licenseId - ID лицензии для WhatsApp
25
+ * @param {Array} typeParam.whatsApp.messenger - массив с типами мессенджеров для WhatsApp
26
+ *
27
+ * @param {Object} typeParam.telegram - параметры для Telegram
28
+ * @param {string} typeParam.telegram.licenseId - ID лицензии для Telegram
29
+ * @param {Array} typeParam.telegram.messenger - массив с типами мессенджеров для Telegram
30
+ */
31
+
32
+ this.make = makeParam;
33
+ this.auth = authParam;
34
+ this.type = typeParam;
35
+ this.updateToken = false;
12
36
  }
13
37
 
14
- async makeTokenChatApp() {
38
+ async sendMessageChatApp(messangerType, messageData) {
39
+ // Проверяем что верно указан messangerType и в messageData есть phone и message
40
+ if (!["whatsApp"].includes(messangerType) && !["telegram"].includes(messangerType)) {
41
+ return { error: true, message: "Неверный тип мессенджера", data: null };
42
+ }
43
+ if (!messageData.phone || !messageData.message) {
44
+ return { error: true, message: "Отсутствует phone или message", data: null };
45
+ }
46
+ let check = await this.checkTokenChatApp();
47
+ if (check.error) {
48
+ return { error: true, message: `Ошибка с токеном ChatApp в функции sendMessageChatApp класса ChatApp\n${check.message}`, data: null };
49
+ }
50
+ let phone = messageData.phone;
51
+ let message = messageData.message;
52
+ let url;
53
+ if (messangerType === "whatsApp") {
54
+ url = `https://api.chatapp.online/v1/licenses/${this.type.whatsApp.licenseId}/messengers/${this.type.whatsApp.messenger[0].type}/chats/${phone}/messages/text`;
55
+ }
56
+ if (messangerType === "telegram") {
57
+ url = `https://api.chatapp.online/v1/licenses/${this.type.telegram.licenseId}/messengers/${this.type.telegram.messenger[0].type}/chats/${phone}/messages/text`;
58
+ }
59
+ let res = await fetch(url, {
60
+ method: "POST",
61
+ headers: {
62
+ Lang: "en",
63
+ "Content-Type": "application/json",
64
+ Accept: "application/json",
65
+ Authorization: this.auth.accessToken,
66
+ },
67
+ body: JSON.stringify({
68
+ text: message,
69
+ }),
70
+ });
71
+ let data = await res.json();
72
+
73
+ if (!data.success) {
74
+ return { error: true, message: `Ошибка при отправке сообщения в ChatApp через ${messangerType}`, data: data };
75
+ } else {
76
+ // Если в процессе запроса обновили токен, то возвращаем информацию об этом.
77
+ let newAuth = null;
78
+ if (this.updateToken) {
79
+ newAuth = this.auth;
80
+ // Сбрасываем флаг обновления токена
81
+ this.updateToken = false;
82
+ }
83
+ return { error: false, message: `Сообщение успешно отправлено в ChatApp через ${messangerType}`, data: data, auth: newAuth };
84
+ }
85
+ }
86
+
87
+ async phoneCheckChatApp(messangerType, phone) {
88
+ if (!["whatsApp"].includes(messangerType) && !["telegram"].includes(messangerType)) {
89
+ return { error: true, message: "Неверный тип мессенджера", data: null };
90
+ }
91
+ let check = await this.checkTokenChatApp();
92
+ if (check.error) {
93
+ return { error: true, message: `Ошибка с токеном ChatApp в функции phoneCheckChatApp класса ChatApp\n${check.message}`, data: check };
94
+ }
95
+ let url;
96
+ if (messangerType === "whatsApp") {
97
+ url = `https://api.chatapp.online/v1/licenses/${this.type.whatsApp.licenseId}/messengers/${this.type.whatsApp.messenger[0].type}/phones/${phone}/check`;
98
+ }
99
+ if (messangerType === "telegram") {
100
+ url = `https://api.chatapp.online/v1/licenses/${this.type.telegram.licenseId}/messengers/${this.type.telegram.messenger[0].type}/phones/${phone}/check`;
101
+ }
102
+ let res = await fetch(url, {
103
+ method: "GET",
104
+ headers: {
105
+ Lang: "en",
106
+ Accept: "application/json",
107
+ Authorization: this.auth.accessToken,
108
+ },
109
+ });
110
+ let data = await res.json();
111
+ if (!data.success) {
112
+ return { error: true, message: `Ошибка при проверке телефона в ChatApp через ${messangerType}`, data: data };
113
+ } else {
114
+ // Если в процессе запроса обновили токен, то возвращаем информацию об этом.
115
+ let newAuth = null;
116
+ if (this.updateToken) {
117
+ newAuth = this.auth;
118
+ // Сбрасываем флаг обновления токена
119
+ this.updateToken = false;
120
+ }
121
+ return { error: false, message: `Телефон успешно проверен в ChatApp через ${messangerType}`, data: data, auth: newAuth };
122
+ }
123
+ }
124
+
125
+ async checkTokenChatApp() {
15
126
  try {
16
- const response = await fetch("https://api.chatapp.online/v1/tokens", {
127
+ const response = await fetch("https://api.chatapp.online/v1/tokens/check", {
17
128
  method: "POST",
18
129
  headers: {
19
130
  Lang: "en",
@@ -21,30 +132,25 @@ class ChatApp {
21
132
  Accept: "application/json",
22
133
  },
23
134
  body: JSON.stringify({
24
- email: process.env.CHATAPP_EMAIL,
25
- password: process.env.CHATAPP_PASS,
26
- appId: process.env.CHATAPP_APP_ID,
135
+ accessToken: this.auth.accessToken,
27
136
  }),
28
137
  });
29
138
 
30
139
  const data = await response.json();
31
140
  if (!data.success) {
32
- return { error: true, message: "Не удалось получить токен ChatApp", data: data };
141
+ await this.refreshTokenChatApp();
142
+ return { error: false, message: "Токен обновлен" };
33
143
  } else {
34
- this.accessToken = data.data.accessToken;
35
- this.accessTokenEndTime = data.data.accessTokenEndTime;
36
- this.refreshToken = data.data.refreshToken;
37
- this.refreshTokenEndTime = data.data.refreshTokenEndTime;
38
- return { error: false };
144
+ return { error: false, message: "Токен действителен" };
39
145
  }
40
146
  } catch (error) {
41
147
  return { error: true, message: error.message, data: null };
42
148
  }
43
149
  }
44
150
 
45
- async refreshTokenChatApp() {
151
+ async makeTokenChatApp() {
46
152
  try {
47
- const response = await fetch("https://api.chatapp.online/v1/tokens/refresh", {
153
+ const response = await fetch("https://api.chatapp.online/v1/tokens", {
48
154
  method: "POST",
49
155
  headers: {
50
156
  Lang: "en",
@@ -52,24 +158,21 @@ class ChatApp {
52
158
  Accept: "application/json",
53
159
  },
54
160
  body: JSON.stringify({
55
- refreshToken: this.refreshToken,
161
+ email: this.make.email,
162
+ password: this.make.pass,
163
+ appId: this.make.appId,
56
164
  }),
57
165
  });
58
- const data = await response.json();
59
166
 
167
+ const data = await response.json();
60
168
  if (!data.success) {
61
- let resMakeToken = await this.makeTokenChatApp();
62
-
63
- if (resMakeToken.error) {
64
- return { error: true, message: "Не удалось обновить токен ChatApp", data: data };
65
- } else {
66
- return { error: false };
67
- }
169
+ return { error: true, message: "Не удалось получить токен ChatApp", data: data };
68
170
  } else {
69
- this.accessToken = data.accessToken;
70
- this.accessTokenEndTime = data.accessTokenEndTime;
71
- this.refreshToken = data.refreshToken;
72
- this.refreshTokenEndTime = data.refreshTokenEndTime;
171
+ this.auth.accessToken = data.data.accessToken;
172
+ this.auth.accessTokenEndTime = data.data.accessTokenEndTime;
173
+ this.auth.refreshToken = data.data.refreshToken;
174
+ this.auth.refreshTokenEndTime = data.data.refreshTokenEndTime;
175
+ this.updateToken = true;
73
176
  return { error: false };
74
177
  }
75
178
  } catch (error) {
@@ -77,9 +180,9 @@ class ChatApp {
77
180
  }
78
181
  }
79
182
 
80
- async checkTokenChatApp() {
183
+ async refreshTokenChatApp() {
81
184
  try {
82
- const response = await fetch("https://api.chatapp.online/v1/tokens/check", {
185
+ const response = await fetch("https://api.chatapp.online/v1/tokens/refresh", {
83
186
  method: "POST",
84
187
  headers: {
85
188
  Lang: "en",
@@ -87,16 +190,26 @@ class ChatApp {
87
190
  Accept: "application/json",
88
191
  },
89
192
  body: JSON.stringify({
90
- accessToken: this.accessToken,
193
+ refreshToken: this.auth.refreshToken,
91
194
  }),
92
195
  });
93
-
94
196
  const data = await response.json();
197
+
95
198
  if (!data.success) {
96
- await this.refreshTokenChatApp();
97
- return { error: false, message: "Токен обновлен" };
199
+ let resMakeToken = await this.makeTokenChatApp();
200
+
201
+ if (resMakeToken.error) {
202
+ return { error: true, message: "Не удалось обновить токен ChatApp", data: data };
203
+ } else {
204
+ return { error: false };
205
+ }
98
206
  } else {
99
- return { error: false, message: "Токен действителен" };
207
+ this.auth.accessToken = data.accessToken;
208
+ this.auth.accessTokenEndTime = data.accessTokenEndTime;
209
+ this.auth.refreshToken = data.refreshToken;
210
+ this.auth.refreshTokenEndTime = data.refreshTokenEndTime;
211
+ this.updateToken = true;
212
+ return { error: false };
100
213
  }
101
214
  } catch (error) {
102
215
  return { error: true, message: error.message, data: null };
@@ -110,7 +223,7 @@ class ChatApp {
110
223
  headers: {
111
224
  Lang: "en",
112
225
  Accept: "application/json",
113
- Authorization: this.accessToken,
226
+ Authorization: this.auth.accessToken,
114
227
  },
115
228
  });
116
229
  const data = await response.json();
@@ -124,78 +237,4 @@ class ChatApp {
124
237
  return { error: true, message: error.message, data: null };
125
238
  }
126
239
  }
127
-
128
- async sendMessageChatApp(messangerType, messageData) {
129
- // Проверяем что верно указан messangerType и в messageData есть phone и message
130
- if (!["whatsApp"].includes(messangerType) && !["telegram"].includes(messangerType)) {
131
- return { error: true, message: "Неверный тип мессенджера", data: null };
132
- }
133
- if (!messageData.phone || !messageData.message) {
134
- return { error: true, message: "Отсутствует phone или message", data: null };
135
- }
136
- let check = await this.checkTokenChatApp();
137
- if (check.error) {
138
- return { error: true, message: `Ошибка с токеном ChatApp в функции sendMessageChatApp класса ChatApp\n${check.message}`, data: null };
139
- }
140
- let phone = messageData.phone;
141
- let message = messageData.message;
142
- let url;
143
- if (messangerType === "whatsApp") {
144
- url = `https://api.chatapp.online/v1/licenses/${config.chatApp.type.whatsApp.licenseId}/messengers/${config.chatApp.type.whatsApp.messenger[0].type}/chats/${phone}/messages/text`;
145
- }
146
- if (messangerType === "telegram") {
147
- url = `https://api.chatapp.online/v1/licenses/${config.chatApp.type.telegram.licenseId}/messengers/${config.chatApp.type.telegram.messenger[0].type}/chats/${phone}/messages/text`;
148
- }
149
- let res = await fetch(url, {
150
- method: "POST",
151
- headers: {
152
- Lang: "en",
153
- "Content-Type": "application/json",
154
- Accept: "application/json",
155
- Authorization: this.accessToken,
156
- },
157
- body: JSON.stringify({
158
- text: message,
159
- }),
160
- });
161
- let data = await res.json();
162
- if (!data.success) {
163
- return { error: true, message: `Ошибка при отправке сообщения в ChatApp через ${messangerType}`, data: data };
164
- } else {
165
- return { error: false, message: `Сообщение успешно отправлено в ChatApp через ${messangerType}`, data: data };
166
- }
167
- }
168
-
169
- async phoneCheckChatApp(messangerType, phone) {
170
- if (!["whatsApp"].includes(messangerType) && !["telegram"].includes(messangerType)) {
171
- return { error: true, message: "Неверный тип мессенджера", data: null };
172
- }
173
- let check = await this.checkTokenChatApp();
174
- if (check.error) {
175
- return { error: true, message: `Ошибка с токеном ChatApp в функции phoneCheckChatApp класса ChatApp\n${check.message}`, data: check };
176
- }
177
- let url;
178
- if (messangerType === "whatsApp") {
179
- url = `https://api.chatapp.online/v1/licenses/${config.chatApp.type.whatsApp.licenseId}/messengers/${config.chatApp.type.whatsApp.messenger[0].type}/chats/${phone}/check`;
180
- }
181
- if (messangerType === "telegram") {
182
- url = `https://api.chatapp.online/v1/licenses/${config.chatApp.type.telegram.licenseId}/messengers/${config.chatApp.type.telegram.messenger[0].type}/chats/${phone}/check`;
183
- }
184
- let res = await fetch(url, {
185
- method: "GET",
186
- headers: {
187
- Lang: "en",
188
- Accept: "application/json",
189
- Authorization: this.accessToken,
190
- },
191
- });
192
- let data = await res.json();
193
- if (!data.success) {
194
- return { error: true, message: `Ошибка при проверке телефона в ChatApp через ${messangerType}`, data: data };
195
- } else {
196
- return { error: false, message: `Телефон успешно проверен в ChatApp через ${messangerType}`, data: data };
197
- }
198
- }
199
240
  }
200
-
201
- export const chatApp = new ChatApp();
package/config.js DELETED
@@ -1,19 +0,0 @@
1
- export const config = {
2
- chatApp: {
3
- // Получаем из класса ChatApp().getLicensesChatApp и статично сохраняем в конфиге тут
4
- type: {
5
- whatsApp: {
6
- licenseId: 15779,
7
- licenseTo: 1765027066,
8
- licenseName: "*5787",
9
- messenger: [{ type: "grWhatsApp", name: "[WEB] WhatsApp" }],
10
- },
11
- telegram: {
12
- licenseId: 17530,
13
- licenseTo: 1765552526,
14
- licenseName: "*6980 telegram",
15
- messenger: [{ type: "telegram", name: "Telegram Personal" }],
16
- },
17
- },
18
- },
19
- };