首先,您需要确保您的 PHP 版本大于或等于 5.4,并且已经启用了 curl 扩展。接下来,您需要获取 ChatGPT API 的访问密钥。您可以通过访问 ChatGPT 网站并创建一个账号来获取该密钥。

在获取到访问密钥之后,您可以使用以下代码样例对接 ChatGPT API:

$access_token = 'your_access_token';
$input_text = 'Hello, how are you?';

$data = array(
    'input_text' => $input_text,
);

$post_data = json_encode($data);

$url = 'https://api.chatgpt.com/v1/complete?access_token=' . $access_token;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($post_data),
));

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

$response = json_decode($result, true);

if (isset($response['output_text'])) {
    echo $response['output_text'];
} else {
    echo 'Error: ' . $response['error'];
}

在上述代码中,$access_token 是您的访问密钥。$input_text 是您要传递给 ChatGPT API 的文本。然后,使用 curl 库向 ChatGPT API 发送 POST 请求,并将其响应存储在 $result 中。最后,您可以从响应中提取输出文本并将其输出到屏幕上。

请注意,上述代码仅为示例。您需要根据您的应用程序的要求对其进行修改。

ChatGPT API 接口对接 PHP 代码示例

原文地址: https://www.cveoy.top/t/topic/nR8r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录