PHP code example of pfinalclub / coze_sdk

1. Go to this page and download the library: Download pfinalclub/coze_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/ */

    

pfinalclub / coze_sdk example snippets




use CozeSdk\OfficialAccount\Application;
use CozeSdk\Kernel\Support\SimpleLogger;

// 创建应用实例
$app = new Application([
    'kid' => 'your_kid_here',
    'iss' => 'your_iss_here',
    'keyPath' => '/path/to/your/private_key.pem',
    'botId' => 'your_bot_id_here'
], new SimpleLogger());

// 验证配置
$app->validate();



use CozeSdk\Chat\Chat;

// 创建聊天实例
$chat = new Chat($app);

// 发送消息
$response = $chat->setUserId('user_123')
    ->sendMessage('你好,请介绍一下PHP');

// 处理响应
foreach ($response['messages'] as $message) {
    echo $message['content'] . "\n";
}



use CozeSdk\Bot\Bot;

// 创建机器人管理实例
$bot = new Bot($app->getAccessToken());

// 获取机器人列表
$botList = $bot->setSpaceId('your_space_id')
    ->getBotList();

// 获取机器人详情
$botDetail = $bot->getBotDetail('bot_id_here');

// 搜索机器人
$searchResults = $bot->searchBots('关键词');



use CozeSdk\Chat\Chat;

$chat = new Chat($app);

// 创建流式聊天(兼容旧版本)
$streamCallback = $chat->setUserId('user_123')
    ->Query('请写一个PHP函数')
    ->Build(true);

// 执行流式响应
$streamCallback();



use CozeSdk\Chat\Chat;
use CozeSdk\Kernel\Support\{
    ConsoleStreamHandler,
    JsonStreamHandler,
    MemoryStreamHandler,
    CallbackStreamHandler
};

$chat = new Chat($app);

// 1. 控制台输出流式处理器
$consoleHandler = new ConsoleStreamHandler();
$result = $chat->sendStreamMessage('你好,请介绍一下PHP', $consoleHandler);

// 2. JSON流式处理器
$jsonHandler = new JsonStreamHandler();
$result = $chat->sendStreamMessage('写一个简单的函数', $jsonHandler);

// 3. 内存流式处理器
$memoryHandler = new MemoryStreamHandler();
$result = $chat->sendStreamMessage('解释什么是OOP', $memoryHandler);

// 4. 回调流式处理器(最灵活)
$callbackHandler = new CallbackStreamHandler(
    function($chunk, $metadata) {
        // 处理每个数据块
        echo $chunk;
        flush();
        return true; // 继续处理
    },
    function($metadata) {
        // 流式传输开始
        echo "开始接收数据...\n";
    },
    function($metadata) {
        // 流式传输结束
        echo "\n接收完成\n";
    },
    function($error, $metadata) {
        // 错误处理
        echo "错误: " . $error->getMessage() . "\n";
    }
);

$result = $chat->sendStreamMessage('请写一个详细的教程', $callbackHandler);



use CozeSdk\Chat\Chat;
use CozeSdk\Kernel\Support\{
    EnhancedStreamHandler,
    RealTimeTextHandler,
    ProgressMonitorHandler
};

$chat = new Chat($app);

// 1. 实时文本流式传输
$result = $chat->sendRealTimeMessage('请介绍一下PHP');
echo "文本长度: " . strlen($result) . " 字符";

// 2. 带进度监控的流式传输
$result = $chat->sendProgressMessage('请写一个详细的教程', 20);
echo "统计信息: " . json_encode($result['stats']);

// 3. 增强流式处理器
$result = $chat->sendEnhancedMessage(
    '请解释什么是OOP',
    // 文本回调
    function($text, $metadata) {
        echo $text;
        flush();
        return true;
    },
    // 数据回调
    function($data, $metadata) {
        // 处理结构化数据
        return true;
    },
    // 进度回调
    function($stats, $metadata) {
        echo "\r进度: {$stats['total_text_length']} 字符";
    }
);

$app = new Application($config, $logger, $cache, $httpClient);

// 获取访问令牌
$accessToken = $app->getAccessToken();

// 获取机器人ID
$botId = $app->getBotId();

// 验证配置
$app->validate();

$chat = new Chat($app, $httpClient, $cache, $logger);

// 设置参数
$chat->setBotId('bot_id')
    ->setUserId('user_id')
    ->setConversationId('conversation_id');

// 发送消息
$response = $chat->sendMessage('消息内容');

// 获取聊天详情
$detail = $chat->getChatRetrieve('chat_id');

// 获取消息列表
$messages = $chat->getChatMessageList('chat_id');

$bot = new Bot($accessToken, $httpClient, $cache, $logger);

// 设置空间ID
$bot->setSpaceId('space_id');

// 获取机器人列表
$botList = $bot->getBotList();

// 获取机器人详情
$botDetail = $bot->getBotDetail('bot_id');

// 获取机器人ID列表
$botIds = $bot->getBotIdList();

// 搜索机器人
$results = $bot->searchBots('关键词');

// 获取统计信息
$stats = $bot->getBotStats();

use CozeSdk\Kernel\Support\SimpleLogger;

// 创建日志实例
$logger = new SimpleLogger(true); // 启用日志

// 日志文件位置
// Linux/Mac: /tmp/coze_sdk_logs/coze_sdk.log
// Windows: C:\Users\{username}\AppData\Local\Temp\coze_sdk_logs\coze_sdk.log

use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;

// 文件系统缓存
$cache = new Psr16Cache(new FilesystemAdapter('coze', 1500));

// Redis 缓存(需要安装 redis 扩展)
$cache = new Psr16Cache(new RedisAdapter($redis));

// 内存缓存(测试用)
$cache = new Psr16Cache(new ArrayAdapter());

use CozeSdk\Kernel\Exception\HttpException;
use CozeSdk\Kernel\Exception\ParamsException;

try {
    $response = $chat->sendMessage('消息');
} catch (ParamsException $e) {
    // 参数错误
    echo "参数错误: " . $e->getMessage();
} catch (HttpException $e) {
    // HTTP 请求错误
    echo "请求错误: " . $e->getMessage();
} catch (\Exception $e) {
    // 其他错误
    echo "未知错误: " . $e->getMessage();
}
bash
# 运行单元测试
php tests/run_tests.php --unit

# 运行流式传输测试
php tests/run_tests.php --stream

# 运行所有测试
php tests/run_tests.php --all

# 显示帮助信息
php tests/run_tests.php --help
bash
# 运行简单单元测试
php tests/simple_unit_test.php

# 运行快速功能测试
php tests/quick_test.php

# 验证PHPUnit配置
php tests/test_phpunit.php