Receiving WhatsApp Messages in NestJS via AWS SNS - code-examples -

Frequently Asked Questions

Receive WhatsApp messages in your NestJS application by integrating with AWS SNS and End User Messaging Social. This involves setting up an SNS topic, connecting your WhatsApp Business Account (WABA) through AWS End User Messaging Social, and configuring your NestJS application to listen for incoming messages via an HTTPS webhook endpoint subscribed to the SNS topic. This architecture decouples your application logic from direct WhatsApp integration complexities.
AWS End User Messaging Social connects your Meta Business Portfolio, including your WhatsApp Business Account (WABA), to your AWS account. It simplifies the integration of WhatsApp with AWS services, streamlines billing, and acts as a bridge between the Meta/WhatsApp platform and AWS infrastructure like SNS for receiving incoming messages.
AWS SNS provides a scalable and manageable way to handle incoming WhatsApp messages by acting as a message bus. It decouples your NestJS application from the direct complexities of managing WebSocket connections or Meta's Webhook infrastructure, allowing developers to focus on business logic.
Always use IAM roles for AWS credentials in production environments. Avoid hardcoding credentials in your application code or storing them in .env files, which pose security risks. IAM roles assigned to your compute resources allow the AWS SDK to automatically retrieve credentials securely.
After creating the SNS subscription, AWS will send a 'SubscriptionConfirmation' message to your NestJS application's webhook endpoint. Your application must extract the 'SubscribeURL' from this message and make an HTTP GET request to that URL. This confirms ownership of the endpoint and enables SNS to send notifications.
The body-parser middleware is essential for parsing the raw text body of incoming SNS messages, which contain the WhatsApp data. Since SNS sends messages with 'Content-Type: text/plain', configuring body-parser to handle this format is crucial for your NestJS application to correctly receive and process the message content.
The 'Message' field within the SNS notification contains the WhatsApp payload as a JSON string, including the message type (e.g., 'text', 'image', 'interactive'). Parse this JSON string in your NestJS application to access the message type and handle each type appropriately based on your application's logic. The guide provides an example of extracting the sender, message type, and text content.
SNS message signature validation is a crucial security measure to ensure that incoming messages are genuinely from AWS and not forged by attackers. The 'sns-validator' library verifies the message signature against the certificate provided by AWS, preventing the processing of fraudulent messages. Never skip this step.
Implement robust error handling using try-catch blocks and the NestJS Logger to log errors effectively. Distinguish between errors that prevent acknowledgment to SNS (like invalid signatures) and processing failures. For the latter, acknowledge receipt to avoid excessive retries but log the error for investigation. Consider using dead-letter queues (DLQs) for messages that consistently fail delivery.
A suggested schema includes columns for various message attributes, including SNS and WhatsApp message IDs, sender and recipient numbers, timestamps, message type and body, media information (if applicable), raw payload, processing status, and creation/update timestamps. This allows for structured storage and retrieval of incoming WhatsApp messages and related data.
You can test the basic route and parsing functionality with tools like curl or Postman, but proper signature verification requires a valid signed message from SNS, typically only possible in a real integration scenario. Focus on unit testing the processing logic or testing the fully deployed setup for comprehensive testing.
You must grant AWS End User Messaging Social permission to publish to your SNS topic by modifying the topic's Access Policy. Add a statement allowing the 'eum.amazonaws.com' service principal to perform the 'sns:Publish' action on your specific topic ARN. Include a condition to restrict access based on your AWS account ID for enhanced security.
The 'Message' field in the SNS notification contains the actual WhatsApp message payload as a JSON string. This string must be parsed to access the message content, including the sender's number, the message text, and other metadata. The article includes an example of the 'Message' field's structure and how to parse it within your NestJS application.
HTTPS is mandatory for the NestJS webhook endpoint because SNS requires secure communication for delivering messages. SNS will not send notifications to HTTP endpoints. This ensures message confidentiality and integrity in transit, protecting sensitive data.