🧭 一、获取 ChatGPT API 密钥(API Key)

  1. 访问官网:
    打开 https://platform.openai.com/

  2. 登录账号:
    使用你的 OpenAI 账户(ChatGPT 登录用的那个)登录。

  3. 进入 API 管理页:
    在顶部菜单选择 “API keys” 或直接访问:
    👉 https://platform.openai.com/api-keys

  4. 创建密钥:
    点击 “+ Create new secret key”,为它命名(如 my-php-app)。

  5. 复制密钥:
    生成后会显示类似:

    sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    ⚠️ 注意:只会显示一次,请立刻复制保存(放进你的 .env 或配置文件中)。


💻 二、PHP 代码示例(cURL 实现)

假设你要调用 ChatGPT 的 GPT-4 模型接口 /v1/chat/completions,生成内容。

<?php
// ChatGPT API 对接示例
// -----------------------
// PHP版本 ≥7.4,并启用cURL扩展。

$api_key = "sk-你的API密钥"; // 替换为你自己的密钥
$url = "https://api.openai.com/v1/chat/completions";

// 发送的内容
$data = [
 "model" => "gpt-4o-mini", // 或 "gpt-4o", "gpt-3.5-turbo" 等
 "messages" => [
 ["role" => "system", "content" => "You are a helpful assistant."],
 ["role" => "user", "content" => "Write a short paragraph about PHP connecting to ChatGPT API."]
 ],
 "temperature" => 0.7, // 控制创意程度(0~1)
 "max_tokens" => 500
];

// 初始化 cURL
$ch = curl_init();
curl_setopt_array($ch, [
 CURLOPT_URL => $url,
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_POST => true,
 CURLOPT_HTTPHEADER => [
 "Content-Type: application/json",
 "Authorization: Bearer $api_key"
 ],
 CURLOPT_POSTFIELDS => json_encode($data),
]);

// 执行请求
$response = curl_exec($ch);

// 错误检测
if (curl_errno($ch)) {
 echo "cURL Error: " . curl_error($ch);
} else {
 $result = json_decode($response, true);
 echo "<h3>✅ ChatGPT 返回结果:</h3>";
 echo "<pre>" . htmlspecialchars($result['choices'][0]['message']['content']) . "</pre>";
}

curl_close($ch);
?>

⚙️ 三、优化建议

1. 使用 .env 文件存储密钥(更安全)

# .env
OPENAI_API_KEY=sk-xxxxxx

然后在PHP中:

$api_key = getenv("OPENAI_API_KEY");

2. 封装成一个通用函数

function chatgpt($prompt, $model = "gpt-4o-mini") {
 $api_key = "sk-xxxxxx";
 $url = "https://api.openai.com/v1/chat/completions";

 $data = [
 "model" => $model,
 "messages" => [
 ["role" => "system", "content" => "You are a helpful assistant."],
 ["role" => "user", "content" => $prompt]
 ]
 ];

 $ch = curl_init($url);
 curl_setopt_array($ch, [
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_HTTPHEADER => [
 "Content-Type: application/json",
 "Authorization: Bearer $api_key"
 ],
 CURLOPT_POST => true,
 CURLOPT_POSTFIELDS => json_encode($data)
 ]);

 $response = curl_exec($ch);
 curl_close($ch);

 $result = json_decode($response, true);
 return $result['choices'][0]['message']['content'] ?? "No response.";
}

// 调用
echo chatgpt("Explain how to connect PHP with ChatGPT API.");

示例执行后可能输出:

✅ ChatGPT 返回结果:
PHP can connect to the ChatGPT API using cURL...



 面向对象类(Class)


ChatGPT.php

<?php
/**
 * ChatGPT API 对接类
 * 作者:Yanxiao
 * 说明:支持多模型调用、错误处理、JSON解析、安全封装
 * 依赖:PHP ≥7.4 + cURL
 */

class ChatGPT
{
 private string $apiKey;
 private string $baseUrl = "https://api.openai.com/v1";
 private int $timeout = 30;

 public function __construct(string $apiKey)
 {
  $this->apiKey = $apiKey;
 }

 /**
  * 通用请求方法
  */
 private function request(string $endpoint, array $data)
 {
  $url = "{$this->baseUrl}/{$endpoint}";
  $ch = curl_init($url);

  curl_setopt_array($ch, [
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_HTTPHEADER => [
    "Content-Type: application/json",
    "Authorization: Bearer {$this->apiKey}"
   ],
   CURLOPT_POST => true,
   CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
   CURLOPT_TIMEOUT => $this->timeout,
  ]);

  $response = curl_exec($ch);
  $error = curl_error($ch);
  curl_close($ch);

  if ($error) {
   throw new Exception("❌ cURL Error: " . $error);
  }

  $result = json_decode($response, true);
  if (isset($result['error'])) {
   throw new Exception("⚠️ API Error: " . $result['error']['message']);
  }

  return $result;
 }

 /**
  * Chat 模式(文字对话)
  */
 public function chat(string $prompt, string $model = "gpt-4o-mini", float $temperature = 0.7, int $maxTokens = 800)
 {
  $data = [
   "model" => $model,
   "messages" => [
    ["role" => "system", "content" => "You are a helpful assistant."],
    ["role" => "user", "content" => $prompt],
   ],
   "temperature" => $temperature,
   "max_tokens" => $maxTokens,
  ];

  $result = $this->request("chat/completions", $data);
  return $result['choices'][0]['message']['content'] ?? "";
 }

 /**
  * JSON 模式(适合结构化结果)
  */
 public function chatJSON(string $prompt, string $model = "gpt-4o-mini")
 {
  $data = [
   "model" => $model,
   "response_format" => ["type" => "json_object"],
   "messages" => [
    ["role" => "system", "content" => "You are a helpful assistant that outputs JSON only."],
    ["role" => "user", "content" => $prompt],
   ],
  ];

  $result = $this->request("chat/completions", $data);
  $content = $result['choices'][0]['message']['content'] ?? "{}";
  return json_decode($content, true);
 }

 /**
  * 设置超时
  */
 public function setTimeout(int $seconds): void
 {
  $this->timeout = $seconds;
 }
}

demo.php 示例调用

<?php
require_once "ChatGPT.php";

try {
 // 1. 初始化
 $chatgpt = new ChatGPT("sk-你的API密钥");

 // 2. 设置超时(可选)
 $chatgpt->setTimeout(20);

 // 3. 发起对话
 $response = $chatgpt->chat("Explain how PHP connects to the ChatGPT API step by step.");
 echo "<h3>✅ 普通文本模式输出:</h3><pre>{$response}</pre>";

 // 4. 获取结构化JSON(可选)
 $jsonResponse = $chatgpt->chatJSON("Generate a JSON list of 3 PHP frameworks with name and description.");
 echo "<h3>✅ JSON模式输出:</h3><pre>";
 print_r($jsonResponse);
 echo "</pre>";

} catch (Exception $e) {
 echo "<h3 style='color:red;'>错误:</h3><pre>" . $e->getMessage() . "</pre>";
}

要想查看其他更多内容,请访问:PHP小志

提示词内容,请访问:提示词 PHP + OpenAI API(v1/chat/completions)+ 技术写作 / SEO 内容类文章生成


点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部