@@ -555,6 +555,277 @@ await client.groups.create(
555555);
556556```
557557
558+ ---
559+
560+ ### 🔗 Webhook Integration
561+
562+ The SDK provides complete TypeScript support for handling webhooks from the Evolution API.
563+
564+ #### Basic Webhook Setup
565+
566+ ``` ts
567+ import express from " express" ;
568+ import {
569+ WebhookData ,
570+ WebhookEvent ,
571+ MessagePayload ,
572+ ContactPayload ,
573+ ConnectionUpdatePayload ,
574+ } from " evolution-api-sdk" ;
575+
576+ const app = express ();
577+ app .use (express .json ());
578+
579+ // Webhook endpoint
580+ app .post (" /webhook" , async (req , res ) => {
581+ try {
582+ const webhookData: WebhookData = req .body ;
583+ await processWebhook (webhookData );
584+ res .status (200 ).send (" OK" );
585+ } catch (error ) {
586+ console .error (" Webhook processing error:" , error );
587+ res .status (500 ).send (" Error" );
588+ }
589+ });
590+
591+ app .listen (3000 , () => {
592+ console .log (" Webhook server running on port 3000" );
593+ });
594+ ```
595+
596+ #### Processing Webhook Events
597+
598+ ``` ts
599+ async function processWebhook(webhookData : WebhookData ): Promise <void > {
600+ const { event, instance, data } = webhookData ;
601+
602+ console .log (` [WEBHOOK] Event: ${event } | Instance: ${instance } ` );
603+
604+ switch (event ) {
605+ case WebhookEvent .MESSAGES_UPSERT :
606+ await handleNewMessage (data as MessagePayload , instance );
607+ break ;
608+
609+ case WebhookEvent .MESSAGES_UPDATE :
610+ await handleMessageUpdate (data as MessagePayload , instance );
611+ break ;
612+
613+ case WebhookEvent .CONNECTION_UPDATE :
614+ await handleConnectionUpdate (data as ConnectionUpdatePayload );
615+ break ;
616+
617+ case WebhookEvent .CONTACTS_UPSERT :
618+ case WebhookEvent .CONTACTS_UPDATE :
619+ await handleContact (data as ContactPayload , instance );
620+ break ;
621+
622+ case WebhookEvent .QRCODE_UPDATED :
623+ console .log (` [WEBHOOK] QR Code updated for instance: ${instance } ` );
624+ break ;
625+
626+ default :
627+ console .log (` [WEBHOOK] Unhandled event: ${event } ` );
628+ }
629+ }
630+ ```
631+
632+ #### Message Handling Examples
633+
634+ ``` ts
635+ async function handleNewMessage(
636+ messageData : MessagePayload ,
637+ instance : string
638+ ): Promise <void > {
639+ const { key, message, pushName } = messageData ;
640+
641+ // Skip messages from groups (optional)
642+ if (key .remoteJid ?.includes (" @g.us" )) {
643+ console .log (" Skipping group message" );
644+ return ;
645+ }
646+
647+ // Skip messages sent by bot itself
648+ if (key .fromMe ) {
649+ console .log (" Skipping outgoing message" );
650+ return ;
651+ }
652+
653+ const from = key .remoteJid ;
654+ const messageId = key .id ;
655+ const contactName = pushName || " Unknown" ;
656+
657+ console .log (` Message from ${contactName } (${from }): ${messageId } ` );
658+
659+ // Process different message types
660+ if (message ?.conversation ) {
661+ // Text message
662+ const text = message .conversation ;
663+ console .log (` Text: ${text } ` );
664+
665+ // Auto-reply example
666+ if (text .toLowerCase () === " hello" ) {
667+ await client .messages .sendText (
668+ {
669+ number: from .replace (" @s.whatsapp.net" , " " ),
670+ text: " Hello! How can I help you?" ,
671+ },
672+ { instance }
673+ );
674+ }
675+ } else if (message ?.imageMessage ) {
676+ // Image message
677+ console .log (` Received image from ${contactName } ` );
678+ const imageUrl = message .imageMessage .url ;
679+ // Process image...
680+ } else if (message ?.audioMessage ) {
681+ // Audio message
682+ console .log (` Received audio from ${contactName } ` );
683+ // Process audio...
684+ }
685+ }
686+
687+ async function handleMessageUpdate(
688+ messageData : MessagePayload ,
689+ instance : string
690+ ): Promise <void > {
691+ const { key, status } = messageData ;
692+ console .log (` Message ${key .id } status updated to: ${status } ` );
693+
694+ // Handle read receipts, delivery confirmations, etc.
695+ switch (status ) {
696+ case " delivered" :
697+ console .log (" Message delivered" );
698+ break ;
699+ case " read" :
700+ console .log (" Message read by recipient" );
701+ break ;
702+ }
703+ }
704+
705+ async function handleConnectionUpdate(
706+ connectionData : ConnectionUpdatePayload
707+ ): Promise <void > {
708+ const { instance, state, statusReason } = connectionData ;
709+
710+ console .log (` Instance ${instance } connection state: ${state } ` );
711+
712+ switch (state ) {
713+ case " open" :
714+ console .log (` ✅ Instance ${instance } connected successfully ` );
715+ break ;
716+ case " close" :
717+ console .log (` ❌ Instance ${instance } disconnected (${statusReason }) ` );
718+ break ;
719+ case " connecting" :
720+ console .log (` 🔄 Instance ${instance } connecting... ` );
721+ break ;
722+ }
723+ }
724+
725+ async function handleContact(
726+ contactData : ContactPayload ,
727+ instance : string
728+ ): Promise <void > {
729+ const { remoteJid, pushName, profilePicUrl } = contactData ;
730+
731+ console .log (` Contact update: ${pushName } (${remoteJid }) ` );
732+
733+ // Store or update contact information
734+ // You might want to save this to your database
735+ }
736+ ```
737+
738+ #### Advanced Webhook Processing
739+
740+ ``` ts
741+ class WebhookProcessor {
742+ private messageQueue: MessagePayload [] = [];
743+ private processing = false ;
744+
745+ async processWebhook(webhookData : WebhookData ): Promise <void > {
746+ const { event, data, instance } = webhookData ;
747+
748+ // Add message to queue for batch processing
749+ if (event === WebhookEvent .MESSAGES_UPSERT ) {
750+ this .messageQueue .push (data as MessagePayload );
751+ this .processQueue ();
752+ }
753+ }
754+
755+ private async processQueue(): Promise <void > {
756+ if (this .processing || this .messageQueue .length === 0 ) return ;
757+
758+ this .processing = true ;
759+
760+ try {
761+ // Process messages in batches
762+ const batch = this .messageQueue .splice (0 , 10 );
763+
764+ for (const message of batch ) {
765+ await this .processMessage (message );
766+ // Add delay to avoid rate limiting
767+ await new Promise ((resolve ) => setTimeout (resolve , 100 ));
768+ }
769+ } finally {
770+ this .processing = false ;
771+
772+ // Continue processing if more messages arrived
773+ if (this .messageQueue .length > 0 ) {
774+ setTimeout (() => this .processQueue (), 1000 );
775+ }
776+ }
777+ }
778+
779+ private async processMessage(message : MessagePayload ): Promise <void > {
780+ // Your message processing logic here
781+ console .log (` Processing message: ${message .key .id } ` );
782+ }
783+ }
784+ ```
785+
786+ #### Available Webhook Events
787+
788+ The SDK supports all Evolution API webhook events:
789+
790+ - ` WebhookEvent.APPLICATION_STARTUP ` - API startup
791+ - ` WebhookEvent.QRCODE_UPDATED ` - QR code updates
792+ - ` WebhookEvent.CONNECTION_UPDATE ` - Connection status changes
793+ - ` WebhookEvent.MESSAGES_SET ` - Initial message load
794+ - ` WebhookEvent.MESSAGES_UPSERT ` - New messages
795+ - ` WebhookEvent.MESSAGES_UPDATE ` - Message status updates
796+ - ` WebhookEvent.MESSAGES_DELETE ` - Message deletions
797+ - ` WebhookEvent.SEND_MESSAGE ` - Message sending events
798+ - ` WebhookEvent.CONTACTS_SET ` - Initial contacts load
799+ - ` WebhookEvent.CONTACTS_UPSERT ` - New contacts
800+ - ` WebhookEvent.CONTACTS_UPDATE ` - Contact updates
801+ - ` WebhookEvent.PRESENCE_UPDATE ` - User presence changes
802+ - ` WebhookEvent.CHATS_SET ` - Initial chats load
803+ - ` WebhookEvent.CHATS_UPDATE ` - Chat updates
804+ - ` WebhookEvent.CHATS_UPSERT ` - New chats
805+ - ` WebhookEvent.CHATS_DELETE ` - Chat deletions
806+ - ` WebhookEvent.GROUPS_UPSERT ` - New groups
807+ - ` WebhookEvent.GROUPS_UPDATE ` - Group updates
808+ - ` WebhookEvent.GROUP_PARTICIPANTS_UPDATE ` - Group member changes
809+ - ` WebhookEvent.NEW_TOKEN ` - JWT token updates
810+
811+ #### Configure Webhook URL
812+
813+ Don't forget to configure your webhook URL in the Evolution API:
814+
815+ ``` ts
816+ // Set your webhook endpoint
817+ await client .webhook .set ({
818+ url: " https://your-domain.com/webhook" ,
819+ webhook_by_events: true ,
820+ events: [
821+ " MESSAGES_UPSERT" ,
822+ " MESSAGES_UPDATE" ,
823+ " CONNECTION_UPDATE" ,
824+ " CONTACTS_UPSERT" ,
825+ ],
826+ });
827+ ```
828+
558829## API Documentation
559830
560831Check the [ official API documentation] ( https://doc.evolution-api.com/v2 ) for more information about their service.
0 commit comments