top of page
Writer's pictureFaysal Jaali

Leveraging AI: Integrating Wix Chat with ChatGPT

Updated: Oct 10


how to integrate Chatgpt to Wix Chat App


In the modern digital landscape, engaging with your audience in real-time is paramount for delivering exceptional customer service. This is where integrating a cutting-edge AI like ChatGPT with your Wix Chat can be a game changer. In this article, we'll guide you through the steps required to seamlessly integrate ChatGPT with your Wix Chat on your website.


Before we go further, we invite you first to explore and interact with our live demo to experience firsthand the seamless integration of Wix Chat with ChatGPT.


Introduction to ChatGPT

ChatGPT is an AI language model developed by OpenAI, capable of understanding and generating human-like text. It can handle a wide array of queries, making it an ideal companion for your Wix chat system.


Benefits of Integration

  1. Real-time Responses: With ChatGPT, you can provide instant answers to customer queries, enhancing user experience.

  2. Cost Efficiency: Automating customer service can significantly reduce operational costs.

  3. 24/7 Availability: ChatGPT ensures that your business is responsive around the clock, even during off-hours.


Step 1: Install Wix Chat

  • If you haven’t already, add Wix Chat to your website via the Wix App Market.



add Wix Chat app screenshot



Step 2: Create a ChatGPT Account


1.1 Visit the OpenAI Website:

1.2 Sign Up for an Account:

  • Click on the “Sign Up/Login” button, usually located at the top right corner of the page.

  • Fill in the required details including your email address, and a strong password, or use your Google account.

  • You may also need to provide additional information or agree to certain terms and conditions.

1.3 Verify Your Email: (Skip if you used Google Account)

  • After signing up, you’ll likely need to verify your email address by clicking on a verification link sent to your email.

  • Check your email inbox (and spam folder, just in case) for the verification email from OpenAI, and click on the link provided to verify your account.

1.4 Access the OpenAI Dashboard:

  • Once your email is verified, log in to your OpenAI account.

  • Select API and you will be taken to the dashboard,

  • On the top right, click on your name, then "View API Keys."

Screenshot of openai website with API key highlighted

1.5 Generate API Key:

  • In the API Keys page, find and click on the option to create a "new secret key".

  • Give your API key a name that will help you remember what it’s for, like “Wix Chat Integration.”

  • Click on “Create” to generate your new API key.

1.6 Secure Your API Key:

  • Store your new API key in a secure location as you will need it for the integration in Step 3.

  • It's crucial to keep your API key secure to prevent unauthorized access to the ChatGPT service on your account.


Step 3: Configure Wix Velo

3.1 Enable Wix Velo:

  • From your Wix Editor, click on "Dev Mode" at the top bar, and then select "Turn on Dev Mode".


screenshot turn on dev mode on wix

3.2 Access Backend:

  • Once Velo is enabled, navigate to the "Site Structure" panel usually located on the left side of the editor.

  • Click on the “Backend” folder to access the backend files of your website.

3.3 Create a New .jsw File:

  • Right-click on the "Backend" folder, select "Add" and then choose "New Web Module" to create a new .jsw file.

  • Name this file chat.jsw or any other name that you prefer, then click "Create".

3.4 Write the Function to Connect to ChatGPT:

  • In the chat.jsw file, paste the following code:


import {fetch} from 'wix-fetch';

export async function getChatGPTResponse(messages, dbData) {
    const url = "https://api.openai.com/v1/chat/completions";
    const model = "gpt-3.5-turbo";

    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            model: model,
            messages: messages,
        }),
    });

    const data = await response.json();
    return data.choices[0].message.content.trim();
}
  • Replace YOUR_API_KEY with the API key you generated from OpenAI in Step 2.

3.5 Save and Publish Your Changes:

  • After inserting the code, save your .jsw file by clicking on the "Save" button, usually located at the top right corner of your Wix editor.

  • Don’t forget to publish your site to make these backend changes live.

3.6 Verify the Function:

  • It's a good practice to verify that the function is working correctly.

  • You can create a small front-end test function to call getChatGPTResponse and log the result to the console.

This completes the setup for Step 3. You have now created a backend function that will interact with the ChatGPT API. The next step will guide you on how to connect this function with your Wix Chat to enable real-time, automated responses to user queries on your website.


Step 4: Link Wix Chat to ChatGPT


4.1 Create events.js in Backend:

  • Navigate to the "Site Structure" panel on the left side of your Wix editor.

  • Right-click on the "Backend" folder, select "Add" and then choose "New JavaScript (.js) File".

  • Name this file events.js.



screenshot shows how to add backend folder in Wix


4.2 Import getChatGPTResponse Function:

  • In events.js, import the getChatGPTResponse function from chatjsw.


import { getChatGPTResponse } from 'backend/chat.jsw';

4.3 Define wixChat_onMessage Function:

  • Now, define the wixChat_onMessage function to handle new messages from Wix Chat.


export async function wixChat_onMessage(event) {
    const userMessage = {
        role: "user",
        content: event.body
    };
    const systemMessage = {
        role: "system",
        content: "You"
    };
    const messages = [systemMessage, userMessage];
    const chatGPTResponse = await getChatGPTResponse(messages);
    return chatGPTResponse;
}

4.4 Configure Wix Chat to Use wixChat_onMessage:

  • Now, you'll need to configure Wix Chat to use this new function whenever a new message is received.

  • Unfortunately, as of the last update, Wix Chat does not natively support backend event handling. You might need to create a workaround, such as a front-end function that polls for new messages and then triggers the backend function.

4.5 Save and Publish Your Changes:

  • Save your events.js file and publish your site to make these changes live.

4.6 Test the Integration:

  • Visit your live website, use the chat feature to send a message, and verify that you receive a response generated by ChatGPT.

This Step has set up a backend wixChat_onMessage function to handle new chat messages and interact with ChatGPT. Remember, the exact implementation might vary, especially the part where Wix Chat triggers this backend function, as Wix Chat's capabilities may have evolved since the last update.


Step 5: Enhance Robustness of Code

5.1 Error Handling:

  • Ensure your getChatGPTResponse function and other parts of your code have proper error handling to manage any issues that arise during the interaction with ChatGPT or Wix Chat. This might include try-catch blocks to capture and log errors.


try {
    const chatGPTResponse = await getChatGPTResponse(messages);
    wixChat.sendMessage(chatGPTResponse);
} catch (error) {
    console.error('Error fetching response from ChatGPT:', error);
    wixChat.sendMessage('Sorry, an error occurred. Please try again later.');
}

5.2 Input Validation:

  • Validate the input from the user before sending it to ChatGPT to avoid any malicious or poorly formatted input that could cause issues.


if (message.body && typeof message.body === 'string') {
    // Proceed with sending the message to ChatGPT
} else {
    console.error('Invalid message input:', message);
    wixChat.sendMessage('Sorry, I didn’t understand that. Please try again.');
}

5.3 Rate Limiting:

  • Implement rate limiting to prevent abuse of the chat feature, especially since each interaction with ChatGPT consumes API requests which could be costly.

// Example rate limiting logic

let lastMessageTimestamp = 0;

function isRateLimited() {
    const now = Date.now();
    const timeSinceLastMessage = now - lastMessageTimestamp;
    lastMessageTimestamp = now;
    return timeSinceLastMessage < RATE_LIMIT_INTERVAL;
}

5.4 Monitoring and Logging:

  • Set up monitoring and logging to track the performance of the chat feature, log errors, and gather data for analysis to help in identifying and fixing issues proactively.

5.5 Testing with Real Users:

  • Conduct usability testing with real users to identify any issues that you might not have noticed.

  • Collect feedback from users to understand their experience and make necessary adjustments.


By focusing on error handling, input validation, rate limiting, and continuous improvement, you can significantly enhance the robustness of your ChatGPT and Wix Chat integration, ensuring a smooth and reliable user experience.


Conclusion

Integrating a real-time chat feature like Wix Chat with the cutting-edge AI capabilities of ChatGPT significantly elevates the user engagement experience on your website. This blend of real-time interaction and intelligent, automated responses not only caters to your visitors' needs promptly but also showcases your brand as innovative and customer-centric. The structured steps outlined in this guide, from account setup and backend configuration to robustness enhancements and thorough testing, provide a comprehensive pathway to achieving a seamless integration, ensuring stability and effectiveness in facilitating real-time, intelligent interactions on your website.


The journey towards optimizing user engagement doesn't end with this integration. It's a continuous process of monitoring, collecting feedback, and making iterative improvements to stay aligned with evolving user expectations. The value added by real-time, intelligent interactions is immense, and with technologies like ChatGPT, the scope of enhancing user satisfaction and engagement is vast. Stay tuned for our follow-up blog post where we will delve deeper into analyzing the impact of ChatGPT integration and how to leverage data insights for further optimization.


Excited about the possibilities? Head over to our demo page and dive into the interactive chat experience we've crafted for you!


Engage with CodeMasters: Your Partner in Integrating Wix Chat with ChatGPT


Ready to transform your website into a dynamic, user-friendly space? At CodeMasters, we excel in delivering tailored web development solutions infused with the latest technologies. Our expertise in AI integrations like ChatGPT can propel your website to new heights of user engagement and satisfaction. Discover the breadth of our web development services and let’s embark on a journey towards digital excellence together. Stay ahead with CodeMasters, and look forward to more insightful explorations in our upcoming blog posts!


Sign up for free and unlock over $300 in exclusive deals on top SaaS tools like LinkedIn credits, QuickBooks, SEMrush, and more! Explore Deals


bottom of page