meta-cloud-api 1.7.3 โ†’ 2.0.1

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 CHANGED
@@ -13,16 +13,48 @@
13
13
 
14
14
  ## Resources
15
15
 
16
- - [Documentation](https://www.meta-cloud-api.xyz/)
16
+ - **[๐Ÿ“š Documentation](https://www.meta-cloud-api.xyz/)** - Complete documentation with guides and examples
17
+ - **[๐Ÿš€ Getting Started](https://www.meta-cloud-api.xyz/getting-started/installation)** - Quick start guide
18
+ - **[๐Ÿ“– API Reference](https://www.meta-cloud-api.xyz/api/messages)** - Comprehensive API documentation
19
+ - **[๐Ÿ”ง Examples](./examples/)** - Production-ready code examples
20
+
21
+ ## Examples
22
+
23
+ - **[express-simple](./examples/express-simple/)** - Basic Express.js integration
24
+ - **[express-production](./examples/express-production/)** - Production-ready example with conversation flows, database, and queue processing
25
+ - **[nextjs-app-router-example](./examples/nextjs-app-router-example/)** - Next.js App Router integration
26
+ - **[nextjs-page-router-example](./examples/nextjs-page-router-example/)** - Next.js Pages Router integration
27
+
28
+ ## Local API Docs
29
+
30
+ - [Messages](./docs/messages.md)
31
+ - [Media](./docs/media.md)
32
+ - [Templates](./docs/templates.md)
33
+ - [Flows](./docs/flows.md)
34
+ - [Phone Numbers](./docs/phone-numbers.md)
35
+ - [Business Profile](./docs/business-profile.md)
36
+ - [Registration](./docs/registration.md)
37
+ - [Two-Step Verification](./docs/two-step-verification.md)
38
+ - [Encryption](./docs/encryption.md)
39
+ - [QR Codes](./docs/qr-codes.md)
40
+ - [WABA](./docs/waba.md)
41
+ - [Block Users](./docs/block-users.md)
42
+ - [Calling](./docs/calling.md)
43
+ - [Groups](./docs/groups.md)
44
+ - [Marketing Messages](./docs/marketing-messages.md)
45
+ - [Commerce Settings](./docs/commerce-settings.md)
46
+ - [Payments](./docs/payments.md)
17
47
 
18
48
  ## Features
19
49
 
20
- - **Type-Safe Development** - Built with TypeScript to provide code completion and catch errors during development
21
- - **Comprehensive Coverage** - Full support for WhatsApp Business Platform APIs including Messages, Media, Templates, Flows, and more
22
- - **Modular Architecture** - Clean separation of concerns with dedicated API classes for each domain
23
- - **Framework-Specific Webhooks** - Built-in support for Express.js and Next.js webhook handling
24
- - **Advanced Features** - Support for Flows, Encryption, QR Codes, Two-Step Verification, and WABA management
25
- - **Error Handling** - Standardized error handling with detailed Meta API error information
50
+ - **๐Ÿ”’ Type-Safe Development** - Built with TypeScript strict mode for complete type safety and excellent IntelliSense
51
+ - **๐Ÿ“ฆ Comprehensive Coverage** - Full support for 17+ WhatsApp Business Platform APIs including Messages, Media, Templates, Flows, and more
52
+ - **๐Ÿ—๏ธ Modular Architecture** - Clean separation with dedicated API classes, tree-shakeable imports, and minimal bundle size
53
+ - **๐Ÿ”Œ Framework-Specific Webhooks** - Built-in adapters for Express.js and Next.js (App Router & Pages Router)
54
+ - **โšก Production Ready** - Battle-tested with error handling, retry logic, rate limiting, and comprehensive logging
55
+ - **๐ŸŽฏ Advanced Features** - Support for Flows, End-to-End Encryption, QR Codes, Two-Step Verification, Groups, and WABA management
56
+ - **๐Ÿ“š Excellent Documentation** - Complete documentation site with guides, API reference, and working examples
57
+ - **๐Ÿงช Well Tested** - Comprehensive test coverage with unit, integration, and E2E tests
26
58
 
27
59
  ## Installation
28
60
 
@@ -34,525 +66,6 @@ yarn add meta-cloud-api
34
66
  pnpm add meta-cloud-api
35
67
  ```
36
68
 
37
- ## Quick Start
38
-
39
- ```typescript
40
- import WhatsApp, { MessageTypesEnum } from 'meta-cloud-api';
41
-
42
- // Initialize the client
43
- const client = new WhatsApp({
44
- accessToken: process.env.CLOUD_API_ACCESS_TOKEN,
45
- phoneNumberId: Number(process.env.WA_PHONE_NUMBER_ID),
46
- businessAcctId: process.env.WA_BUSINESS_ACCOUNT_ID
47
- });
48
-
49
- // Send a WhatsApp text message
50
- const response = await client.messages.text({
51
- to: '+1234567890',
52
- body: 'Hello from Meta Cloud API!'
53
- });
54
-
55
- console.log(`Message ID: ${response.messages[0].id}`);
56
- ```
57
-
58
- ## Usage Examples
59
-
60
- ### Messaging
61
-
62
- #### Text Message
63
-
64
- ```typescript
65
- const result = await client.messages.text({
66
- to: "15551234567",
67
- body: "Hello from Meta Cloud API!"
68
- });
69
- ```
70
-
71
- #### Template Message
72
-
73
- ```typescript
74
- import { ComponentTypesEnum, LanguagesEnum, ParametersTypesEnum } from 'meta-cloud-api';
75
-
76
- const result = await client.messages.template({
77
- to: "15551234567",
78
- body: {
79
- name: "shipping_confirmation",
80
- language: {
81
- code: LanguagesEnum.English_US,
82
- policy: "deterministic"
83
- },
84
- components: [
85
- {
86
- type: ComponentTypesEnum.Body,
87
- parameters: [
88
- {
89
- type: ParametersTypesEnum.Text,
90
- text: "John Doe"
91
- },
92
- {
93
- type: ParametersTypesEnum.Text,
94
- text: "12345"
95
- }
96
- ]
97
- }
98
- ]
99
- }
100
- });
101
- ```
102
-
103
- #### Media Message
104
-
105
- ```typescript
106
- const result = await client.messages.image({
107
- to: "15551234567",
108
- body: {
109
- link: "https://example.com/image.jpg"
110
- }
111
- });
112
- ```
113
-
114
- #### Interactive Message
115
-
116
- ```typescript
117
- import { InteractiveTypesEnum } from 'meta-cloud-api';
118
-
119
- const result = await client.messages.interactive({
120
- to: "15551234567",
121
- body: {
122
- type: InteractiveTypesEnum.Button,
123
- body: {
124
- text: "What would you like to do?"
125
- },
126
- action: {
127
- buttons: [
128
- {
129
- type: "reply",
130
- reply: {
131
- id: "help_button",
132
- title: "Get Help"
133
- }
134
- },
135
- {
136
- type: "reply",
137
- reply: {
138
- id: "info_button",
139
- title: "Account Info"
140
- }
141
- }
142
- ]
143
- }
144
- }
145
- });
146
- ```
147
-
148
- ### Webhook Integration
149
-
150
- #### Express.js Webhook
151
-
152
- ```typescript
153
- import express from 'express';
154
- import { MessageTypesEnum } from 'meta-cloud-api';
155
- import { webhookHandler } from 'meta-cloud-api/webhook/express';
156
-
157
- const app = express();
158
-
159
- // Create webhook handler
160
- const bot = webhookHandler({
161
- accessToken: process.env.CLOUD_API_ACCESS_TOKEN!,
162
- phoneNumberId: parseInt(process.env.WA_PHONE_NUMBER_ID!),
163
- webhookVerificationToken: process.env.WEBHOOK_VERIFICATION_TOKEN!,
164
- });
165
-
166
- // Handle text messages
167
- bot.processor.onMessage(MessageTypesEnum.Text, async (whatsapp, message) => {
168
- await whatsapp.messages.text({
169
- to: message.from,
170
- body: `Echo: ${message.text?.body}`,
171
- });
172
- });
173
-
174
- // Setup webhook endpoints
175
- app.get('/webhook', bot.webhook);
176
- app.post('/webhook', express.json(), bot.webhook);
177
-
178
- app.listen(3000);
179
- ```
180
-
181
- #### Next.js Webhook
182
-
183
- ```typescript
184
- // pages/api/webhook.ts
185
- import { NextApiRequest, NextApiResponse } from 'next';
186
- import { MessageTypesEnum } from 'meta-cloud-api';
187
- import { webhookHandler } from 'meta-cloud-api/webhook/nextjs';
188
-
189
- const bot = webhookHandler({
190
- accessToken: process.env.CLOUD_API_ACCESS_TOKEN!,
191
- phoneNumberId: parseInt(process.env.WA_PHONE_NUMBER_ID!),
192
- webhookVerificationToken: process.env.WEBHOOK_VERIFICATION_TOKEN!,
193
- });
194
-
195
- // Handle text messages
196
- bot.processor.onMessage(MessageTypesEnum.Text, async (whatsapp, message) => {
197
- await whatsapp.messages.text({
198
- to: message.from,
199
- body: `Echo: ${message.text?.body}`,
200
- });
201
- });
202
-
203
- export default async function handler(req: NextApiRequest, res: NextApiResponse) {
204
- return bot.webhook(req, res);
205
- }
206
- ```
207
-
208
- ### Advanced Message Handling
209
-
210
- ```typescript
211
- import { MessageTypesEnum } from 'meta-cloud-api';
212
-
213
- // Pre-process all messages (e.g., mark as read)
214
- // โœจ Use processed.messageId for consistent ID access across all message types
215
- bot.processor.onMessagePreProcess(async (whatsapp, processed) => {
216
- // messageId is automatically extracted from the correct location
217
- // (message.id for most types, message.context.id for nfm_reply)
218
- await whatsapp.messages.markAsRead({ messageId: processed.messageId });
219
- });
220
-
221
- // โœจ Type-safe specialized handlers (recommended)
222
- // These methods provide better type safety - no need for optional chaining!
223
-
224
- bot.processor.onText(async (whatsapp, processed) => {
225
- const { message, messageId } = processed;
226
- // message.text is guaranteed to exist - no need for message.text?.body
227
- console.log('Received:', message.text.body);
228
- await whatsapp.messages.text({
229
- to: message.from,
230
- text: { body: `Echo: ${message.text.body}` }
231
- });
232
-
233
- // Mark as read using the extracted messageId
234
- await whatsapp.messages.markAsRead({ messageId });
235
- });
236
-
237
- bot.processor.onImage(async (whatsapp, processed) => {
238
- const { message } = processed;
239
- // message.image is guaranteed to exist
240
- console.log('Image ID:', message.image.id);
241
- console.log('Caption:', message.image.caption);
242
- });
243
-
244
- bot.processor.onInteractive(async (whatsapp, processed) => {
245
- const { message, messageId } = processed;
246
- // message.interactive is guaranteed to exist
247
- if (message.interactive.type === 'nfm_reply') {
248
- const flowResponse = JSON.parse(message.interactive.nfm_reply.response_json);
249
- console.log('Flow response:', flowResponse);
250
-
251
- // messageId works correctly for nfm_reply (uses context.id automatically)
252
- await whatsapp.messages.markAsRead({ messageId });
253
- } else if (message.interactive.type === 'button_reply') {
254
- console.log('Button clicked:', message.interactive.button_reply.id);
255
- } else if (message.interactive.type === 'list_reply') {
256
- console.log('List item selected:', message.interactive.list_reply.id);
257
- }
258
- });
259
-
260
- // Other specialized handlers available:
261
- // onVideo, onAudio, onDocument, onSticker, onButton,
262
- // onLocation, onContacts, onReaction, onOrder, onSystem
263
-
264
- // ๐Ÿ“ Legacy generic handler (still supported)
265
- bot.processor.onMessage(MessageTypesEnum.Text, async (whatsapp, processed) => {
266
- // With generic handler, you need optional chaining
267
- console.log(processed.message.text?.body); // โš ๏ธ Need ? because text might be undefined
268
-
269
- // But messageId is always available regardless of message type!
270
- await whatsapp.messages.markAsRead({ messageId: processed.messageId });
271
- });
272
-
273
- // ๐Ÿ” TypeScript Discriminated Union for Manual Type Narrowing
274
- // Use this when you need to check message types dynamically in pre/post-process handlers
275
- bot.processor.onMessagePreProcess(async (whatsapp, processed) => {
276
- const { message, messageId } = processed;
277
-
278
- // TypeScript automatically narrows the type based on the type property!
279
- if (message.type === MessageTypesEnum.Text) {
280
- console.log(message.text.body); // โœ… No optional chaining needed!
281
- } else if (message.type === MessageTypesEnum.Image) {
282
- console.log(message.image.id); // โœ… Type-safe!
283
- } else if (message.type === MessageTypesEnum.Interactive) {
284
- console.log(message.interactive.type); // โœ… Guaranteed to exist!
285
- }
286
-
287
- // messageId works for all types - automatically extracted from the correct location
288
- await whatsapp.messages.markAsRead({ messageId });
289
- });
290
-
291
- // Handle message status updates
292
- bot.processor.onMessageStatus(async (whatsapp, status) => {
293
- console.log(`Message ${status.id} status: ${status.status}`);
294
- });
295
- ```
296
-
297
- ### Templates Management
298
-
299
- ```typescript
300
- // List all templates
301
- const templates = await client.templates.list({
302
- businessId: process.env.WA_BUSINESS_ACCOUNT_ID
303
- });
304
-
305
- // Create a new template
306
- const newTemplate = await client.templates.create({
307
- businessId: process.env.WA_BUSINESS_ACCOUNT_ID,
308
- name: "welcome_message",
309
- category: "MARKETING",
310
- components: [
311
- {
312
- type: "HEADER",
313
- format: "TEXT",
314
- text: "Welcome!"
315
- },
316
- {
317
- type: "BODY",
318
- text: "Hi {{1}}, welcome to our service!"
319
- }
320
- ],
321
- language: "en_US"
322
- });
323
- ```
324
-
325
- ### Media Management
326
-
327
- ```typescript
328
- import fs from 'fs';
329
-
330
- // Upload media
331
- const mediaUpload = await client.media.upload({
332
- file: fs.createReadStream("./path/to/image.jpg"),
333
- type: "image/jpeg"
334
- });
335
-
336
- // Get media URL
337
- const media = await client.media.get({
338
- mediaId: mediaUpload.id
339
- });
340
-
341
- // Download media
342
- const mediaBuffer = await client.media.download({
343
- mediaId: mediaUpload.id
344
- });
345
- ```
346
-
347
- ### Business Profile Management
348
-
349
- ```typescript
350
- // Update business profile
351
- const profile = await client.businessProfile.update({
352
- about: "We provide the best service!",
353
- address: "123 Business St, City",
354
- description: "Premium products and services",
355
- email: "contact@business.com",
356
- websites: ["https://www.business.com"]
357
- });
358
-
359
- // Get current profile
360
- const currentProfile = await client.businessProfile.get();
361
- ```
362
-
363
- ### Phone Number Management
364
-
365
- #### Conversational Automation
366
-
367
- Configure conversational components like Welcome Messages, Ice Breakers, and Commands to enhance user interactions:
368
-
369
- ```typescript
370
- // Enable welcome message
371
- await client.phoneNumber.setConversationalAutomation({
372
- enable_welcome_message: true
373
- });
374
-
375
- // Configure ice breakers (prompts) - up to 4, each max 80 characters
376
- await client.phoneNumber.setConversationalAutomation({
377
- prompts: ['Book a flight', 'Plan a vacation', 'Find hotels', 'Get travel tips']
378
- });
379
-
380
- // Configure commands - up to 30, each command max 32 chars, description max 256 chars
381
- await client.phoneNumber.setConversationalAutomation({
382
- commands: [
383
- { command_name: 'tickets', command_description: 'Book flight tickets' },
384
- { command_name: 'hotel', command_description: 'Book hotel rooms' },
385
- { command_name: 'imagine', command_description: 'Create images using a text prompt' }
386
- ]
387
- });
388
-
389
- // Configure all features at once
390
- await client.phoneNumber.setConversationalAutomation({
391
- enable_welcome_message: true,
392
- commands: [
393
- { command_name: 'tickets', command_description: 'Book flight tickets' }
394
- ],
395
- prompts: ['Book a flight', 'Plan a vacation']
396
- });
397
-
398
- // Get current configuration
399
- const config = await client.phoneNumber.getConversationalAutomation();
400
- console.log('Welcome message enabled:', config.enable_welcome_message);
401
- console.log('Commands:', config.commands);
402
- console.log('Ice breakers:', config.prompts);
403
- ```
404
-
405
- #### Phone Number Information
406
-
407
- ```typescript
408
- // Get phone number details
409
- const phoneInfo = await client.phoneNumber.getPhoneNumberById();
410
- console.log('Display number:', phoneInfo.display_phone_number);
411
- console.log('Quality rating:', phoneInfo.quality_rating);
412
- console.log('Verified name:', phoneInfo.verified_name);
413
-
414
- // Get specific fields only
415
- const phoneDetails = await client.phoneNumber.getPhoneNumberById(
416
- 'display_phone_number,verified_name,code_verification_status'
417
- );
418
- ```
419
-
420
- ### Block Users Management
421
-
422
- ```typescript
423
- // Block a user (only works for users who messaged you in last 24 hours)
424
- const blockResult = await client.blockUsers.block(['1234567890']);
425
- console.log('Blocked users:', blockResult.block_users.added_users);
426
- console.log('Failed to block:', blockResult.block_users.failed_users);
427
-
428
- // Block multiple users at once
429
- const multiBlockResult = await client.blockUsers.block([
430
- '1234567890',
431
- '0987654321',
432
- '1122334455'
433
- ]);
434
-
435
- // Unblock users
436
- const unblockResult = await client.blockUsers.unblock(['1234567890']);
437
-
438
- // Get list of blocked users with pagination
439
- const blockedUsers = await client.blockUsers.listBlockedUsers({
440
- limit: 10
441
- });
442
-
443
- // Iterate through all blocked users
444
- let cursor: string | undefined;
445
- const allBlockedUsers = [];
446
-
447
- do {
448
- const page = await client.blockUsers.listBlockedUsers({
449
- limit: 100,
450
- after: cursor
451
- });
452
-
453
- page.data.forEach(item => {
454
- if (item.block_users) {
455
- allBlockedUsers.push(...item.block_users);
456
- }
457
- });
458
-
459
- cursor = page.paging?.cursors?.after;
460
- } while (cursor);
461
-
462
- console.log(`Total blocked users: ${allBlockedUsers.length}`);
463
- ```
464
-
465
- ### WhatsApp Flows
466
-
467
- ```typescript
468
- // Create a flow
469
- const flow = await client.flows.create({
470
- name: "Customer Survey",
471
- categories: ["SURVEY"],
472
- clone_flow_id: "existing_flow_id" // Optional
473
- });
474
-
475
- // Update flow
476
- const updatedFlow = await client.flows.update({
477
- flowId: flow.id,
478
- name: "Updated Survey",
479
- categories: ["SURVEY", "FEEDBACK"]
480
- });
481
- ```
482
-
483
- ## Example Projects
484
-
485
- We provide ready-to-use example projects demonstrating integration with different frameworks:
486
-
487
- ### [Express.js Echo Bot](./examples/express-example)
488
- A simple echo bot that responds to any text message. Perfect for getting started!
489
-
490
- ```bash
491
- cd examples/express-example
492
- npm install
493
- cp env.example .env # Configure your credentials
494
- npm run dev
495
- ```
496
-
497
- ### [Next.js Echo Bot](./examples/nextjs-page-router-example)
498
- Next.js implementation with API routes for webhook handling.
499
-
500
- ```bash
501
- cd examples/nextjs-page-router-example
502
- npm install
503
- cp env.example .env.local # Configure your credentials
504
- npm run dev
505
- ```
506
-
507
- ## Modular Imports
508
-
509
- Use specific imports for better tree-shaking:
510
-
511
- ```typescript
512
- // Import specific API classes
513
- import { MessagesApi } from 'meta-cloud-api/messages';
514
- import { MediaApi } from 'meta-cloud-api/media';
515
- import { TemplateApi } from 'meta-cloud-api/template';
516
-
517
- // Import specific webhook handlers
518
- import { webhookHandler } from 'meta-cloud-api/webhook/express';
519
- import { webhookHandler } from 'meta-cloud-api/webhook/nextjs';
520
-
521
- // Import types and enums
522
- import { MessageTypesEnum, InteractiveTypesEnum } from 'meta-cloud-api/types/enums';
523
- import type { WhatsAppConfig } from 'meta-cloud-api/types/config';
524
- ```
525
-
526
- ## Configuration
527
-
528
- ```typescript
529
- interface WhatsAppConfig {
530
- accessToken: string; // Required: Meta Cloud API access token
531
- phoneNumberId: number; // Required: WhatsApp phone number ID
532
- businessAcctId?: string; // Optional: Business account ID
533
- apiVersion?: string; // Optional: API version (default: v21.0)
534
- webhookVerificationToken?: string; // Optional: For webhook verification
535
- requestTimeout?: number; // Optional: Request timeout in ms
536
- }
537
- ```
538
-
539
- ## Error Handling
540
-
541
- ```typescript
542
- try {
543
- const result = await client.messages.text({
544
- to: "15551234567",
545
- body: "Hello World"
546
- });
547
- } catch (error) {
548
- if (error.response?.data?.error) {
549
- console.error('Meta API Error:', error.response.data.error);
550
- } else {
551
- console.error('Network Error:', error.message);
552
- }
553
- }
554
- ```
555
-
556
69
  ## Requirements
557
70
 
558
71
  - **Node.js** 18 LTS or later
package/dist/chunk.js ADDED
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};