@oficialapi/sdk 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 OficialAPI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,563 @@
1
+ # OficialAPI SDK
2
+
3
+ SDK oficial da OficialAPI para integração com WhatsApp, Telegram, Facebook, Instagram e WebChat. Desenvolvido em TypeScript com suporte completo a TypeScript e JavaScript.
4
+
5
+ ## 🚀 Características
6
+
7
+ - ✅ **100% TypeScript** - Tipos completos e IntelliSense
8
+ - ✅ **Autenticação Automática** - Renovação automática de tokens
9
+ - ✅ **Retry Inteligente** - Retry automático em caso de falhas
10
+ - ✅ **Tratamento de Erros** - Erros formatados e informativos
11
+ - ✅ **Fácil de Usar** - API intuitiva e bem documentada
12
+ - ✅ **Robusto** - Testado e pronto para produção
13
+ - ✅ **Rápido** - Otimizado para performance
14
+ - ✅ **Seguro** - Validação e sanitização de dados
15
+
16
+ ## 📦 Instalação
17
+
18
+ ```bash
19
+ npm install @oficialapi/sdk
20
+ # ou
21
+ yarn add @oficialapi/sdk
22
+ # ou
23
+ pnpm add @oficialapi/sdk
24
+ ```
25
+
26
+ ## 🔧 Configuração
27
+
28
+ ```typescript
29
+ import { OficialAPISDK } from '@oficialapi/sdk';
30
+
31
+ const sdk = new OficialAPISDK({
32
+ clientId: 'seu-client-id',
33
+ clientSecret: 'seu-client-secret',
34
+ timeout: 30000, // opcional, padrão: 30000ms
35
+ maxRetries: 3, // opcional, padrão: 3
36
+ retryDelay: 1000, // opcional, padrão: 1000ms
37
+ });
38
+ ```
39
+
40
+ ## 📚 Exemplos de Uso
41
+
42
+ ### WhatsApp
43
+
44
+ #### Enviar Mensagem de Texto
45
+
46
+ ```typescript
47
+ const result = await sdk.whatsapp.sendText({
48
+ token: 'sk_live_9999999999999999999999999999',
49
+ sender: '5511999999999',
50
+ messageText: 'Olá! Como posso ajudar você hoje?'
51
+ });
52
+
53
+ console.log(result.data.messageId);
54
+ ```
55
+
56
+ #### Enviar Mídia
57
+
58
+ ```typescript
59
+ await sdk.whatsapp.sendMedia({
60
+ token: 'sk_live_...',
61
+ sender: '5511999999999',
62
+ fileUrl: 'https://example.com/image.jpg',
63
+ type: 'image',
64
+ caption: 'Veja esta imagem!'
65
+ });
66
+ ```
67
+
68
+ #### Enviar Template
69
+
70
+ ```typescript
71
+ await sdk.whatsapp.sendTemplate({
72
+ token: 'sk_live_...',
73
+ sender: '5511999999999',
74
+ templateName: 'welcome_message',
75
+ languageCode: 'pt_BR',
76
+ components: [
77
+ {
78
+ type: 'body',
79
+ parameters: [
80
+ { type: 'text', text: 'João' }
81
+ ]
82
+ }
83
+ ]
84
+ });
85
+ ```
86
+
87
+ #### Enviar Botões
88
+
89
+ ```typescript
90
+ await sdk.whatsapp.sendButtons({
91
+ token: 'sk_live_...',
92
+ sender: '5511999999999',
93
+ messageText: 'Escolha uma opção:',
94
+ buttons: [
95
+ {
96
+ type: 'reply',
97
+ reply: {
98
+ id: 'option1',
99
+ title: 'Opção 1'
100
+ }
101
+ },
102
+ {
103
+ type: 'reply',
104
+ reply: {
105
+ id: 'option2',
106
+ title: 'Opção 2'
107
+ }
108
+ }
109
+ ]
110
+ });
111
+ ```
112
+
113
+ #### Enviar Lista Interativa
114
+
115
+ ```typescript
116
+ await sdk.whatsapp.sendList({
117
+ token: 'sk_live_...',
118
+ sender: '5511999999999',
119
+ messageText: 'Escolha um produto:',
120
+ buttonText: 'Ver Produtos',
121
+ sections: [
122
+ {
123
+ title: 'Produtos',
124
+ rows: [
125
+ {
126
+ id: 'product1',
127
+ title: 'Produto 1',
128
+ description: 'Descrição do produto 1'
129
+ },
130
+ {
131
+ id: 'product2',
132
+ title: 'Produto 2',
133
+ description: 'Descrição do produto 2'
134
+ }
135
+ ]
136
+ }
137
+ ]
138
+ });
139
+ ```
140
+
141
+ #### Enviar Contato
142
+
143
+ ```typescript
144
+ await sdk.whatsapp.sendContact({
145
+ token: 'sk_live_...',
146
+ sender: '5511999999999',
147
+ contacts: [
148
+ {
149
+ name: {
150
+ formatted_name: 'João Silva',
151
+ first_name: 'João',
152
+ last_name: 'Silva'
153
+ },
154
+ phones: [
155
+ {
156
+ phone: '+5511999999999',
157
+ type: 'Mobile',
158
+ wa_id: '5511999999999'
159
+ }
160
+ ]
161
+ }
162
+ ]
163
+ });
164
+ ```
165
+
166
+ #### Enviar Localização
167
+
168
+ ```typescript
169
+ await sdk.whatsapp.sendLocation({
170
+ token: 'sk_live_...',
171
+ sender: '5511999999999',
172
+ latitude: -23.5505,
173
+ longitude: -46.6333,
174
+ name: 'São Paulo',
175
+ address: 'São Paulo, SP, Brasil'
176
+ });
177
+ ```
178
+
179
+ #### Enviar Áudio
180
+
181
+ ```typescript
182
+ await sdk.whatsapp.sendAudio({
183
+ token: 'sk_live_...',
184
+ sender: '5511999999999',
185
+ audioUrl: 'https://example.com/audio.ogg'
186
+ });
187
+ ```
188
+
189
+ #### Enviar Vídeo
190
+
191
+ ```typescript
192
+ await sdk.whatsapp.sendVideo({
193
+ token: 'sk_live_...',
194
+ sender: '5511999999999',
195
+ videoUrl: 'https://example.com/video.mp4',
196
+ caption: 'Veja este vídeo!'
197
+ });
198
+ ```
199
+
200
+ #### Enviar Documento
201
+
202
+ ```typescript
203
+ await sdk.whatsapp.sendDocument({
204
+ token: 'sk_live_...',
205
+ sender: '5511999999999',
206
+ documentUrl: 'https://example.com/document.pdf',
207
+ filename: 'documento.pdf',
208
+ caption: 'Aqui está o documento'
209
+ });
210
+ ```
211
+
212
+ #### Enviar Pedido com Opções de Pagamento
213
+
214
+ ```typescript
215
+ await sdk.whatsapp.sendOrderDetails({
216
+ token: 'sk_live_...',
217
+ sender: '5511999999999',
218
+ orderId: 'ORDER123',
219
+ orderItems: [
220
+ {
221
+ item_code: 'ITEM001',
222
+ description: 'Produto 1',
223
+ quantity: 2,
224
+ price: 50.00
225
+ }
226
+ ],
227
+ orderTotal: 100.00,
228
+ currency: 'BRL',
229
+ paymentMethods: [
230
+ {
231
+ type: 'PIX',
232
+ name: 'PIX'
233
+ },
234
+ {
235
+ type: 'CREDIT_CARD',
236
+ name: 'Cartão de Crédito'
237
+ }
238
+ ]
239
+ });
240
+ ```
241
+
242
+ #### Gerenciar Templates
243
+
244
+ ```typescript
245
+ // Listar templates
246
+ const templates = await sdk.whatsapp.listTemplates('sk_live_...');
247
+
248
+ // Obter detalhes de um template
249
+ const template = await sdk.whatsapp.getTemplate('sk_live_...', 'template_id');
250
+
251
+ // Criar template
252
+ await sdk.whatsapp.createTemplate({
253
+ token: 'sk_live_...',
254
+ name: 'welcome_message',
255
+ language: 'pt_BR',
256
+ category: 'UTILITY',
257
+ components: [
258
+ {
259
+ type: 'BODY',
260
+ text: 'Olá {{1}}! Bem-vindo ao nosso serviço.'
261
+ }
262
+ ]
263
+ });
264
+
265
+ // Upload de mídia para template
266
+ const file = new File(['...'], 'image.jpg', { type: 'image/jpeg' });
267
+ await sdk.whatsapp.uploadMedia({
268
+ token: 'sk_live_...',
269
+ file: file,
270
+ filename: 'image.jpg'
271
+ });
272
+ ```
273
+
274
+ ### Telegram
275
+
276
+ #### Enviar Mensagem de Texto
277
+
278
+ ```typescript
279
+ await sdk.telegram.sendMessage({
280
+ token: 'sk_live_...',
281
+ chatId: '123456789',
282
+ text: 'Olá! Como posso ajudar?',
283
+ parseMode: 'HTML'
284
+ });
285
+ ```
286
+
287
+ #### Enviar Mídia
288
+
289
+ ```typescript
290
+ await sdk.telegram.sendMedia({
291
+ token: 'sk_live_...',
292
+ chatId: '123456789',
293
+ fileUrl: 'https://example.com/image.jpg',
294
+ type: 'photo',
295
+ caption: 'Veja esta imagem!'
296
+ });
297
+ ```
298
+
299
+ #### Enviar Botões
300
+
301
+ ```typescript
302
+ await sdk.telegram.sendButtons({
303
+ token: 'sk_live_...',
304
+ chatId: '123456789',
305
+ text: 'Escolha uma opção:',
306
+ buttons: [
307
+ [
308
+ { text: 'Opção 1', callback_data: 'option1' },
309
+ { text: 'Opção 2', callback_data: 'option2' }
310
+ ]
311
+ ]
312
+ });
313
+ ```
314
+
315
+ #### Enviar Localização
316
+
317
+ ```typescript
318
+ await sdk.telegram.sendLocation({
319
+ token: 'sk_live_...',
320
+ chatId: '123456789',
321
+ latitude: -23.5505,
322
+ longitude: -46.6333
323
+ });
324
+ ```
325
+
326
+ #### Enviar Contato
327
+
328
+ ```typescript
329
+ await sdk.telegram.sendContact({
330
+ token: 'sk_live_...',
331
+ chatId: '123456789',
332
+ phoneNumber: '+5511999999999',
333
+ firstName: 'João',
334
+ lastName: 'Silva'
335
+ });
336
+ ```
337
+
338
+ #### Enviar Enquete
339
+
340
+ ```typescript
341
+ await sdk.telegram.sendPoll({
342
+ token: 'sk_live_...',
343
+ chatId: '123456789',
344
+ question: 'Qual sua cor favorita?',
345
+ options: ['Vermelho', 'Azul', 'Verde'],
346
+ isAnonymous: false
347
+ });
348
+ ```
349
+
350
+ ### WebChat
351
+
352
+ #### Enviar Mensagem de Texto
353
+
354
+ ```typescript
355
+ await sdk.webchat.sendText({
356
+ token: 'sk_live_...',
357
+ sender: 'user123',
358
+ messageText: 'Olá!'
359
+ });
360
+ ```
361
+
362
+ #### Enviar Card
363
+
364
+ ```typescript
365
+ await sdk.webchat.sendCard({
366
+ token: 'sk_live_...',
367
+ sender: 'user123',
368
+ title: 'Produto',
369
+ description: 'Descrição do produto',
370
+ imageUrl: 'https://example.com/image.jpg',
371
+ buttons: [
372
+ {
373
+ type: 'url',
374
+ title: 'Ver Mais',
375
+ value: 'https://example.com/product'
376
+ }
377
+ ]
378
+ });
379
+ ```
380
+
381
+ #### Enviar Formulário
382
+
383
+ ```typescript
384
+ await sdk.webchat.sendForm({
385
+ token: 'sk_live_...',
386
+ sender: 'user123',
387
+ title: 'Formulário de Contato',
388
+ fields: [
389
+ {
390
+ type: 'text',
391
+ name: 'name',
392
+ label: 'Nome',
393
+ required: true
394
+ },
395
+ {
396
+ type: 'email',
397
+ name: 'email',
398
+ label: 'E-mail',
399
+ required: true
400
+ }
401
+ ],
402
+ submitButtonText: 'Enviar'
403
+ });
404
+ ```
405
+
406
+ ### Facebook
407
+
408
+ #### Listar Posts
409
+
410
+ ```typescript
411
+ const posts = await sdk.facebook.listPosts({
412
+ token: 'sk_live_...',
413
+ pageId: 'page_id',
414
+ limit: 10
415
+ });
416
+ ```
417
+
418
+ #### Criar Post
419
+
420
+ ```typescript
421
+ await sdk.facebook.createPost({
422
+ token: 'sk_live_...',
423
+ pageId: 'page_id',
424
+ message: 'Novo post!',
425
+ link: 'https://example.com'
426
+ });
427
+ ```
428
+
429
+ #### Enviar Mensagem
430
+
431
+ ```typescript
432
+ await sdk.facebook.sendText({
433
+ token: 'sk_live_...',
434
+ recipientId: 'user_id',
435
+ message: 'Olá!'
436
+ });
437
+ ```
438
+
439
+ ### Instagram
440
+
441
+ #### Enviar Mensagem de Texto
442
+
443
+ ```typescript
444
+ await sdk.instagram.sendText({
445
+ token: 'sk_live_...',
446
+ recipientId: 'user_id',
447
+ message: 'Olá!'
448
+ });
449
+ ```
450
+
451
+ #### Enviar Mídia
452
+
453
+ ```typescript
454
+ await sdk.instagram.sendMedia({
455
+ token: 'sk_live_...',
456
+ recipientId: 'user_id',
457
+ fileUrl: 'https://example.com/image.jpg',
458
+ type: 'image',
459
+ caption: 'Veja esta imagem!'
460
+ });
461
+ ```
462
+
463
+ #### Enviar Resposta Privada a Comentário
464
+
465
+ ```typescript
466
+ await sdk.instagram.sendPrivateReply({
467
+ token: 'sk_live_...',
468
+ commentId: 'comment_id',
469
+ message: 'Obrigado pelo comentário!'
470
+ });
471
+ ```
472
+
473
+ ### Canais
474
+
475
+ #### Listar Canais
476
+
477
+ ```typescript
478
+ const channels = await sdk.channels.list();
479
+ console.log(channels);
480
+ ```
481
+
482
+ ### Integrações
483
+
484
+ #### Criar Webhook
485
+
486
+ ```typescript
487
+ const webhook = await sdk.integrations.createWebhook({
488
+ url: 'https://example.com/webhook',
489
+ expiresInDays: 365
490
+ });
491
+ ```
492
+
493
+ ## 🔐 Autenticação
494
+
495
+ O SDK gerencia automaticamente a autenticação. Quando você cria uma instância do SDK, ele automaticamente:
496
+
497
+ 1. Obtém um token de acesso usando suas credenciais
498
+ 2. Renova o token quando necessário
499
+ 3. Adiciona o token em todas as requisições
500
+
501
+ Se precisar definir um token manualmente (útil para testes):
502
+
503
+ ```typescript
504
+ sdk.setAccessToken('seu-token-aqui', 86400); // expiresIn em segundos
505
+ ```
506
+
507
+ Para limpar o token:
508
+
509
+ ```typescript
510
+ sdk.clearToken();
511
+ ```
512
+
513
+ ## 🛠️ Tratamento de Erros
514
+
515
+ O SDK formata todos os erros de forma consistente:
516
+
517
+ ```typescript
518
+ try {
519
+ await sdk.whatsapp.sendText({...});
520
+ } catch (error) {
521
+ console.error('Erro:', error.message);
522
+ console.error('Status:', error.status);
523
+ console.error('Detalhes:', error.details);
524
+ }
525
+ ```
526
+
527
+ ## 📝 Tipos TypeScript
528
+
529
+ Todos os tipos estão disponíveis para importação:
530
+
531
+ ```typescript
532
+ import type {
533
+ SDKConfig,
534
+ Channel,
535
+ SendWhatsAppTextParams,
536
+ ApiResponse,
537
+ // ... outros tipos
538
+ } from '@oficialapi/sdk';
539
+ ```
540
+
541
+ ## 🔄 Retry Automático
542
+
543
+ O SDK possui retry automático configurável:
544
+
545
+ - **maxRetries**: Número máximo de tentativas (padrão: 3)
546
+ - **retryDelay**: Delay entre tentativas em ms (padrão: 1000)
547
+
548
+ O retry é aplicado automaticamente em:
549
+ - Erros de rede
550
+ - Erros 5xx (erros do servidor)
551
+ - Timeouts
552
+
553
+ ## 📖 Documentação Completa
554
+
555
+ Para mais informações, consulte a [documentação completa da API](https://api.oficialapi.com.br/api/docs).
556
+
557
+ ## 🤝 Suporte
558
+
559
+ Para suporte, entre em contato através do [painel administrativo](https://access.oficialapi.com.br) ou abra uma issue no repositório.
560
+
561
+ ## 📄 Licença
562
+
563
+ MIT