PHP code example of vergil-lai / wecom-aibot-php-sdk
1. Go to this page and download the library: Download vergil-lai/wecom-aibot-php-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
vergil-lai / wecom-aibot-php-sdk example snippets
VergilLai\WecomAiBot\WSClient;
use VergilLai\WecomAiBot\Types\WsClientOptions;
use VergilLai\WecomAiBot\Types\WsFrame;
use VergilLai\WecomAiBot\Utils;
// 1. 创建客户端实例
$wsClient = new WSClient(new WsClientOptions(
botId: 'your-bot-id', // 企业微信后台获取的机器人 ID
secret: 'your-bot-secret', // 企业微信后台获取的机器人 Secret
));
// 2. 建立连接(支持链式调用)
$wsClient->connect();
// 3. 监听认证成功
$wsClient->on('authenticated', function () {
echo '🔐 认证成功', PHP_EOL;
});
// 4. 监听文本消息并进行流式回复
$wsClient->on('message.text', function (WsFrame $frame) use ($wsClient) {
$content = $frame->body['text']['content'] ?? '';
echo "收到文本: {$content}", PHP_EOL;
$streamId = Utils::generateReqId('stream');
// 发送流式中间内容
$wsClient->replyStream($frame, $streamId, '正在思考中...', false);
// 发送最终结果
React\EventLoop\Loop::addTimer(1.0, function () use ($wsClient, $frame, $streamId, $content) {
$wsClient->replyStream($frame, $streamId, "你好!你说的是: \"{$content}\"", true);
});
});
// 5. 监听进入会话事件(发送欢迎语)
$wsClient->on('event.enter_chat', function (WsFrame $frame) use ($wsClient) {
$wsClient->replyWelcome($frame, [
'msgtype' => 'text',
'text' => ['content' => '您好!我是智能助手,有什么可以帮您的吗?'],
]);
});
// 6. 优雅退出
$loop = React\EventLoop\Loop::get();
$loop->addSignal(SIGINT, function () use ($wsClient, $loop) {
$wsClient->disconnect();
$loop->stop();
});
$wsClient = new WSClient(options: WsClientOptions|array);