php调用智谱ChatGLM API需严格遵循OpenAPI规范:使用curl发送POST请求,设置Authorization头(Bearer+空格+API密钥)、Content-Type为application/json,json体含model、messages(格式为[{“role”:”user”,”content”:”xxx”}])、stream=false;否则易返回401或400错误。

PHP 调用智谱 ChatGLM API 的核心是 curl 发送 POST 请求
智谱 ai(Zhipu AI)的 ChatGLM 系列模型(如 glm-4、glm-3-turbo)不提供原生 PHP SDK,必须手动构造 http 请求。关键不是“封装成函数”,而是确保请求头、认证方式、JSON 体结构完全符合其 OpenAPI 规范——否则直接返回 401 Unauthorized 或 400 Bad Request。
常见错误包括:Authorization 头漏了 Bearer 前缀、Content-Type 没设为 application/json、messages 数组格式不合法(必须是 [{"role": "user", "content": "xxx"}])、model 字段写错(比如写成 chatglm3 而非官方文档写的 glm-3-turbo)。
必须设置的请求头和参数字段
智谱 API 要求严格校验以下字段,缺一不可:
-
Authorization: Bearer—— 注意Bearer后带空格,your_api_key是你在 open.bigmodel.cn 生成的密钥 Content-Type: application/json- POST body 必须是 JSON 字符串,且包含:
model(字符串)、messages(消息数组)、stream(布尔值,设为false才能一次性拿到完整响应) -
messages中每条必须有role("user"或"assistant")和content(字符串),不能为NULL或空字符串
一个可直接运行的 PHP 封装函数示例
该函数只做最小必要封装:接收 $api_key、$prompt、$model,返回原始 JSON 响应或 false。不处理重试、超时自适应、流式解析等进阶逻辑——那些容易掩盖真实错误。
立即学习“PHP免费学习笔记(深入)”;
function call_zhipu_chatglm($api_key, $prompt, $model = 'glm-4') { $url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'model' => $model, 'messages' => [['role' => 'user', 'content' => $prompt]], 'stream' => false ])); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $api_key, 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($http_code !== 200 || $response === false) { return false; } return json_decode($response, true); } // 使用示例: $result = call_zhipu_chatglm('your_api_key_here', '你好,请用中文简单介绍你自己'); if ($result && isset($result['choices'][0]['message']['content'])) { echo $result['choices'][0]['message']['content']; } else { echo '调用失败或响应格式异常'; }
返回结果解析和常见陷阱
成功响应的 JSON 结构固定,但新手常在这里出错:
-
$result['choices'][0]['message']['content']是你要的文本,但必须先判空——choices可能为空数组(如配额用尽) - 如果返回
{"Error":{"code":"invalid_apikey","message":"Invalid API Key"}},说明Authorization头格式错或密钥无效 - 如果返回
{"error":{"code":"rate_limit_exceeded","message":"Rate limit exceeded"}},不是代码问题,是账号免费额度已用完,需升级或等重置 - 不要尝试用
file_get_contents()+stream_context_create()替代curl—— 智谱 API 对Connection和Transfer-Encoding敏感,curl更可控
真正难的不是写函数,而是把错误响应里的 error.code 和文档一一对照;很多“调不通”其实只是密钥没权限调用指定模型,或者模型名拼错了。