@warriorteam/messenger-sdk 1.4.0 → 1.4.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.
Files changed (2) hide show
  1. package/README.md +182 -2
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -5,11 +5,14 @@ A modern TypeScript SDK for the Facebook Messenger Platform API, designed with s
5
5
  ## Features
6
6
 
7
7
  - 🚀 **Zero runtime dependencies** - Built with native fetch
8
- - 📝 **Full TypeScript support** - Complete type definitions
8
+ - 📝 **Full TypeScript support** - Complete type definitions with discriminated unions
9
9
  - 🔄 **Dual module support** - ESM and CommonJS
10
10
  - ✅ **Comprehensive validation** - Built-in message and template validation
11
11
  - 🛡️ **Error handling** - Detailed error types and messages
12
12
  - 📚 **Complete API coverage** - Send API, Templates, Attachments, Moderation, Profile
13
+ - 🔐 **Webhook utilities** - Complete webhook type system and signature verification
14
+ - 🎯 **Token override** - Per-method access token override support
15
+ - 🔧 **Type-safe webhooks** - Discriminated unions for proper TypeScript narrowing
13
16
 
14
17
  ## Installation
15
18
 
@@ -47,7 +50,7 @@ console.log('Message sent:', result.message_id);
47
50
 
48
51
  ```typescript
49
52
  const messenger = new Messenger({
50
- accessToken: string; // Required: Your page access token
53
+ accessToken?: string; // Optional: Default page access token
51
54
  version?: string; // Optional: API version (default: 'v23.0')
52
55
  baseUrl?: string; // Optional: Custom base URL
53
56
  timeout?: number; // Optional: Request timeout in ms (default: 30000)
@@ -55,6 +58,35 @@ const messenger = new Messenger({
55
58
  });
56
59
  ```
57
60
 
61
+ ### Token Override Support
62
+
63
+ Every API method supports per-call access token override, perfect for multi-tenant applications:
64
+
65
+ ```typescript
66
+ const messenger = new Messenger({
67
+ accessToken: 'default_page_token'
68
+ });
69
+
70
+ // Use default token
71
+ await messenger.send.message({
72
+ recipient: { id: 'USER_PSID' },
73
+ message: { text: 'Hello from default page!' }
74
+ });
75
+
76
+ // Override token for this specific call
77
+ await messenger.send.message({
78
+ recipient: { id: 'USER_PSID' },
79
+ message: { text: 'Hello from different page!' }
80
+ }, {
81
+ accessToken: 'other_page_token'
82
+ });
83
+
84
+ // Works with all API methods
85
+ const profile = await messenger.profile.getBasic('USER_PSID', {
86
+ accessToken: 'specific_token'
87
+ });
88
+ ```
89
+
58
90
  ### Send API
59
91
 
60
92
  #### Send Text Message
@@ -240,6 +272,151 @@ await messenger.send.message({
240
272
 
241
273
  **Note**: Profile API requires "Advanced User Profile Access" feature and user interaction to grant permissions.
242
274
 
275
+ ## Webhook Support
276
+
277
+ The SDK provides comprehensive webhook support with full TypeScript safety through discriminated unions.
278
+
279
+ ### Webhook Types and Processing
280
+
281
+ ```typescript
282
+ import {
283
+ processWebhookEvents,
284
+ extractWebhookEvents,
285
+ getWebhookEventType,
286
+ getWebhookPayloadEventTypes,
287
+ WebhookEventType,
288
+ GenericWebhookPayload
289
+ } from '@warriorteam/messenger-sdk';
290
+
291
+ // Process webhook with type-safe handlers
292
+ app.post('/webhook', express.json(), async (req, res) => {
293
+ const payload: GenericWebhookPayload = req.body;
294
+
295
+ await processWebhookEvents(payload, {
296
+ onMessage: async (event) => {
297
+ // TypeScript knows this is MessageWebhookEvent
298
+ console.log(`Received message: ${event.message.text}`);
299
+ },
300
+ onMessageEdit: async (event) => {
301
+ // TypeScript knows this is MessageEditWebhookEvent
302
+ console.log(`Message edited to: ${event.message_edit.text}`);
303
+ },
304
+ onMessageReaction: async (event) => {
305
+ // TypeScript knows this is MessageReactionWebhookEvent
306
+ console.log(`Reaction: ${event.reaction.reaction}`);
307
+ },
308
+ onMessagingPostback: async (event) => {
309
+ // TypeScript knows this is MessagingPostbackWebhookEvent
310
+ console.log(`Postback: ${event.postback.payload}`);
311
+ }
312
+ });
313
+
314
+ res.sendStatus(200);
315
+ });
316
+ ```
317
+
318
+ ### Manual Event Processing
319
+
320
+ ```typescript
321
+ // Extract events manually
322
+ const events = extractWebhookEvents(payload);
323
+ for (const event of events) {
324
+ const eventType = getWebhookEventType(event);
325
+
326
+ switch (eventType) {
327
+ case WebhookEventType.MESSAGE:
328
+ // Handle message event
329
+ break;
330
+ case WebhookEventType.MESSAGE_EDIT:
331
+ // Handle edit event
332
+ break;
333
+ // ... other cases
334
+ }
335
+ }
336
+
337
+ // Check what event types are in the payload
338
+ const eventTypes = getWebhookPayloadEventTypes(payload);
339
+ console.log('Received event types:', eventTypes);
340
+ ```
341
+
342
+ ### Webhook Verification
343
+
344
+ The SDK provides utilities for both subscription verification and signature validation:
345
+
346
+ ```typescript
347
+ import {
348
+ verifyWebhookSubscription,
349
+ verifyWebhookSignature
350
+ } from '@warriorteam/messenger-sdk';
351
+
352
+ // Subscription verification (GET request)
353
+ app.get('/webhook', (req, res) => {
354
+ const challenge = verifyWebhookSubscription(
355
+ req.query as any,
356
+ process.env.VERIFY_TOKEN!
357
+ );
358
+
359
+ if (challenge) {
360
+ res.send(challenge);
361
+ } else {
362
+ res.status(403).send('Forbidden');
363
+ }
364
+ });
365
+
366
+ // Signature verification (POST request)
367
+ app.post('/webhook', express.raw({type: 'application/json'}), async (req, res) => {
368
+ const signature = req.get('X-Hub-Signature-256');
369
+ const result = await verifyWebhookSignature(
370
+ req.body,
371
+ signature,
372
+ process.env.APP_SECRET!
373
+ );
374
+
375
+ if (!result.isValid) {
376
+ return res.status(401).json({error: result.error});
377
+ }
378
+
379
+ // Process webhook events...
380
+ const payload = JSON.parse(req.body.toString());
381
+ // ... handle events
382
+ });
383
+ ```
384
+
385
+ ### Type-Safe Event Handling
386
+
387
+ The SDK uses discriminated unions for perfect TypeScript support:
388
+
389
+ ```typescript
390
+ import {
391
+ MessengerWebhookEvent,
392
+ isMessageEvent,
393
+ isMessageEditEvent,
394
+ isMessagingPostbackEvent
395
+ } from '@warriorteam/messenger-sdk';
396
+
397
+ function handleWebhookEvent(event: MessengerWebhookEvent) {
398
+ if (isMessageEvent(event)) {
399
+ // TypeScript knows event.message exists
400
+ console.log(`Message: ${event.message.text}`);
401
+ } else if (isMessageEditEvent(event)) {
402
+ // TypeScript knows event.message_edit exists
403
+ console.log(`Edit: ${event.message_edit.text}`);
404
+ } else if (isMessagingPostbackEvent(event)) {
405
+ // TypeScript knows event.postback exists
406
+ console.log(`Postback: ${event.postback.payload}`);
407
+ }
408
+ }
409
+ ```
410
+
411
+ ### Supported Webhook Event Types
412
+
413
+ - `MESSAGE` - User sends a message
414
+ - `MESSAGE_EDIT` - User edits a sent message
415
+ - `MESSAGE_REACTION` - User reacts to a message
416
+ - `MESSAGE_READ` - User reads messages (read receipts)
417
+ - `MESSAGING_FEEDBACK` - User submits feedback via templates
418
+ - `MESSAGING_POSTBACK` - User clicks buttons/quick replies
419
+
243
420
  ## Error Handling
244
421
 
245
422
  The SDK provides specific error types for different scenarios:
@@ -277,6 +454,9 @@ Check the `examples/` directory for complete usage examples:
277
454
  - `send-template.ts` - Template messages
278
455
  - `user-profile.ts` - Profile API usage
279
456
  - `moderation.ts` - User moderation
457
+ - `webhook-handler.ts` - Complete webhook setup with type safety
458
+ - `multi-tenant.ts` - Token override for multi-tenant applications
459
+ - `signature-verification.ts` - Webhook security implementation
280
460
 
281
461
  ## Development
282
462
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warriorteam/messenger-sdk",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "description": "TypeScript SDK for Facebook Messenger Platform API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",