Explore how to connect WhatsApp to OpenAI using Z-API and Node.js. This example receives messages through a webhook, generates AI responses, and sends them back to WhatsApp.
This example uses the retired OpenAI model text-davinci-003. Update the OpenAI integration in index.js to a supported model and compatible API request format before testing AI responses.
See the OpenAI documentation for current integration guidance.
- Node.js and npm installed.
- A Z-API instance connected to WhatsApp.
- An OpenAI API key.
- A public HTTPS URL for receiving webhooks. For local development, you can use ngrok.
git clone https://github.com/Z-API/chat-gpt-example.git
cd chat-gpt-examplenpm installCreate a .env file in the project root:
OPEN_AI_API_KEY=your_openai_api_key
Z_API_INSTANCE_ID=your_zapi_instance_id
Z_API_INSTANCE_TOKEN=your_zapi_instance_tokenGet your instance credentials from your Z-API account and your API key from the OpenAI platform.
Keep your credentials private and do not commit your .env file.
npm startFor development with automatic restarts:
npm run devThe server listens on port 3000.
For local testing, install and configure ngrok, then expose port 3000:
ngrok http 3000Copy the public HTTPS URL provided by ngrok and append /on-new-message:
https://YOUR-NGROK-DOMAIN/on-new-message
Set this address as the received-message webhook in your Z-API instance.
Keep the application and ngrok running while testing. If your tunnel URL changes, update the webhook address in Z-API.
After updating the OpenAI integration and completing the setup:
- Send
!gptfrom another WhatsApp account to the number connected to your Z-API instance. - Wait for the welcome message.
- Send a text message to continue the conversation.
- Z-API forwards an incoming WhatsApp message to
/on-new-message. - The application starts a chat session when it receives
!gpt. - Subsequent text messages are sent to OpenAI.
- The generated response is sent back through Z-API.
- Conversations are stored in memory and are lost when the application restarts.
- The welcome and error messages are in Portuguese and can be customized in
index.js. - This is a learning example. Review API compatibility, authentication, error handling, and persistent storage before adapting it for production.