With the rapid development of WeChat Mini Programs, more and more developers are looking to add instant messaging features to their apps. Real-time chat enhances user engagement and improves interactivity. In this tutorial, we'll show how to use PHP with the WebSocket protocol to create a real-time chat system for WeChat Mini Programs.
The key to real-time chat lies in maintaining an ongoing communication channel between the client and the server. Traditional HTTP requests are one-way and temporary, while WebSocket allows full-duplex communication over a single TCP connection, enabling both sides to send data actively.
In PHP, we can easily build a WebSocket server using the Ratchet library. Ratchet allows us to handle connections, broadcast messages, and manage multiple users simultaneously, making it ideal for chat applications.
First, prepare a PHP runtime environment using Apache or Nginx. After installing Composer, run the following command to install the Ratchet library:
<span class="fun">composer require cboden/ratchet</span>
Next, create a file named chat_server.php to handle WebSocket communication. Below is an example implementation:
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class ChatServer implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
$data = json_decode($msg, true);
foreach ($this->clients as $client) {
$client->send(json_encode($data));
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = \Ratchet\Server\IoServer::factory(
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(
new ChatServer()
)
),
8080
);
$server->run();
Once the file is running, the WebSocket server will listen on port 8080, waiting for connections from your WeChat Mini Program.
In the WeChat Mini Program frontend, you can use the wx.connectSocket method to connect to your WebSocket server and send or receive messages as shown below:
const socket = wx.connectSocket({
url: 'ws://localhost:8080',
success: function() {
console.log('WebSocket connection established');
}
});
socket.onOpen(function() {
console.log('WebSocket connection opened');
socket.send({
message: 'Hello, WebSocket!'
});
});
socket.onMessage(function(res) {
console.log('Received message:', res.data);
});
socket.onClose(function() {
console.log('WebSocket connection closed');
});
With this setup, your Mini Program can now communicate with the PHP WebSocket server in real time, supporting multi-user chat interactions.
On the server side, within the onMessage method, you can process incoming messages based on your business logic—for example, saving them to a database, filtering sensitive words, or identifying users before broadcasting the message to all connected clients. This is how you can implement group chat functionality.
This guide demonstrated how to build a real-time chat feature for WeChat Mini Programs using PHP and WebSocket. From setting up the environment and implementing the Ratchet server to establishing the frontend connection, developers can quickly create a working real-time communication system. With further optimization, you can extend it to include features like private messaging, message history, and online status indicators.