@green-api/greenapi-integration 0.1.0 → 0.3.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/README.md +120 -59
- package/README.ru.md +118 -39
- package/dist/core/base-adapter.d.ts +151 -10
- package/dist/core/base-adapter.js +127 -11
- package/dist/core/errors.d.ts +75 -0
- package/dist/core/errors.js +75 -0
- package/dist/core/green-api.client.d.ts +188 -0
- package/dist/core/green-api.client.js +189 -1
- package/dist/core/guard.d.ts +45 -0
- package/dist/core/guard.js +45 -0
- package/dist/core/message-transformer.d.ts +46 -2
- package/dist/core/message-transformer.js +28 -0
- package/dist/core/storage-provider.d.ts +62 -3
- package/dist/core/storage-provider.js +21 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/types/types.d.ts +212 -66
- package/dist/utils/helpers.d.ts +72 -1
- package/dist/utils/helpers.js +109 -2
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -37,15 +37,6 @@ npm install @green-api/greenapi-integration
|
|
|
37
37
|
### 1. BaseAdapter
|
|
38
38
|
|
|
39
39
|
The foundation of your integration. Handles message & instance management, and platform-specific logic.
|
|
40
|
-
The `BaseAdapter` internally uses `GreenApiClient` for all common operations, so in most cases, you don't need to use
|
|
41
|
-
GreenApiClient methods directly.
|
|
42
|
-
|
|
43
|
-
**When to use `BaseAdapter` vs `GreenApiClient`**:
|
|
44
|
-
|
|
45
|
-
✅ Use `BaseAdapter` methods for all standard operations (sending messages, handling webhooks, managing instances)
|
|
46
|
-
|
|
47
|
-
⚠️ Use `GreenApiClient` directly only for specialized operations not covered by BaseAdapter (like setProfilePicture,
|
|
48
|
-
getAuthorizationCode)
|
|
49
40
|
|
|
50
41
|
```typescript
|
|
51
42
|
abstract class BaseAdapter<TPlatformWebhook, TPlatformMessage> {
|
|
@@ -60,19 +51,76 @@ abstract class BaseAdapter<TPlatformWebhook, TPlatformMessage> {
|
|
|
60
51
|
}
|
|
61
52
|
```
|
|
62
53
|
|
|
63
|
-
|
|
54
|
+
#### Methods
|
|
55
|
+
|
|
56
|
+
When extending BaseAdapter, your implementation has access to several methods:
|
|
57
|
+
|
|
58
|
+
##### Webhook Handling
|
|
59
|
+
|
|
60
|
+
These webhook handling methods call your message transformation methods automatically, without the need to use them
|
|
61
|
+
directly in
|
|
62
|
+
your code.
|
|
64
63
|
|
|
65
64
|
```typescript
|
|
66
|
-
//
|
|
67
|
-
|
|
68
|
-
await adapter.handlePlatformWebhook(webhook, instanceId);
|
|
69
|
-
await adapter.createInstance(instance, settings, userCred);
|
|
70
|
-
await adapter.sendMessage(transformedWebhook);
|
|
65
|
+
// Handle webhooks from your platform
|
|
66
|
+
await adapter.handlePlatformWebhook(webhookData, instanceId);
|
|
71
67
|
|
|
72
|
-
//
|
|
73
|
-
|
|
74
|
-
await
|
|
75
|
-
|
|
68
|
+
// Handle webhooks from GREEN-API. The second parameter is telling the function to handle only specific webhooks.
|
|
69
|
+
// The second parameter must be specified, otherwise webhooks will not be processed.
|
|
70
|
+
await adapter.handleGreenApiWebhook(webhook, ['incomingMessageReceived']);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
##### Instance Management
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
// Create new instance
|
|
77
|
+
const instance = await adapter.createInstance(instanceData, settings, userEmail);
|
|
78
|
+
|
|
79
|
+
// Get instance details
|
|
80
|
+
const details = await adapter.getInstance(instanceId);
|
|
81
|
+
|
|
82
|
+
// Remove instance
|
|
83
|
+
await adapter.removeInstance(instanceId);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
##### User Management
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// Create new user
|
|
90
|
+
const user = await adapter.createUser(userEmail, userData);
|
|
91
|
+
|
|
92
|
+
// Update user
|
|
93
|
+
await adapter.updateUser(userEmail, updateData);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
#### Webhook Implementation Example
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
// Platform webhook endpoint
|
|
100
|
+
app.post('/webhook/platform', async (req, res) => {
|
|
101
|
+
try {
|
|
102
|
+
await adapter.handlePlatformWebhook(req.body, instanceId);
|
|
103
|
+
res.status(200).send();
|
|
104
|
+
} catch (error) {
|
|
105
|
+
console.error('Failed to handle platform webhook:', error);
|
|
106
|
+
res.status(500).send();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// GREEN-API webhook endpoint
|
|
111
|
+
app.post('/webhook/green-api', async (req, res) => {
|
|
112
|
+
try {
|
|
113
|
+
// Process specific webhook types
|
|
114
|
+
await adapter.handleGreenApiWebhook(req.body, [
|
|
115
|
+
'incomingMessageReceived',
|
|
116
|
+
'outgoingMessageStatus'
|
|
117
|
+
]);
|
|
118
|
+
res.status(200).send();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
console.error('Failed to handle GREEN-API webhook:', error);
|
|
121
|
+
res.status(500).send();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
76
124
|
```
|
|
77
125
|
|
|
78
126
|
### 2. MessageTransformer
|
|
@@ -147,8 +195,7 @@ app.post('/webhook', async (req, res) => {
|
|
|
147
195
|
|
|
148
196
|
### 5. GreenApiClient
|
|
149
197
|
|
|
150
|
-
Direct interface to GREEN-API
|
|
151
|
-
be used directly for specialized operations.
|
|
198
|
+
Direct interface to GREEN-API methods.
|
|
152
199
|
|
|
153
200
|
```typescript
|
|
154
201
|
const client = new GreenApiClient({
|
|
@@ -156,7 +203,7 @@ const client = new GreenApiClient({
|
|
|
156
203
|
apiTokenInstance: 'your_token'
|
|
157
204
|
});
|
|
158
205
|
|
|
159
|
-
// Examples
|
|
206
|
+
// Examples:
|
|
160
207
|
await client.setProfilePicture(fileBlob);
|
|
161
208
|
await client.getAuthorizationCode(phoneNumber);
|
|
162
209
|
await client.getQR();
|
|
@@ -164,6 +211,8 @@ await client.getQR();
|
|
|
164
211
|
|
|
165
212
|
## Developer Guide
|
|
166
213
|
|
|
214
|
+
This guide will walk you through creating your first integration with GREEN-API's WhatsApp gateway.
|
|
215
|
+
|
|
167
216
|
### Project Structure
|
|
168
217
|
|
|
169
218
|
```
|
|
@@ -181,9 +230,37 @@ your-integration/
|
|
|
181
230
|
└── tsconfig.json
|
|
182
231
|
```
|
|
183
232
|
|
|
233
|
+
```mermaid
|
|
234
|
+
graph TB
|
|
235
|
+
subgraph "WhatsApp to Platform"
|
|
236
|
+
WA[WhatsApp] -->|Send message| GA1[GREEN-API]
|
|
237
|
+
GA1 -->|Webhook| INT1[Your Integration]
|
|
238
|
+
INT1 -->|1 . Validate webhook| GD1[BaseGreenApiAuthGuard]
|
|
239
|
+
INT1 -->|2 . Transform message| TR1[MessageTransformer]
|
|
240
|
+
INT1 -->|3 . Send to platform| PL1[Your Platform]
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
subgraph "Platform to WhatsApp"
|
|
244
|
+
PL2[Your Platform] -->|Webhook| INT2[Your Integration]
|
|
245
|
+
INT2 -->|1 . Transform message| TR2[MessageTransformer]
|
|
246
|
+
INT2 -->|2 . Send via API| GA2[GREEN-API]
|
|
247
|
+
GA2 -->|Send message| WA2[WhatsApp]
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
subgraph "Components"
|
|
251
|
+
style Components fill: #f9f9f9, stroke: #333, stroke-width: 2px
|
|
252
|
+
TR[MessageTransformer]
|
|
253
|
+
ST[StorageProvider]
|
|
254
|
+
AD[BaseAdapter]
|
|
255
|
+
GD[WebhookGuard]
|
|
256
|
+
end
|
|
257
|
+
```
|
|
258
|
+
|
|
184
259
|
### Implementation Steps
|
|
185
260
|
|
|
186
|
-
1
|
|
261
|
+
#### Step 1: Define Platform Types
|
|
262
|
+
|
|
263
|
+
First, define the message types for your platform:
|
|
187
264
|
|
|
188
265
|
```typescript
|
|
189
266
|
// types/types.ts
|
|
@@ -202,7 +279,9 @@ export interface YourPlatformMessage {
|
|
|
202
279
|
}
|
|
203
280
|
```
|
|
204
281
|
|
|
205
|
-
2
|
|
282
|
+
#### Step 2: Create Message Transformer
|
|
283
|
+
|
|
284
|
+
Create a transformer that converts messages between your platform's format and GREEN-API's format:
|
|
206
285
|
|
|
207
286
|
```typescript
|
|
208
287
|
// core/transformer.ts
|
|
@@ -229,7 +308,9 @@ export class YourTransformer extends MessageTransformer<YourPlatformWebhook, You
|
|
|
229
308
|
}
|
|
230
309
|
```
|
|
231
310
|
|
|
232
|
-
3
|
|
311
|
+
#### Step 3: Implement Storage Provider
|
|
312
|
+
|
|
313
|
+
Create a storage provider to manage users and instances. You can use any database or ORM:
|
|
233
314
|
|
|
234
315
|
```typescript
|
|
235
316
|
// core/storage.ts
|
|
@@ -258,7 +339,9 @@ export class YourStorage extends StorageProvider {
|
|
|
258
339
|
}
|
|
259
340
|
```
|
|
260
341
|
|
|
261
|
-
4
|
|
342
|
+
#### Step 4: Create Your Platform Adapter
|
|
343
|
+
|
|
344
|
+
The adapter handles the actual communication between platforms:
|
|
262
345
|
|
|
263
346
|
```typescript
|
|
264
347
|
// core/adapter.ts
|
|
@@ -281,7 +364,9 @@ export class YourAdapter extends BaseAdapter<YourPlatformWebhook, YourPlatformMe
|
|
|
281
364
|
}
|
|
282
365
|
```
|
|
283
366
|
|
|
284
|
-
5
|
|
367
|
+
#### Step 5: Implement Webhook Controller
|
|
368
|
+
|
|
369
|
+
Define webhook endpoints that your application will listen to:
|
|
285
370
|
|
|
286
371
|
```typescript
|
|
287
372
|
// core/webhook.ts
|
|
@@ -366,7 +451,9 @@ router.post('/instance', async (req, res) => {
|
|
|
366
451
|
export default router;
|
|
367
452
|
```
|
|
368
453
|
|
|
369
|
-
6
|
|
454
|
+
#### Step 6: Create Application Entry Point
|
|
455
|
+
|
|
456
|
+
Put it all together in your entrypoint:
|
|
370
457
|
|
|
371
458
|
```typescript
|
|
372
459
|
// main.ts
|
|
@@ -407,24 +494,6 @@ async function bootstrap() {
|
|
|
407
494
|
bootstrap();
|
|
408
495
|
```
|
|
409
496
|
|
|
410
|
-
Or with NestJS:
|
|
411
|
-
|
|
412
|
-
```typescript
|
|
413
|
-
// main.ts
|
|
414
|
-
import { NestFactory } from '@nestjs/core';
|
|
415
|
-
import { AppModule } from './app.module';
|
|
416
|
-
import helmet from 'helmet';
|
|
417
|
-
|
|
418
|
-
async function bootstrap() {
|
|
419
|
-
const app = await NestFactory.create(AppModule);
|
|
420
|
-
app.setGlobalPrefix('api');
|
|
421
|
-
app.use(helmet());
|
|
422
|
-
await app.listen(process.env.PORT ?? 3000);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
bootstrap();
|
|
426
|
-
```
|
|
427
|
-
|
|
428
497
|
### Publishing Your Integration
|
|
429
498
|
|
|
430
499
|
1. **Prepare package.json**
|
|
@@ -441,7 +510,6 @@ bootstrap();
|
|
|
441
510
|
},
|
|
442
511
|
"dependencies": {
|
|
443
512
|
"@green-api/greenapi-integration": "^1.0.0",
|
|
444
|
-
"@prisma/client": "^5.0.0",
|
|
445
513
|
"express": "^4.18.2"
|
|
446
514
|
// other dependencies
|
|
447
515
|
}
|
|
@@ -741,18 +809,7 @@ PORT=3000
|
|
|
741
809
|
|
|
742
810
|
For complete real-world integration examples, check out:
|
|
743
811
|
|
|
744
|
-
- [Rocket.Chat Integration](
|
|
745
|
-
|
|
746
|
-
## Best Practices
|
|
747
|
-
|
|
748
|
-
1. **Message Transformation**:
|
|
749
|
-
- Handle only relevant message types
|
|
750
|
-
|
|
751
|
-
2. **Security**:
|
|
752
|
-
- Validate all incoming webhooks
|
|
753
|
-
- Use secure tokens
|
|
754
|
-
- Implement rate limiting
|
|
755
|
-
- Use HTTPS for all endpoints
|
|
812
|
+
- [Rocket.Chat Integration](https://github.com/green-api/greenapi-integration-rocketchat)
|
|
756
813
|
|
|
757
814
|
## Utilities
|
|
758
815
|
|
|
@@ -764,6 +821,10 @@ formatPhoneNumber('1234567890') // Returns '1234567890@c.us'
|
|
|
764
821
|
|
|
765
822
|
// Generate secure random tokens
|
|
766
823
|
generateRandomToken(32) // Returns a 32-character random token
|
|
824
|
+
|
|
825
|
+
// Extract phone number from vcard
|
|
826
|
+
const vcard = 'BEGIN:VCARD\nTEL:+1234567890\nEND:VCARD'
|
|
827
|
+
extractPhoneNumberFromVCard(vcard) // Returns '+1234567890'
|
|
767
828
|
```
|
|
768
829
|
|
|
769
830
|
## License
|
package/README.ru.md
CHANGED
|
@@ -37,17 +37,6 @@ npm install @green-api/greenapi-integration
|
|
|
37
37
|
### 1. BaseAdapter
|
|
38
38
|
|
|
39
39
|
Основа вашей интеграции. Управляет сообщениями и инстансами, а также логикой взаимодействия с платформой.
|
|
40
|
-
BaseAdapter внутренне использует GreenApiClient для всех общих операций, поэтому в большинстве случаев вам не нужно
|
|
41
|
-
использовать
|
|
42
|
-
методы GreenApiClient напрямую.
|
|
43
|
-
|
|
44
|
-
**Когда использовать BaseAdapter, а когда GreenApiClient**:
|
|
45
|
-
|
|
46
|
-
✅ Используйте методы BaseAdapter для всех стандартных операций (отправка сообщений, обработка вебхуков, управление
|
|
47
|
-
инстансами)
|
|
48
|
-
|
|
49
|
-
⚠️ Используйте GreenApiClient напрямую только для специальных операций, не покрытых BaseAdapter (например,
|
|
50
|
-
setProfilePicture, getAuthorizationCode)
|
|
51
40
|
|
|
52
41
|
```typescript
|
|
53
42
|
abstract class BaseAdapter<TPlatformWebhook, TPlatformMessage> {
|
|
@@ -62,19 +51,75 @@ abstract class BaseAdapter<TPlatformWebhook, TPlatformMessage> {
|
|
|
62
51
|
}
|
|
63
52
|
```
|
|
64
53
|
|
|
65
|
-
|
|
54
|
+
#### Методы
|
|
55
|
+
|
|
56
|
+
При расширении BaseAdapter, ваша реализация получает доступ к следующим методам:
|
|
57
|
+
|
|
58
|
+
##### Обработка вебхуков
|
|
59
|
+
|
|
60
|
+
Эти методы обработки вебхуков автоматически вызывают ваши методы преобразования (маппинга) сообщений, без необходимости
|
|
61
|
+
использовать их напрямую.
|
|
66
62
|
|
|
67
63
|
```typescript
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
await adapter.handlePlatformWebhook(webhook, instanceId);
|
|
71
|
-
await adapter.createInstance(instance, settings, userCred);
|
|
72
|
-
await adapter.sendMessage(transformedWebhook);
|
|
64
|
+
// Обработка вебхуков от вашей платформы
|
|
65
|
+
await adapter.handlePlatformWebhook(webhookData, instanceId);
|
|
73
66
|
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
await
|
|
77
|
-
|
|
67
|
+
// Обработка вебхуков от GREEN-API. Второй параметр указывает функции, какие конкретные вебхуки обрабатывать.
|
|
68
|
+
// Второй параметр должен быть указан, иначе вебхуки не будут обработаны.
|
|
69
|
+
await adapter.handleGreenApiWebhook(webhook, ['incomingMessageReceived']);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
##### Управление инстансами
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
// Создание нового инстанса
|
|
76
|
+
const instance = await adapter.createInstance(instanceData, settings, userEmail);
|
|
77
|
+
|
|
78
|
+
// Получение данных инстанса
|
|
79
|
+
const details = await adapter.getInstance(instanceId);
|
|
80
|
+
|
|
81
|
+
// Удаление инстанса
|
|
82
|
+
await adapter.removeInstance(instanceId);
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
##### Управление пользователями
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
// Создание нового пользователя
|
|
89
|
+
const user = await adapter.createUser(userEmail, userData);
|
|
90
|
+
|
|
91
|
+
// Обновление пользователя
|
|
92
|
+
await adapter.updateUser(userEmail, updateData);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
#### Пример реализации вебхуков
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
// Конечная точка для вебхуков платформы
|
|
99
|
+
app.post('/webhook/platform', async (req, res) => {
|
|
100
|
+
try {
|
|
101
|
+
await adapter.handlePlatformWebhook(req.body, instanceId);
|
|
102
|
+
res.status(200).send();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
console.error('Не удалось обработать вебхук платформы:', error);
|
|
105
|
+
res.status(500).send();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// Конечная точка для вебхуков GREEN-API
|
|
110
|
+
app.post('/webhook/green-api', async (req, res) => {
|
|
111
|
+
try {
|
|
112
|
+
// Обработка определенных типов вебхуков
|
|
113
|
+
await adapter.handleGreenApiWebhook(req.body, [
|
|
114
|
+
'incomingMessageReceived',
|
|
115
|
+
'outgoingMessageStatus'
|
|
116
|
+
]);
|
|
117
|
+
res.status(200).send();
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error('Не удалось обработать вебхук GREEN-API:', error);
|
|
120
|
+
res.status(500).send();
|
|
121
|
+
}
|
|
122
|
+
});
|
|
78
123
|
```
|
|
79
124
|
|
|
80
125
|
### 2. MessageTransformer
|
|
@@ -166,6 +211,8 @@ await client.getQR();
|
|
|
166
211
|
|
|
167
212
|
## Руководство разработчика
|
|
168
213
|
|
|
214
|
+
Это руководство проведет вас через процесс создания вашей первой интеграции с WhatsApp шлюзом GREEN-API.
|
|
215
|
+
|
|
169
216
|
### Структура проекта
|
|
170
217
|
|
|
171
218
|
```
|
|
@@ -183,9 +230,37 @@ your-integration/
|
|
|
183
230
|
└── tsconfig.json
|
|
184
231
|
```
|
|
185
232
|
|
|
233
|
+
```mermaid
|
|
234
|
+
graph TB
|
|
235
|
+
subgraph "WhatsApp в Платформу"
|
|
236
|
+
WA[WhatsApp] -->|Отправка сообщения| GA1[GREEN-API]
|
|
237
|
+
GA1 -->|Вебхук| INT1[Ваша Интеграция]
|
|
238
|
+
INT1 -->|1 . Валидация вебхука| GD1[BaseGreenApiAuthGuard]
|
|
239
|
+
INT1 -->|2 . Преобразование сообщения| TR1[MessageTransformer]
|
|
240
|
+
INT1 -->|3 . Отправка в платформу| PL1[Ваша Платформа]
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
subgraph "Платформа в WhatsApp"
|
|
244
|
+
PL2[Ваша Платформа] -->|Вебхук| INT2[Ваша Интеграция]
|
|
245
|
+
INT2 -->|1 . Преобразование сообщения| TR2[MessageTransformer]
|
|
246
|
+
INT2 -->|2 . Отправка через API| GA2[GREEN-API]
|
|
247
|
+
GA2 -->|Отправка сообщения| WA2[WhatsApp]
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
subgraph "Компоненты"
|
|
251
|
+
style Компоненты fill: #f9f9f9, stroke: #333, stroke-width: 2px
|
|
252
|
+
TR[MessageTransformer]
|
|
253
|
+
ST[StorageProvider]
|
|
254
|
+
AD[BaseAdapter]
|
|
255
|
+
GD[WebhookGuard]
|
|
256
|
+
end
|
|
257
|
+
```
|
|
258
|
+
|
|
186
259
|
### Этапы реализации
|
|
187
260
|
|
|
188
|
-
1
|
|
261
|
+
#### Этап 1: Определение типов платформы
|
|
262
|
+
|
|
263
|
+
Сначала определите типы сообщений для вашей платформы:
|
|
189
264
|
|
|
190
265
|
```typescript
|
|
191
266
|
// types/types.ts
|
|
@@ -204,7 +279,9 @@ export interface YourPlatformMessage {
|
|
|
204
279
|
}
|
|
205
280
|
```
|
|
206
281
|
|
|
207
|
-
2.
|
|
282
|
+
#### Этап 2. Создание преобразователя сообщений
|
|
283
|
+
|
|
284
|
+
Создайте преобразователь, который конвертирует сообщения между форматом вашей платформы и форматом GREEN-API:
|
|
208
285
|
|
|
209
286
|
```typescript
|
|
210
287
|
// core/transformer.ts
|
|
@@ -231,7 +308,10 @@ export class YourTransformer extends MessageTransformer<YourPlatformWebhook, You
|
|
|
231
308
|
}
|
|
232
309
|
```
|
|
233
310
|
|
|
234
|
-
3
|
|
311
|
+
#### Этап 3: Реализация хранилища
|
|
312
|
+
|
|
313
|
+
Создайте провайдер хранилища для управления пользователями и инстансами. Вы можете использовать любую базу данных или
|
|
314
|
+
ORM:
|
|
235
315
|
|
|
236
316
|
```typescript
|
|
237
317
|
// core/storage.ts
|
|
@@ -260,7 +340,9 @@ export class YourStorage extends StorageProvider {
|
|
|
260
340
|
}
|
|
261
341
|
```
|
|
262
342
|
|
|
263
|
-
4
|
|
343
|
+
#### Этап 4: Создание адаптера платформы
|
|
344
|
+
|
|
345
|
+
Адаптер обрабатывает фактическое взаимодействие между платформами:
|
|
264
346
|
|
|
265
347
|
```typescript
|
|
266
348
|
// core/adapter.ts
|
|
@@ -283,7 +365,9 @@ export class YourAdapter extends BaseAdapter<YourPlatformWebhook, YourPlatformMe
|
|
|
283
365
|
}
|
|
284
366
|
```
|
|
285
367
|
|
|
286
|
-
5
|
|
368
|
+
#### Этап 5: Реализация контроллера вебхуков
|
|
369
|
+
|
|
370
|
+
Определите эндпоинты вебхуков, которые будет слушать ваше приложение:
|
|
287
371
|
|
|
288
372
|
```typescript
|
|
289
373
|
// core/webhook.ts
|
|
@@ -368,7 +452,9 @@ router.post('/instance', async (req, res) => {
|
|
|
368
452
|
export default router;
|
|
369
453
|
```
|
|
370
454
|
|
|
371
|
-
6
|
|
455
|
+
#### Этап 6: Создание точки входа приложения
|
|
456
|
+
|
|
457
|
+
Соберите все компоненты вместе в точке входа:
|
|
372
458
|
|
|
373
459
|
```typescript
|
|
374
460
|
// main.ts
|
|
@@ -744,18 +830,7 @@ PORT=3000
|
|
|
744
830
|
|
|
745
831
|
Для полных примеров реальных интеграций, смотрите:
|
|
746
832
|
|
|
747
|
-
- [Интеграция с Rocket.Chat](
|
|
748
|
-
|
|
749
|
-
## Лучшие практики
|
|
750
|
-
|
|
751
|
-
1. **Преобразование сообщений**:
|
|
752
|
-
- Обрабатывайте только релевантные типы сообщений
|
|
753
|
-
|
|
754
|
-
2. **Безопасность**:
|
|
755
|
-
- Проверяйте все входящие вебхуки
|
|
756
|
-
- Используйте безопасные вебхук-токены
|
|
757
|
-
- Реализуйте ограничение частоты запросов
|
|
758
|
-
- Используйте HTTPS для всех эндпоинтов
|
|
833
|
+
- [Интеграция с Rocket.Chat](https://github.com/green-api/greenapi-integration-rocketchat)
|
|
759
834
|
|
|
760
835
|
## Утилиты
|
|
761
836
|
|
|
@@ -767,6 +842,10 @@ formatPhoneNumber('1234567890') // Возвращает '1234567890@c.us'
|
|
|
767
842
|
|
|
768
843
|
// Генерация безопасных случайных токенов
|
|
769
844
|
generateRandomToken(32) // Возвращает 32-символьный случайный токен
|
|
845
|
+
|
|
846
|
+
// Извлечение номера телефона из vcard
|
|
847
|
+
const vcard = 'BEGIN:VCARD\nTEL:+1234567890\nEND:VCARD'
|
|
848
|
+
extractPhoneNumberFromVCard(vcard) // Возвращает '+1234567890'
|
|
770
849
|
```
|
|
771
850
|
|
|
772
851
|
## Лицензия
|
|
@@ -1,23 +1,164 @@
|
|
|
1
1
|
import { GreenApiClient } from "./green-api.client";
|
|
2
2
|
import { MessageTransformer } from "./message-transformer";
|
|
3
|
-
import {
|
|
3
|
+
import { BaseUser, ForwardMessagesResponse, GreenApiWebhook, Instance, SendResponse, StateInstanceWebhook, WebhookType } from "../types/types";
|
|
4
4
|
import { StorageProvider } from "./storage-provider";
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Base adapter for platform integrations with GREEN-API.
|
|
7
|
+
* This class handles the core integration logic between your platform and GREEN-API's WhatsApp gateway.
|
|
8
|
+
*
|
|
9
|
+
* @category Core
|
|
10
|
+
* @typeParam TPlatformWebhook - The webhook type specific to your platform
|
|
11
|
+
* @typeParam TPlatformMessage - The message type specific to your platform
|
|
12
|
+
* @typeParam TUser - User type extending BaseUser (default: BaseUser)
|
|
13
|
+
* @typeParam TInstance - Instance type extending Instance (default: Instance)
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* class YourAdapter extends BaseAdapter<YourWebhook, YourMessage> {
|
|
18
|
+
* async createPlatformClient(config: YourConfig) {
|
|
19
|
+
* return new YourPlatformClient(config);
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* async sendToPlatform(message: YourMessage, instance: Instance) {
|
|
23
|
+
* const client = await this.createPlatformClient(instance.config);
|
|
24
|
+
* await client.sendMessage(message);
|
|
25
|
+
* }
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare abstract class BaseAdapter<TPlatformWebhook, TPlatformMessage, TUser extends BaseUser = BaseUser, TInstance extends Instance = Instance> {
|
|
6
30
|
protected transformer: MessageTransformer<TPlatformWebhook, TPlatformMessage>;
|
|
7
31
|
protected storage: StorageProvider<TUser, TInstance>;
|
|
32
|
+
/**
|
|
33
|
+
* Creates an instance of BaseAdapter.
|
|
34
|
+
*
|
|
35
|
+
* @param transformer - Message transformer for converting between platform and GREEN-API formats
|
|
36
|
+
* @param storage - Storage provider for user and instance data
|
|
37
|
+
*/
|
|
8
38
|
constructor(transformer: MessageTransformer<TPlatformWebhook, TPlatformMessage>, storage: StorageProvider<TUser, TInstance>);
|
|
39
|
+
/**
|
|
40
|
+
* Sends a message to your platform. This method must be implemented to define how
|
|
41
|
+
* messages are sent to your specific platform.
|
|
42
|
+
*
|
|
43
|
+
* @param message - The platform-specific message to send
|
|
44
|
+
* @param instance - The instance configuration for the current integration
|
|
45
|
+
* @returns Promise that resolves when the message is sent
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* async sendToPlatform(message: YourMessage, instance: Instance) {
|
|
50
|
+
* const client = await this.createPlatformClient(instance.config);
|
|
51
|
+
* await client.sendMessage({
|
|
52
|
+
* recipient: message.to,
|
|
53
|
+
* content: message.text
|
|
54
|
+
* });
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
9
58
|
abstract sendToPlatform(message: TPlatformMessage, instance: TInstance): Promise<void>;
|
|
10
|
-
|
|
11
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Creates a platform-specific client. This method must be implemented to define how
|
|
61
|
+
* to create a client for your platform's API.
|
|
62
|
+
*
|
|
63
|
+
* @param params - Configuration parameters for your platform's client
|
|
64
|
+
* @returns Promise resolving to your platform's client instance
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* async createPlatformClient(config: YourConfig) {
|
|
69
|
+
* return new YourPlatformSDK({
|
|
70
|
+
* apiKey: config.apiKey,
|
|
71
|
+
* apiUrl: config.apiUrl
|
|
72
|
+
* });
|
|
73
|
+
* }
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
12
76
|
abstract createPlatformClient(params: any): Promise<any>;
|
|
77
|
+
/**
|
|
78
|
+
* Handles instance state change webhooks from GREEN-API.
|
|
79
|
+
* Adapters MUST override this method if they need to handle instance state changes
|
|
80
|
+
*
|
|
81
|
+
* @param webhook - The state change webhook from GREEN-API
|
|
82
|
+
* @returns Promise resolving when the webhook is handled
|
|
83
|
+
*/
|
|
84
|
+
handleStateInstanceWebhook(webhook: StateInstanceWebhook): Promise<void>;
|
|
85
|
+
/**
|
|
86
|
+
* Creates a GREEN-API client instance.
|
|
87
|
+
*
|
|
88
|
+
* @param instance - The instance configuration containing ID and token
|
|
89
|
+
* @returns GREEN-API client
|
|
90
|
+
*/
|
|
91
|
+
createGreenApiClient(instance: Instance): GreenApiClient;
|
|
92
|
+
/**
|
|
93
|
+
* Handles and wraps errors in IntegrationError.
|
|
94
|
+
*
|
|
95
|
+
* @param context - Error context description
|
|
96
|
+
* @param error - Original error
|
|
97
|
+
* @throws {IntegrationError} Always throws wrapped error
|
|
98
|
+
* @internal This method is used internally by the adapter
|
|
99
|
+
*/
|
|
100
|
+
private handleError;
|
|
101
|
+
/**
|
|
102
|
+
* Handles incoming webhooks from your platform and sends them to GREEN-API.
|
|
103
|
+
*
|
|
104
|
+
* @param message - The webhook message from your platform
|
|
105
|
+
* @param idInstance - The GREEN-API instance ID
|
|
106
|
+
* @returns Promise resolving to the send response
|
|
107
|
+
* @throws {IntegrationError} If instance is not found or message handling fails
|
|
108
|
+
*/
|
|
13
109
|
handlePlatformWebhook(message: TPlatformWebhook, idInstance: number | bigint): Promise<SendResponse | ForwardMessagesResponse>;
|
|
14
|
-
|
|
15
|
-
|
|
110
|
+
/**
|
|
111
|
+
* Handles incoming GREEN-API webhooks and forwards them to your platform.
|
|
112
|
+
*
|
|
113
|
+
* @param webhook - The webhook from GREEN-API
|
|
114
|
+
* @param allowedTypes - Array of webhook types to process, otherwise skipped
|
|
115
|
+
* @throws {NotFoundError} If instance is not found
|
|
116
|
+
* @throws {IntegrationError} If webhook handling fails
|
|
117
|
+
*/
|
|
118
|
+
handleGreenApiWebhook(webhook: GreenApiWebhook, allowedTypes: WebhookType[]): Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* Creates a new instance with specified settings.
|
|
121
|
+
*
|
|
122
|
+
* @param instance - The instance configuration
|
|
123
|
+
* @param userCred - User credentials
|
|
124
|
+
* @returns Promise resolving to the created instance
|
|
125
|
+
* @throws {NotFoundError} If user is not found
|
|
126
|
+
* @throws {IntegrationError} If instance creation fails
|
|
127
|
+
*/
|
|
128
|
+
createInstance(instance: Instance, userCred: any): Promise<TInstance>;
|
|
129
|
+
/**
|
|
130
|
+
* Removes an instance by ID.
|
|
131
|
+
*
|
|
132
|
+
* @param idInstance - The instance ID to remove
|
|
133
|
+
* @returns Promise resolving to the removed instance
|
|
134
|
+
* @throws {NotFoundError} If instance is not found
|
|
135
|
+
*/
|
|
16
136
|
removeInstance(idInstance: number | bigint): Promise<TInstance>;
|
|
137
|
+
/**
|
|
138
|
+
* Retrieves an instance by ID.
|
|
139
|
+
*
|
|
140
|
+
* @param idInstance - The instance ID to retrieve
|
|
141
|
+
* @returns Promise resolving to the instance or null if not found
|
|
142
|
+
* @throws {IntegrationError} If retrieval fails
|
|
143
|
+
*/
|
|
17
144
|
getInstance(idInstance: number | bigint): Promise<TInstance | null>;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
145
|
+
/**
|
|
146
|
+
* Updates user information.
|
|
147
|
+
*
|
|
148
|
+
* @param userCred - User credentials
|
|
149
|
+
* @param userUpdateData - New user data
|
|
150
|
+
* @returns Promise resolving to success status
|
|
151
|
+
* @throws {IntegrationError} If update fails
|
|
152
|
+
*/
|
|
153
|
+
updateUser(userCred: any, userUpdateData: any): Promise<TUser>;
|
|
154
|
+
/**
|
|
155
|
+
* Creates a new user in the storage.
|
|
156
|
+
* This method is implemented in the base adapter but can be overridden if needed.
|
|
157
|
+
*
|
|
158
|
+
* @param userCred - User credentials
|
|
159
|
+
* @param data - User data
|
|
160
|
+
* @throws {BadRequestError} If user already exists
|
|
161
|
+
* @throws {IntegrationError} If creation fails
|
|
162
|
+
*/
|
|
22
163
|
createUser(userCred: any, data: any): Promise<TUser>;
|
|
23
164
|
}
|