### Node.js Key Generation and Server Setup Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Commands to generate encryption keys, set up environment variables, and install dependencies for a Node.js example. ```bash # Generate keys node examples/endpoint/nodejs/basic/src/keyGenerator.js my-passphrase # Setup .env cat > .env << EOF PRIVATE_KEY="..." PASSPHRASE="my-passphrase" APP_SECRET="..." PORT="3000" EOF # Install and start npm install npm start ``` -------------------------------- ### Generate Keys, Configure Environment, and Start Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-nodejs.md A bash script demonstrating the steps to generate cryptographic keys, set up the .env file with necessary secrets, install dependencies, and start the Node.js server. ```bash # 1. Generate keys node src/keyGenerator.js my-passphrase # 2. Create .env file with generated keys and APP_SECRET cat > .env << EOF APP_SECRET="your-app-secret" PRIVATE_KEY="..." PASSPHRASE="my-passphrase" PORT="3000" EOF # 3. Install dependencies npm install # 4. Start server npm start # Server is listening on port: 3000 ``` -------------------------------- ### Environment Variables Example (.env file) Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-nodejs.md Provides an example of how to configure environment variables for the server, including APP_SECRET, PRIVATE_KEY, PASSPHRASE, and PORT. ```bash APP_SECRET="your-app-secret" PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-INFO: DES-EDE3-CBC,ABC123... MIIE... -----END RSA PRIVATE KEY-----" PASSPHRASE="your-passphrase" PORT="3000" ``` -------------------------------- ### Start Endpoint Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Commands to start the endpoint server for different languages. Node.js requires npm installation. ```bash # Node.js npm install && npm start ``` ```bash # Go go run main.go ``` ```bash # C# dotnet run ``` -------------------------------- ### Running the Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md Commands to install dependencies and run the Go server. The server will listen on port 3000. ```bash # Install dependencies go get github.com/gin-gonic/gin # Run go run main.go # Output: # [GIN-debug] Loaded HTML Templates (0): # [GIN-debug] Listening and serving HTTP on :3000 ``` -------------------------------- ### Go Server Execution Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Environment variables and command to run the Go example. ```bash export PRIVATE_KEY="..." export PASSPHRASE="..." go run main.go ``` -------------------------------- ### Logging Examples Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md Examples of using Go's standard log package for error logging and fmt.Printf for debug output. Debug logging is recommended for troubleshooting. ```go log.Print(err) // Error logging fmt.Printf(...) // Debug output ``` -------------------------------- ### Python Flask Dependencies and Execution Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Commands to install necessary Python packages and run the Python example. ```bash pip install flask python-dotenv requests python articles/creating-surveys/main.py ``` -------------------------------- ### Environment Setup: Go Module Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md Defines the Go module name and version, and lists the required dependencies for the project. ```go module flows-endpoint go 1.21 require github.com/gin-gonic/gin v1.9.1 ``` -------------------------------- ### Webhook Setup with ngrok Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Steps to set up a webhook listener using Node.js and expose it publicly using ngrok. ```bash # Terminal 1: Start webhook npm start # Terminal 2: Expose with ngrok ngrok http 3000 # Terminal 3: Configure in WhatsApp Business Manager # Callback URL: https://xxx.ngrok.io/webhook # Verify Token: your-token ``` -------------------------------- ### Environment Variables Example (.env file) Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Example of how to configure environment variables for the webhook server. These include tokens for verification and API access, and optional settings for port and flow ID. ```bash WEBHOOK_VERIFY_TOKEN="your-secure-token-123" GRAPH_API_TOKEN="EAA..." FLOW_ID="1234567890" PORT="3000" ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Installs necessary Python packages for the project using pip. ```bash pip install flask python-dotenv requests ``` -------------------------------- ### Verify Webhook Setup Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/endpoints.md This endpoint is used to verify the webhook setup with WhatsApp. It requires a token for verification. ```APIDOC ## GET /webhook ### Description Verifies the webhook setup with WhatsApp. ### Method GET ### Endpoint /webhook ### Parameters #### Query Parameters - **token** (string) - Required - The verify token provided during webhook configuration. - **challenge** (string) - Required - A challenge string sent by WhatsApp. - **mode** (string) - Required - Should be "subscribe". ### Response #### Success Response (200) - **challenge** (string) - The challenge string received from WhatsApp, used to confirm verification. ``` -------------------------------- ### Webhook Verification Request Example Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md This GET request is used during initial setup to verify webhook token ownership. Ensure your verify_token matches the one configured in your WhatsApp Cloud API settings. ```http GET /webhook?hub.mode=subscribe&hub.verify_token=my_token&hub.challenge=abc123 ``` -------------------------------- ### Environment Setup: .env File Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md Configuration for the server endpoint, including the private RSA key and its passphrase. Ensure these are kept secure. ```bash PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-INFO: DES-EDE3-CBC,ABC123... MIIE... -----END RSA PRIVATE KEY-----" PASSPHRASE="your-secure-passphrase" ``` -------------------------------- ### Node.js Flow Handler Example Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example demonstrating screen routing and request handling for Node.js flows. This is part of the core flow logic. ```javascript // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for a Node.js flow handler would manage the state and routing of the user through the flow. ``` -------------------------------- ### Set up Local Webhook Testing with ngrok Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Provides commands to start the server and expose it locally using ngrok for integration testing. This allows testing the webhook configuration with external services. ```bash # Terminal 1: Start server npm start # Terminal 2: Expose with ngrok ngrok http 3000 # Terminal 3: Configure webhook # Use ngrok URL in WhatsApp Business Manager # Send test message in WhatsApp ``` -------------------------------- ### Example Command to Generate Keys Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/key-generator-nodejs.md Demonstrates the command-line execution of the key generator with a specific passphrase. Ensure you use a strong, unique passphrase for security. ```bash node src/keyGenerator.js my-secure-passphrase-12345 ``` -------------------------------- ### Webhook Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Receives WhatsApp events and verifies webhook setup. ```APIDOC ## POST /webhook ### Description Receives incoming WhatsApp events. ### Method POST ### Endpoint /webhook ### Auth None ## GET /webhook ### Description Verifies the webhook setup with a challenge. ### Method GET ### Endpoint /webhook ### Auth Token ``` -------------------------------- ### Verify Endpoint Setup Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Curl command to test if the flow endpoint server is running and accessible. ```bash curl http://localhost:3000/ ``` -------------------------------- ### Survey Processing Example Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Shows an example of extracting individual survey response IDs from the parsed flow data, such as source, tour type, and quality. ```python # Extract each response source_id = flow_data["source"] tour_type_id = flow_data["tour_type"] tour_quality_id = flow_data["tour_quality"] # ... etc ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/examples/endpoint/nodejs/basic/README.md Sets the environment variables for the passphrase and private key. Ensure multiline keys have correct line breaks. ```bash PASSPHRASE="my-secret" PRIVATE_KEY="-----[REPLACE THIS] BEGIN RSA PRIVATE KEY----- MIIE... ... ... xyz -----[REPLACE THIS] END RSA PRIVATE KEY-----" ``` -------------------------------- ### GET /webhook Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Webhook verification endpoint used during initial setup to verify the webhook token and confirm endpoint ownership. ```APIDOC ## GET /webhook ### Description Verifies webhook token to confirm endpoint ownership. Required by WhatsApp before webhook accepts events. ### Method GET ### Endpoint /webhook ### Parameters #### Query Parameters - **hub.mode** (string) - Required - subscribe - **hub.verify_token** (string) - Required - Token to verify webhook - **hub.challenge** (string) - Required - Challenge string from WhatsApp ### Response #### Success Response (200) **Body:** The challenge string (if successful) #### Error Response (403) **Description:** If token mismatch. ### Example Request ``` GET /webhook?hub.mode=subscribe&hub.verify_token=my_token&hub.challenge=abc123 ``` ### Response Example ```http HTTP/1.1 200 OK abc123 ``` ``` -------------------------------- ### Go Server Endpoint Implementation Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of a Gin framework endpoint implementation for Go. This handles incoming requests from WhatsApp. ```go // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for a Gin framework endpoint would define routes and handle HTTP requests. ``` -------------------------------- ### Example Flow Handler Logic Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/errors.md Demonstrates how to handle different request actions ('ping', 'INIT', 'data_exchange') and screens within a flow. Throws an error for unhandled requests. ```javascript export const getNextScreen = async (decryptedBody) => { const { screen, action } = decryptedBody; if (action === "ping") { return { data: { status: "active" } }; } if (action === "INIT") { return { screen: "MY_SCREEN", data: {...} }; } if (action === "data_exchange") { switch (screen) { case "MY_SCREEN": return { screen: "SUCCESS", data: {...} }; default: break; } } console.error("Unhandled request body:", decryptedBody); throw new Error( "Unhandled endpoint request. Make sure you handle the request action & screen logged above." ); }; ``` -------------------------------- ### Node.js Flow Handler Example Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/flow-handler-nodejs.md Demonstrates how to use the getNextScreen function to handle initial flow opening, user data submission, and health checks. ```javascript import { getNextScreen } from './flow.js'; // Handle initial flow open const initResponse = await getNextScreen({ action: "INIT", flow_token: "token-123" }); // Returns: { screen: "MY_SCREEN", data: { greeting: "Hey there! 👋" } } // Handle user data submission const nextResponse = await getNextScreen({ screen: "MY_SCREEN", action: "data_exchange", data: { name: "John" }, flow_token: "token-123" }); // Returns: { screen: "SUCCESS", data: { ... } } // Handle health check const healthResponse = await getNextScreen({ action: "ping" }); // Returns: { data: { status: "active" } } ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/key-generator-nodejs.md Illustrates how to configure the PASSPHRASE and PRIVATE_KEY environment variables in a .env file after generating the keys. Protect your private key by not committing the .env file to version control. ```bash PASSPHRASE="your-passphrase" PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----" ``` -------------------------------- ### C# Endpoint Configuration Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Example of configuring environment variables for C# flow endpoint servers within an appsettings.json file. ```json { "PRIVATE_KEY": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", "PASSPHRASE": "my-secure-passphrase-123" } ``` -------------------------------- ### Configure Environment Variables in JSON Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/encryption-csharp.md Example of how to set environment variables like PRIVATE_KEY and PASSPHRASE within a JSON configuration file, such as launchSettings.json or appsettings.json. ```json { "PRIVATE_KEY": "-----BEGIN RSA PRIVATE KEY-----\n...", "PASSPHRASE": "your-passphrase" } ``` -------------------------------- ### Instantiate PasswordFinder Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/encryption-csharp.md Example of creating a new PasswordFinder instance with a specific passphrase. This is used when initializing a PemReader. ```csharp new PasswordFinder("my-passphrase") ``` -------------------------------- ### Endpoint Returns Initial Screen (JavaScript) Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/flow-lifecycle.md Example JavaScript code for an endpoint to construct the response for the initial screen of a WhatsApp Flow, based on the 'INIT' action. ```javascript if (action === "INIT") { return { screen: "FIRST_SCREEN", data: { title: "Welcome", message: "Please select your options", options: [ { id: "opt1", title: "Option 1" }, { id: "opt2", title: "Option 2" } ] } }; } ``` -------------------------------- ### Example Request Flow (Client to Server) Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-nodejs.md Illustrates the structure of an HTTP POST request from a client (WhatsApp) to the server endpoint, including headers and the encrypted JSON body. ```javascript // Client (WhatsApp) POST / HTTP/1.1 Content-Type: application/json X-Hub-Signature-256: sha256=abc123... { "encrypted_aes_key": "MIGfMA0GCS...", "encrypted_flow_data": "CjLaHz5...", "initial_vector": "K7mQ8Lx..." } // Server responds HTTP/1.1 200 OK Content-Type: text/plain MxE2R5f9Jk... ``` -------------------------------- ### Example Output of Key Generation Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/key-generator-nodejs.md Shows the expected output when the key generator successfully creates a public and private key pair. This includes the passphrase, private key, and public key, which should be copied to your .env file and uploaded to WhatsApp Business Manager respectively. ```text Successfully created your public private key pair. Please copy the below values into your /.env file ************* COPY PASSPHRASE & PRIVATE KEY BELOW TO .env FILE ************* PASSPHRASE="my-secure-passphrase-12345" PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,ABC123DEF456 MIIE...JwEBAg== -----END RSA PRIVATE KEY-----" ************* COPY PASSPHRASE & PRIVATE KEY ABOVE TO .env FILE ************* ************* COPY PUBLIC KEY BELOW ************* -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBIgKCAQEA0x... -----END PUBLIC KEY----- ************* COPY PUBLIC KEY ABOVE ************* ``` -------------------------------- ### Go Endpoint Environment Variables Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Example of exporting environment variables for Go flow endpoint servers. ```bash export PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----" export PASSPHRASE="my-secure-passphrase-123" ``` -------------------------------- ### Gin Server Startup and Handler Registration Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md This snippet initializes the Gin router, registers the POST / handler, and starts the server to listen on port 3000. It assumes the handler function `processRequest` and necessary variables are defined elsewhere. ```go r := gin.Default() r.POST("/", func(c *gin.Context) { encryptedResponse, err := processRequest(c, privateKey, passphrase) if err != nil { log.Print(err) c.String(500, "Internal Server Error") return } c.String(200, encryptedResponse) }) r.Run(":3000") // Listen on port 3000 ``` -------------------------------- ### GET /webhook Route for Verification Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Implements the webhook verification endpoint for GET requests. It checks the incoming query parameters against the configured VERIFY_TOKEN and returns the challenge string if they match, ensuring the webhook is correctly set up. ```python @app.route("/webhook", methods=["GET"]) def webhook_get(): if (request.args.get("hub.mode") == "subscribe" and request.args.get("hub.verify_token") == VERIFY_TOKEN): return make_response(request.args.get("hub.challenge"), 200) else: return make_response("Success", 403) ``` -------------------------------- ### Go Encryption and Decryption Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of RSA and AES encryption/decryption for Go. This is used for securing flow data. ```go // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for encryption/decryption in Go would involve using standard library packages or third-party libraries. ``` -------------------------------- ### Node.js Server Endpoint Implementation Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of an Express.js endpoint implementation for Node.js. This handles incoming requests from WhatsApp. ```javascript // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for an Express.js endpoint would set up routes, middleware, and handle request/response cycles. ``` -------------------------------- ### Setup Webhook Environment Variables Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Configure these environment variables for your webhook server to receive and process flow completions. A GRAPH_API_TOKEN is required for sending confirmations. ```bash WEBHOOK_VERIFY_TOKEN="your-secure-token" GRAPH_API_TOKEN="EAA..." FLOW_ID="1234567890" ``` -------------------------------- ### Environment Variables for WhatsApp Tools Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/endpoints.md This bash snippet shows example environment variables that should be used for securing WhatsApp API credentials. Never commit these to version control. ```bash # .env (never commit) PRIVATE_KEY="..." PASSPHRASE="..." APP_SECRET="..." GRAPH_API_TOKEN="..." WEBHOOK_VERIFY_TOKEN="..." WHATSAPP_BUSINESS_ACCOUNT_ID="..." ``` -------------------------------- ### Flows Webhook - Response Handling Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Example logic for processing a flow response (nfm_reply) and sending a confirmation message. ```APIDOC ### Response Handling ```javascript if ( message.type === "interactive" && message.interactive?.type === "nfm_reply" ) { // Process flow response const flowResponse = message.interactive.nfm_reply.response_json; // Send confirmation message } ``` Detects flow completion (nfm_reply = "native flow message reply") and sends confirmation. ``` -------------------------------- ### Local Webhook Testing with ngrok Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Use ngrok to expose your local server to the internet for testing webhooks. After starting ngrok, register the provided URL with your WhatsApp Business account. ```bash ngrok http 3000 # Register webhook with ngrok URL # Send test messages in WhatsApp ``` -------------------------------- ### Node.js Webhook Environment Variables Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Example of required and optional environment variables for a Node.js webhook server, stored in a .env file. ```bash # Required WEBHOOK_VERIFY_TOKEN="my-secure-verification-token" GRAPH_API_TOKEN="EAAxxx..." # Optional FLOW_ID="1234567890" PORT="3000" ``` -------------------------------- ### Python Webhook Environment Variables Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Example of required and optional environment variables for a Python webhook server, stored in a .env file. ```bash # Required VERIFY_TOKEN="my-secure-verification-token" ACCESS_TOKEN="EAAxxx..." # Optional for flow creation PHONE_NUMBER_ID="1234567890" WHATSAPP_BUSINESS_ACCOUNT_ID="100..." ``` -------------------------------- ### Common Request Routing Logic Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Illustrates the typical action-based routing pattern used across examples to handle different request types and states. ```javascript if (action === "ping") → return health check else if (data?.error) → return acknowledgment else if (action === "INIT") → return first screen else if (action === "data_exchange") → switch on screen name → return next screen else → throw error ``` -------------------------------- ### Python Webhook Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of a Flask webhook server in Python with flow management capabilities. This handles incoming events from WhatsApp. ```python # This is a placeholder for actual code examples that would be found in the API reference. # The actual code for a Python Flask webhook server would define routes to handle incoming requests and manage flow states. ``` -------------------------------- ### Docker Configuration for Production Deployment Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md A Dockerfile to build a production-ready image for the Node.js application. It installs dependencies, copies source code, and sets environment variables. ```dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY src ./src ENV NODE_ENV=production ENV PORT=3000 EXPOSE 3000 CMD ["node", "src/server.js"] ``` -------------------------------- ### Python Programmatic Flow Creation and Webhook Handling Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Complete example in Python for creating flows programmatically via the Graph API, handling webhook responses, and processing survey data. ```python 1. create_flow() → Creates flow, uploads JSON, publishes 2. send_flow() → Sends to user when triggered 3. webhook receives nfm_reply → flow_reply_processor() 4. flow_reply_processor() → Maps response IDs to labels 5. send_message() → Sends confirmation with results ``` ```python match source_id: case "0": source = "Online search" case "1": source = "Social media" case "2": source = "Referral" # ... map all possible values reply = f"Thanks for the survey!\n{source}\n{tour_type}\n..." send_message(reply, user_phone) ``` -------------------------------- ### Node.js/Python Endpoint Environment Variables Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Example of required and optional environment variables for Node.js or Python flow endpoint servers, stored in a .env file. ```bash # Required PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,ABC123DEF456 MIIE+JO... -----END RSA PRIVATE KEY-----" PASSPHRASE="my-secure-passphrase-123" # Optional APP_SECRET="your-app-secret-from-meta" PORT="3000" ``` -------------------------------- ### API Endpoint Setup for Encryption/Decryption Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/encryption-csharp.md Sets up a minimal ASP.NET Core API endpoint that handles POST requests. It decrypts incoming data using provided environment variables for private key and passphrase, then encrypts and returns a response. ```csharp var app = WebApplication.CreateBuilder(args).Build(); var PRIVATE_KEY = Environment.GetEnvironmentVariable("PRIVATE_KEY") ?? throw new InvalidOperationException("PRIVATE_KEY not set"); var PASSPHRASE = Environment.GetEnvironmentVariable("PASSPHRASE") ?? throw new InvalidOperationException("PASSPHRASE not set"); app.MapPost("/", (EndpointPayload body) => { var decrypted = EncryptionUtils.DecryptRequest( body.encrypted_aes_key, body.encrypted_flow_data, body.initial_vector, PRIVATE_KEY, PASSPHRASE ); var action = decrypted.decryptedBody.GetProperty("action").GetString(); var response = new { screen = "SCREEN_NAME", data = new { some_key = "some_value" } }; var encryptedResponse = EncryptionUtils.EncryptResponse( response, decrypted.aesKeyBytes, decrypted.initialVectorBytes ); return Results.Content(encryptedResponse, "text/plain"); }) .WithName("PostEndpointData"); app.Run(); ``` -------------------------------- ### Node.js Webhook: Triggering Flows and Processing Responses Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Handles incoming messages to trigger WhatsApp flows and process replies. This example demonstrates basic webhook integration for flow automation. ```javascript // Trigger logic if (message.text.body.toLowerCase().includes("appointment")) { await sendFlow(message.from, FLOW_ID); } // Response processing if (message.interactive?.type === "nfm_reply") { await sendConfirmation(message.from); } // Read receipt await markAsRead(message.id); ``` -------------------------------- ### Server Startup Command Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md This bash command demonstrates how to set the required environment variables and run the Go Flows endpoint server. Ensure you replace '...' with your actual private key. ```bash export PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- ... " export PASSPHRASE="my-passphrase" go run main.go ``` -------------------------------- ### Postman Webhook Test Collection Example Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md An example JSON structure for a Postman request to test the webhook endpoint. It includes the method, URL, headers, and a sample request body. ```json { "POST": "{{webhook_url}}/webhook", "Headers": { "Content-Type": "application/json" }, "Body": { "entry": [{ "changes": [{ "value": { "messages": [{ "type": "text", "from": "1234567890", "text": { "body": "test" } }] } }] }] } } ``` -------------------------------- ### GET / Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Health check route for the webhook server. ```APIDOC ## GET / ### Description Health check route. ### Method GET ### Endpoint / ### Response #### Success Response **Body:** HTML content indicating the service is running. ```html
Nothing to see here. Checkout README.md to start.``` ``` -------------------------------- ### Server Initialization with Express.js Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-nodejs.md Sets up an Express.js server to handle incoming WhatsApp Flows requests. Includes middleware for parsing JSON and storing the raw request body for signature verification. ```javascript import express from "express"; import { decryptRequest, encryptResponse } from "./encryption.js"; import { getNextScreen } from "./flow.js"; const app = express(); // Middleware: parse JSON and store raw body for signature verification app.use( express.json({ verify: (req, res, buf, encoding) => { req.rawBody = buf?.toString(encoding || "utf8"); }, }), ); // Main endpoint app.post("/", async (req, res) => { // ... request handling }); // Health check app.get("/", (req, res) => { res.send(`
Nothing to see here.\nCheckout README.md to start.`); }); app.listen(PORT, () => { console.log(`Server is listening on port: ${PORT}`); }); ``` -------------------------------- ### Node.js Encryption and Decryption Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of RSA and AES encryption/decryption for Node.js. This is used for securing flow data. ```javascript // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for encryption/decryption in Node.js would involve using libraries like 'crypto'. ``` -------------------------------- ### PemReader Initialization with PasswordFinder Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/encryption-csharp.md Demonstrates how to initialize a PemReader with a StringReader for PEM content and a PasswordFinder for the passphrase. This is crucial for decrypting private keys. ```csharp var pemReader = new PemReader( new StringReader(privatePem), new PasswordFinder(passphrase) ); ``` -------------------------------- ### Error Handling with FlowEndpointException Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Example of try-catch block for handling potential decryption errors, specifically catching FlowEndpointException. ```javascript try { const decrypted = decryptRequest(...); } catch (err) { if (err instanceof FlowEndpointException) { return res.status(err.statusCode).send(); } return res.status(500).send(); } ``` -------------------------------- ### INIT Action Sequence Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/flow-lifecycle.md Details the request and response sequence for initiating a WhatsApp Flow. Includes encryption methods and the initial `getNextScreen` call. ```text 1. Client → Endpoint (INIT request, AES key encrypted with RSA) 2. Endpoint decrypts with private key 3. Endpoint calls getNextScreen(action: "INIT") 4. Endpoint → Client (first screen, encrypted with AES) ``` -------------------------------- ### WhatsApp Text Message Payload Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/endpoints.md This is an example of a JSON payload for sending a text message via the WhatsApp Cloud API. ```json { "messaging_product": "whatsapp", "to": "1234567890", "type": "text", "text": { "preview_url": false, "body": "Hello world" } } ``` -------------------------------- ### Configure HTTPS Server Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Sets up an HTTPS server using environment variables for SSL certificate paths. This is crucial for production environments. ```javascript // Use environment variables for SSL certificates const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync(process.env.SSL_KEY_PATH), cert: fs.readFileSync(process.env.SSL_CERT_PATH) }; https.createServer(options, app).listen(443); ``` -------------------------------- ### Endpoint Initialization Processing Logic Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/flow-lifecycle.md Illustrates the server-side processing steps for an incoming flow initialization request, including signature validation, decryption, and determining the first screen. ```text 1. Validate X-Hub-Signature-256 header with APP_SECRET ├─ If invalid → Return 432 (Invalid Signature) └─ Continue 2. Decrypt encrypted_aes_key with PRIVATE_KEY (RSA) ├─ If failed → Return 421 (Key Expired) └─ Store decrypted AES key 3. Decrypt encrypted_flow_data with AES key + IV (AES-128-GCM) ├─ If failed → Return 500 (Server Error) └─ Parse decrypted JSON 4. Extract from decrypted body: ├─ action: "INIT" ├─ flow_token: "unique-token-123" └─ version: 1 5. Call getNextScreen({action: "INIT", ...}) └─ Returns first screen configuration ``` -------------------------------- ### C# Encryption and Decryption Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of RSA and AES encryption/decryption using BouncyCastle in C#. This is used for securing flow data. ```csharp // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for encryption/decryption in C# would involve using libraries like BouncyCastle. ``` -------------------------------- ### C# .NET Application Execution Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Instructions to run the C# .NET application, noting the need to configure environment variables. ```bash # Set environment variables in launchSettings.json or appsettings.json dotnet run ``` -------------------------------- ### Summary/Review Screen Configuration Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Configures a screen to display a summary or review of information. Use this to present collected data back to the user before final submission. ```javascript { screen: "SUMMARY", data: { title: "Review Your Information", name: "John Doe", email: "john@example.com" } } ``` -------------------------------- ### Flask App Initialization and Environment Loading Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Initializes a Flask application and loads environment variables for WhatsApp API credentials and configuration. Ensure your .env file contains PHONE_NUMBER_ID, VERIFY_TOKEN, ACCESS_TOKEN, and WHATSAPP_BUSINESS_ACCOUNT_ID. ```python from flask import Flask, json, make_response, request from dotenv import load_dotenv import requests import os import uuid app = Flask(__name__) load_dotenv() PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID") VERIFY_TOKEN = os.getenv("VERIFY_TOKEN") ACCESS_TOKEN = os.getenv("ACCESS_TOKEN") WHATSAPP_BUSINESS_ACCOUNT_ID = os.getenv("WHATSAPP_BUSINESS_ACCOUNT_ID") ``` -------------------------------- ### Basic Error Handling with Try-Except Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Illustrates a basic try-except block for handling potential errors during flow creation and API responses. Recommends more detailed logging for production. ```python try: created_flow_id = flow_create_response.json()["id"] # ... rest of creation return make_response("FLOW CREATED", 200) except: return make_response("ERROR", 500) ``` -------------------------------- ### Webhook Verification Endpoint Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Handles the GET request for webhook verification. It checks the mode and verify token, responding with the challenge if valid. ```javascript app.get("/webhook", (req, res) => { if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === WEBHOOK_VERIFY_TOKEN) { res.status(200).send(req.query["hub.challenge"]); } else { res.sendStatus(403); } }); ``` -------------------------------- ### Health Check Endpoint Response Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/endpoints.md The response body for the GET / health check endpoint. This is plain text and indicates the server is running. ```html
Nothing to see here. Checkout README.md to start.``` -------------------------------- ### Flows Webhook - Trigger Logic Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-nodejs.md Example logic for sending a flow message when a user's text message contains the keyword 'appointment'. ```APIDOC ### Trigger Logic ```javascript if ( message.type === "text" && message.text.body.toLowerCase().includes("appointment") ) { // Send flow message } ``` Sends a flow message when user's text contains "appointment". ``` -------------------------------- ### Creating Response Map Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-go.md This snippet shows how to construct the response map, which will be encrypted and sent back to the client. It includes a 'screen' field and a 'data' map. ```go response := map[string]interface{}{ "screen": "SCREEN_NAME", "data": map[string]string{"some_key": "some_value"}, } ``` -------------------------------- ### Node.js Webhook Handlers Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/README.md Example of webhook handlers for Node.js, including integration with the Graph API. This is used to process flow completion events. ```javascript // This is a placeholder for actual code examples that would be found in the API reference. // The actual code for Node.js webhook handlers would parse incoming events and interact with the WhatsApp Graph API. ``` -------------------------------- ### GET /webhook Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Webhook verification endpoint. Responds with the challenge string if the verification token matches, otherwise returns a 403 Forbidden status. ```APIDOC ## GET /webhook ### Description Webhook verification endpoint used by WhatsApp to verify the webhook subscription. It checks for the presence of `hub.mode`, `hub.verify_token`, and `hub.challenge` parameters. ### Method GET ### Endpoint /webhook ### Parameters #### Query Parameters - **hub.mode** (string) - Required - Must be 'subscribe'. - **hub.verify_token** (string) - Required - The verification token configured for the webhook. - **hub.challenge** (string) - Required - A random string to be echoed back. ### Response #### Success Response (200) - **Body**: Challenge string (if verification succeeds) #### Error Response (403) - **Body**: "Success" (if verification fails) ``` -------------------------------- ### GET / - Health Check Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/server-endpoint-nodejs.md A simple health check endpoint that returns a static message. It does not perform any active checks but indicates the server is running. ```APIDOC ## GET / ### Description Health check endpoint that displays a welcome message. Useful for verifying the server is operational. ### Method GET ### Endpoint / ### Response #### Success Response - **Body** (string) - HTML content with a preformatted message. #### Response Example ```html
Nothing to see here. Checkout README.md to start.``` ``` -------------------------------- ### Project File Structure Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Outlines the required file structure for the project, including the main Python script, flow JSON definition, and environment variables file. ```text project/ ├── main.py ├── survey.json # Flow JSON definition ├── .env # Environment variables └── requirements.txt ``` -------------------------------- ### State Propagation in Screen Responses Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/examples-guide.md Demonstrates how to propagate state by including previous user selections and new data when transitioning between screens. ```javascript case "SCREEN_1": return { ...SCREEN_RESPONSES.SCREEN_2, data: { ...SCREEN_RESPONSES.SCREEN_2.data, // Include previous user selections prev_selection: data.selection, // Add new data for this screen options: generateOptions(data.selection) } }; ``` -------------------------------- ### Load Environment Variables and Initialize Flask App Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Initializes a Flask application and loads environment variables using dotenv. It retrieves essential configuration like PHONE_NUMBER_ID and ACCESS_TOKEN. ```python from flask import Flask from dotenv import load_dotenv import os app = Flask(__name__) load_dotenv() PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID") ACCESS_TOKEN = os.getenv("ACCESS_TOKEN") messaging_url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages" ``` -------------------------------- ### Form/Input Screen Configuration Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/configuration.md Configures a screen for user input, defining fields and their properties. Use this for collecting data from the user. ```javascript { screen: "INPUT_SCREEN", data: { field1: [ { id: "value1", title: "Label 1" }, { id: "value2", title: "Label 2" } ], field2_enabled: false // Toggle field availability } } ``` -------------------------------- ### POST /create-flow Route Implementation Source: https://github.com/whatsapp/whatsapp-flows-tools/blob/main/_autodocs/api-reference/webhook-python.md Handles the creation and initial upload of a new WhatsApp flow. This endpoint is triggered via a POST request and returns 'FLOW CREATED' on success or 'ERROR' on failure. It requires the ACCESS_TOKEN and WHATSAPP_BUSINESS_ACCOUNT_ID environment variables. ```python @app.route("/create-flow", methods=["POST"]) def create_flow(): flow_base_url = f"https://graph.facebook.com/v18.0/{WHATSAPP_BUSINESS_ACCOUNT_ID}/flows" flow_creation_payload = { "name": "