PHP 연동 예제 모음 > BlueTalk::블루톡 무료 실시간 채팅 위젯 · 1:1 DM · 웹 채팅 연동

PHP 서버 샘플 모음
1. 준비 사항

예제 실행 전에 PHP 환경에서 다음을 확인해 주세요.

  • cURL 확장이 활성화되어 있어야 합니다. (phpinfo 또는 extension=curl 확인)
  • 파일 업로드 예제에서는 서버에 $_FILES를 다룰 수 있는 기본 설정이 필요합니다.
  • 샘플 코드는 이해를 돕기 위한 것으로, 운영 환경에서는 예외 처리·로그·보안 체크를 더 강화해야 합니다.

아래 예제에서 사용하는 서버 주소와 site_key, user_id, user_key 등은 실제 사용 환경에 맞게 교체하셔야 합니다.

2. 파일 업로드 예제 (POST /upload/chat-file)

PHP 서버에서 BlueTalk 서버로 직접 파일을 업로드하고 싶을 때 사용할 수 있는 예제입니다.
예를 들어 관리페이지에서 이미지를 올려 채팅 공지에 넣고 싶을 때 사용할 수 있습니다.

<?php
// upload_to_bluetalk.php

// BlueTalk 서버 주소 (예시)
$api_base = 'https://server.bluetalk.kr';

// 사이트별 설정
$blt_site_key = '발급받은_site_key';
$channel_key  = 'global';

// 이 예제에서는 봇/관리자 계정을 가정
$user_id      = 'system_bot';
$user_key     = '서버에서_생성한_user_key';

// 업로드할 로컬 파일 경로
$local_file   = __DIR__ . '/test.png';

if (!file_exists($local_file)) {
    die('파일이 존재하지 않습니다: ' . $local_file);
}

// PHP 5.6 이상에서 CURLFile 사용
$file = new CURLFile($local_file, mime_content_type($local_file), basename($local_file));

$post_fields = array(
    'file'        => $file,
    'site_key'    => $blt_site_key,
    'channel_key' => $channel_key,
    'user_id'     => $user_id,
    'user_key'    => $user_key,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_base . '/upload/chat-file');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 필요에 따라 조정

$response = curl_exec($ch);
if ($response === false) {
    echo 'cURL 오류: ' . curl_error($ch);
    curl_close($ch);
    exit;
}
curl_close($ch);

// JSON 파싱
$data = json_decode($response, true);

if (!$data || !isset($data['ok']) || !$data['ok']) {
    echo "업로드 실패\n";
    var_dump($data);
    exit;
}

$file_info = $data['file']; // id, type, name, size, mime

echo "업로드 성공!\n";
echo "file_id: " . $file_info['id'] . "\n";
echo "name   : " . $file_info['name'] . "\n";
echo "url    : " . $api_base . '/chat-file/' . $file_info['id'] . "\n";

성공 시 { ok:true, file:{ id, type, name, size, mime } } 형태의 응답을 받게 됩니다.
이때 $file_info['id'] 값을 채팅 메시지의 attachment_ids에 넣어 사용합니다.

3. HTML 폼 + PHP로 업로드 테스트 페이지 만들기

이번에는 브라우저에서 파일을 선택하고, 그 파일을 PHP가 받아서 다시 BlueTalk 서버로 업로드하는 예제입니다.

<?php
// upload_form.php

// BlueTalk 서버 설정
$api_base     = 'https://server.bluetalk.kr';
$blt_site_key = '발급받은_site_key';
$channel_key  = 'global';

// 로그인/관리자 계정 정보 (예시)
// 실제로는 세션/DB에서 가져와야 합니다.
$user_id      = 'admin';
$user_key     = '서버에서_생성한_user_key';

$result_msg   = '';
$file_preview = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_FILES['upload_file']) || $_FILES['upload_file']['error'] !== UPLOAD_ERR_OK) {
        $result_msg = '파일 업로드에 실패했습니다.';
    } else {
        $tmp_name = $_FILES['upload_file']['tmp_name'];
        $name     = $_FILES['upload_file']['name'];
        $type     = $_FILES['upload_file']['type'];

        $file = new CURLFile($tmp_name, $type, $name);

        $post_fields = array(
            'file'        => $file,
            'site_key'    => $blt_site_key,
            'channel_key' => $channel_key,
            'user_id'     => $user_id,
            'user_key'    => $user_key,
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_base . '/upload/chat-file');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

        $response = curl_exec($ch);
        if ($response === false) {
            $result_msg = 'cURL 오류: ' . curl_error($ch);
        } else {
            $data = json_decode($response, true);
            if ($data && isset($data['ok']) && $data['ok']) {
                $file_info = $data['file'];
                $result_msg = '업로드 성공! file_id = ' . $file_info['id'];

                // 이미지라면 미리보기
                if ($file_info['type'] === 'image') {
                    $url = $api_base . '/chat-file/' . $file_info['id'];
                    $file_preview = '<img src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') .
                                    '" alt="' . htmlspecialchars($file_info['name'], ENT_QUOTES, 'UTF-8') .
                                    '" style="max-width:200px; margin-top:10px;">';
                }
            } else {
                $reason = isset($data['reason']) ? $data['reason'] : 'UNKNOWN';
                $result_msg = '업로드 실패: ' . $reason;
            }
        }
        curl_close($ch);
    }
}
?>

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>BlueTalk 업로드 테스트</title>
</head>
<body>
  <h3>BlueTalk 이미지/파일 업로드 테스트</h3>

  <form method="post" enctype="multipart/form-data">
    <input type="file" name="upload_file" required>
    <button type="submit">업로드</button>
  </form>

  <div style="margin-top:15px; font-size:13px;">
    <?php if ($result_msg) echo htmlspecialchars($result_msg, ENT_QUOTES, 'UTF-8'); ?>
    <?php if ($file_preview) echo '<br>' . $file_preview; ?>
  </div>
</body>
</html>

이 코드를 그대로 /ex/ 아래에 두고 테스트하면, BlueTalk 서버로 파일이 업로드되는지 바로 확인할 수 있습니다.

4. Health Check 예제 (GET /health)

BlueTalk 서버가 정상 동작 중인지 확인하기 위한 간단한 헬스 체크 예제입니다.

<?php
// health_check.php

$api_base = 'https://server.bluetalk.kr';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_base . '/health');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Health Check 실패: ' . curl_error($ch);
} else {
    echo 'Health Check 응답: ' . htmlspecialchars($response, ENT_QUOTES, 'UTF-8');
}
curl_close($ch);

이 스크립트를 cron 등으로 주기적으로 호출하여 응답 상태를 모니터링할 수 있습니다.

5. PHP에서 WebSocket 연동에 대한 참고

BlueTalk의 실시간 채팅/DM은 기본적으로 socket.io 기반 WebSocket을 사용합니다.
PHP에서도 socket.io 클라이언트 라이브러리를 사용하거나, 순수 WebSocket 클라이언트를 작성해서 직접 이벤트를 주고받을 수 있습니다.

  • 단, PHP에서 상시 실행되는 프로세스를 유지해야 하므로 웹 요청 1회성 스크립트에는 적합하지 않습니다.
  • 봇/백그라운드 작업은 Node.js 또는 Python 같은 장기 실행 환경에서 구현하는 것을 추천합니다.
  • PHP에서는 REST API(파일 업로드, health check 등)에 집중하는 것이 일반적으로 더 간단합니다.

WebSocket 쪽 상세 이벤트 구조가 필요하다면 WebSocket 이벤트 문서를 참고하세요.

6. JS SDK(new BlueTalk)와의 연결 포인트

마지막으로, PHP에서 생성한 site_key / user_id / nickname / user_key를 실제 페이지의 JS SDK(BlueTalk 위젯)로 연결하는 기본 패턴을 정리합니다.

<?php
// 예: 어떤 PHP 페이지 상단에서
$blt_site_key = '발급받은_site_key';
$blt_secret   = '서버_비밀문자열';

if ($is_member) {
    $blt_user_id  = $member['mb_id'];
    $blt_nickname = get_text($member['mb_nick']);
} else {
    $blt_user_id  = 'guest';
    $blt_nickname = '손님';
}

$payload      = $blt_user_id . '|' . $blt_site_key . '|' . $blt_secret;
$blt_user_key = hash('sha256', $payload);
?>

<div id="bluetalk" style="height:480px;"></div>
<script src="https://bluetalk.kr/talk/bluetalk.js"></script>
<script>
  window.SITE_KEY          = "<?= $blt_site_key; ?>";
  window.GLOBAL_USER_ID    = "<?= htmlspecialchars($blt_user_id,   ENT_QUOTES, 'UTF-8'); ?>";
  window.GLOBAL_USER_KEY   = "<?= $blt_user_key; ?>";
  window.GLOBAL_NICKNAME   = "<?= htmlspecialchars($blt_nickname, ENT_QUOTES, 'UTF-8'); ?>";

  const bt = new BlueTalk({
    mode:     'global',
    targetId: 'bluetalk'
  });
  bt.init();
</script>
팔로팡 오일보이&커스텀 AI코인봇 AI Coin Bot 코스퀀트