Laravel + React Integration Guide

Securely integrate the AskEase Chatbot Service into your Laravel backend and React frontend. This setup routes messages through your Laravel server first to **protect your secure API key** from being exposed to the browser.

1. Configure Environment Variables (.env)

CHATBOT_SERVICE_URL=https://easecert-chatbot-service-production.up.railway.app
CHATBOT_API_KEY=your_secure_chatbot_api_key_here
CHATBOT_PROJECT_ID=easecert

2. Register Config Mapping (config/services.php)

Add the chatbot mapping to your config/services.php array. This is required so you can run php artisan config:cache in production:

'chatbot' => [
    'url' => env('CHATBOT_SERVICE_URL', 'http://localhost:8080'),
    'project_id' => env('CHATBOT_PROJECT_ID', 'easecert'),
    'api_key' => env('CHATBOT_API_KEY'),
],

3. Create Chatbot Controller (app/Http/Controllers/ChatbotController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ChatbotController extends Controller
{
    public function sendMessage(Request $request)
    {
        $request->validate([
            'message' => 'required|string|max:500'
        ]);

        $chatbotUrl = rtrim(config('services.chatbot.url'), '/');
        $projectId = config('services.chatbot.project_id');
        $apiKey = config('services.chatbot.api_key');

        // Forward request securely using Laravel HTTP Client
        $response = Http::withHeaders([
            'X-Project-ID' => $projectId,
            'X-API-Key' => $apiKey,
        ])->timeout(15)
          ->post("{$chatbotUrl}/api/v1/chat", [
            'message' => $request->input('message')
        ]);

        if ($response->successful()) {
            return response()->json([
                'status' => 'success',
                'response' => $response->json('response')
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'Could not connect to the Chatbot service.'
        ], 502);
    }
}

4. Register Route (routes/api.php)

Route::post('/chatbot/chat', [ChatbotController::class, 'sendMessage']);

Create React Chat Component (ChatWidget.jsx)

Query your local Laravel backend route, leaving your frontend completely clean of secure keys:

import React, { useState } from 'react';

export default function ChatWidget() {
    const [messages, setMessages] = useState([
        { text: "Hello! How can I assist you with EaseCert today?", sender: "bot" }
    ]);
    const [input, setInput] = useState("");
    const [loading, setLoading] = useState(false);

    const handleSend = async (e) => {
        e.preventDefault();
        if (!input.trim() || loading) return;

        const userMsg = { text: input, sender: "user" };
        setMessages(prev => [...prev, userMsg]);
        setInput("");
        setLoading(true);

        try {
            const response = await fetch('/api/chatbot/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: userMsg.text })
            });
            
            const data = await response.json();
            setMessages(prev => [...prev, { text: data.response, sender: "bot" }]);
        } catch (error) {
            setMessages(prev => [...prev, { text: "Error connecting to server.", sender: "bot" }]);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="chat-widget">
            <div className="chat-window">
                {messages.map((m, idx) => (
                    <div key={idx} className={`bubble ${m.sender}`}>
                        {m.text}
                    </div>
                ))}
            </div>
            <form onSubmit={handleSend}>
                <input value={input} onChange={e => setInput(e.target.value)} />
                <button type="submit">Send</button>
            </form>
        </div>
    );
}

Direct API HTTP Query (cURL)

curl -X POST "https://easecert-chatbot-service-production.up.railway.app/api/v1/chat" \
  -H "Content-Type: application/json" \
  -H "X-Project-ID: easecert" \
  -H "X-API-Key: your_secure_chatbot_api_key_here" \
  -d '{"message": "How do I start my audit submission?"}'