Files
sam-kd/ai_sam/api/get_api_key.php

85 lines
3.5 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Gemini API Key 조회 API
* Codebridge-Chatbot 프로젝트의 서비스 계정을 사용합니다.
*/
header('Content-Type: application/json; charset=utf-8');
// 서비스 계정 JSON 파일 경로
$serviceAccountFile = dirname(dirname(__DIR__)) . '/apikey/google_service_account.json';
// API 키 파일 경로
$apiKeyFile = dirname(dirname(__DIR__)) . '/apikey/gemini_api_key.txt';
try {
// Codebridge-Chatbot 프로젝트 확인
$serviceAccount = null;
if (file_exists($serviceAccountFile)) {
$serviceAccount = json_decode(file_get_contents($serviceAccountFile), true);
if ($serviceAccount && isset($serviceAccount['project_id'])) {
// project_id가 'codebridge-chatbot'인지 확인
if ($serviceAccount['project_id'] !== 'codebridge-chatbot') {
echo json_encode([
'success' => false,
'error' => '서비스 계정 프로젝트가 "codebridge-chatbot"이 아닙니다. 현재 프로젝트: ' . $serviceAccount['project_id'] . '. Codebridge-Chatbot 프로젝트의 서비스 계정을 사용해주세요.'
], JSON_UNESCAPED_UNICODE);
return;
}
}
}
// API 키 파일 확인 (Codebridge-Chatbot 프로젝트의 API 키)
if (file_exists($apiKeyFile)) {
$apiKey = trim(file_get_contents($apiKeyFile));
// 플레이스홀더 텍스트 체크
if (empty($apiKey) ||
strpos($apiKey, '================================') !== false ||
strpos($apiKey, 'GEMINI API KEY') !== false ||
strpos($apiKey, '여기에') !== false ||
strlen($apiKey) < 20) {
echo json_encode([
'success' => false,
'error' => 'Codebridge-Chatbot 프로젝트의 API Key가 설정되지 않았습니다. apikey/gemini_api_key.txt 파일에 유효한 API Key를 입력해주세요.'
], JSON_UNESCAPED_UNICODE);
return;
}
// 서비스 계정 정보도 함께 반환
$response = [
'success' => true,
'apiKey' => $apiKey
];
if ($serviceAccount && $serviceAccount['project_id'] === 'codebridge-chatbot') {
$response['projectId'] = $serviceAccount['project_id'];
$response['serviceAccount'] = true;
$response['clientEmail'] = $serviceAccount['client_email'] ?? '';
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
return;
}
// API 키 파일이 없으면 오류
if ($serviceAccount && $serviceAccount['project_id'] === 'codebridge-chatbot') {
echo json_encode([
'success' => false,
'error' => 'Codebridge-Chatbot 프로젝트의 API 키 파일(gemini_api_key.txt)을 찾을 수 없습니다. Google Cloud Console에서 API 키를 생성하고 apikey/gemini_api_key.txt 파일에 입력해주세요.'
], JSON_UNESCAPED_UNICODE);
} else {
echo json_encode([
'success' => false,
'error' => 'Codebridge-Chatbot 프로젝트의 서비스 계정 파일(google_service_account.json) 또는 API 키 파일(gemini_api_key.txt)을 찾을 수 없습니다.'
], JSON_UNESCAPED_UNICODE);
}
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => '인증 정보를 읽는 중 오류가 발생했습니다: ' . $e->getMessage()
], JSON_UNESCAPED_UNICODE);
}
?>