PHP 调用示例
本页面提供 PHP 调用 51API 的完整示例。
环境要求
- PHP 7.4+
- 启用 cURL 扩展
安装依赖(可选)
bash
composer require guzzlehttp/guzzle1
bash
# 使用 PHP 内置的 cURL 扩展
# 无需安装额外依赖1
2
2
基础调用示例
使用 cURL
php
<?php
$apiKey = getenv("NEWAPI_API_KEY"); // 从环境变量获取
$url = "https://www.51api.org/v1/chat/completions";
$data = [
"model" => "gpt-4o",
"messages" => [
["role" => "system", "content" => "你是一个有帮助的助手。"],
["role" => "user", "content" => "你好!"]
]
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . $apiKey
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "cURL 错误: " . curl_error($ch);
} elseif ($httpCode !== 200) {
echo "请求失败,状态码: " . $httpCode . "\n";
echo $response;
} else {
$result = json_decode($response, true);
echo "AI: " . $result['choices'][0]['message']['content'];
}
curl_close($ch);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
封装函数
将 API 调用封装为可复用的函数:
php
<?php
/**
* 51API 调用封装类
*/
class Api51Client {
private string $apiKey;
private string $baseUrl;
private int $timeout;
public function __construct(
string $apiKey,
string $baseUrl = "https://www.51api.org/v1",
int $timeout = 120
) {
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
$this->timeout = $timeout;
}
/**
* 发送聊天请求
*
* @param string $model 模型名称
* @param array $messages 消息数组
* @param array $options 其他选项
* @return array 响应数据
*/
public function chat(string $model, array $messages, array $options = []): array {
$data = array_merge([
"model" => $model,
"messages" => $messages
], $options);
return $this->request("/chat/completions", $data);
}
/**
* 简单对话(单条消息)
*/
public function ask(string $model, string $question): string {
$messages = [
["role" => "user", "content" => $question]
];
$response = $this->chat($model, $messages);
return $response['choices'][0]['message']['content'] ?? '';
}
/**
* 发送 HTTP 请求
*/
private function request(string $endpoint, array $data): array {
$url = $this->baseUrl . $endpoint;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . $this->apiKey
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL 错误: " . $error);
}
if ($httpCode !== 200) {
throw new Exception("API 错误 ($httpCode): " . $response);
}
return json_decode($response, true);
}
}
// 使用示例
$api = new Api51Client(getenv("NEWAPI_API_KEY"));
try {
$reply = $api->ask("gpt-4o", "你好!");
echo "AI: " . $reply . "\n";
} catch (Exception $e) {
echo "错误: " . $e->getMessage() . "\n";
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
流式响应
php
<?php
$apiKey = getenv("NEWAPI_API_KEY");
$url = "https://www.51api.org/v1/chat/completions";
$data = [
"model" => "gpt-4o",
"messages" => [
["role" => "user", "content" => "讲一个简短的故事"]
],
"stream" => true
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . $apiKey
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => false, // 不缓存响应
CURLOPT_TIMEOUT => 300,
// 流式处理回调
CURLOPT_WRITEFUNCTION => function($ch, $data) {
$lines = explode("\n", $data);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) continue;
if (strpos($line, 'data:') === 0) {
$jsonStr = trim(substr($line, 5));
if ($jsonStr === '[DONE]') {
break;
}
$json = json_decode($jsonStr, true);
if (isset($json['choices'][0]['delta']['content'])) {
echo $json['choices'][0]['delta']['content'];
flush(); // 立即输出
}
}
}
return strlen($data);
}
]);
echo "AI: ";
curl_exec($ch);
echo "\n";
if (curl_errno($ch)) {
echo "错误: " . curl_error($ch) . "\n";
}
curl_close($ch);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
多轮对话
php
<?php
class ChatSession {
private Api51Client $api;
private string $model;
private array $messages = [];
public function __construct(Api51Client $api, string $model = "gpt-4o") {
$this->api = $api;
$this->model = $model;
}
/**
* 设置系统提示
*/
public function setSystem(string $content): void {
// 移除旧的 system 消息
$this->messages = array_filter($this->messages, function($msg) {
return $msg['role'] !== 'system';
});
// 添加新的 system 消息到开头
array_unshift($this->messages, [
"role" => "system",
"content" => $content
]);
}
/**
* 发送消息并获取回复
*/
public function send(string $message): string {
// 添加用户消息
$this->messages[] = [
"role" => "user",
"content" => $message
];
// 发送请求
$response = $this->api->chat($this->model, $this->messages);
$reply = $response['choices'][0]['message']['content'];
// 保存 AI 回复到历史
$this->messages[] = [
"role" => "assistant",
"content" => $reply
];
return $reply;
}
/**
* 清空对话历史
*/
public function clear(): void {
$this->messages = [];
}
}
// 使用示例
$api = new Api51Client(getenv("NEWAPI_API_KEY"));
$session = new ChatSession($api, "gpt-4o");
$session->setSystem("你是一个友好的助手。");
echo "AI: " . $session->send("我叫小明") . "\n";
echo "AI: " . $session->send("我刚才说我叫什么?") . "\n";1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
使用 Guzzle HTTP
如果你使用 Composer,可以用 Guzzle:
安装
bash
composer require guzzlehttp/guzzle1
示例
php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$apiKey = getenv("NEWAPI_API_KEY");
$client = new Client([
'base_uri' => 'https://www.51api.org/v1/',
'timeout' => 120,
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $apiKey
]
]);
try {
$response = $client->post('chat/completions', [
'json' => [
'model' => 'gpt-4o',
'messages' => [
['role' => 'user', 'content' => '你好!']
]
]
]);
$data = json_decode($response->getBody(), true);
echo "AI: " . $data['choices'][0]['message']['content'];
} catch (Exception $e) {
echo "错误: " . $e->getMessage();
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
常见问题
cURL 超时
增加超时时间:
php
curl_setopt($ch, CURLOPT_TIMEOUT, 600); // 10 分钟1
SSL 证书问题
如果遇到 SSL 问题:
php
// 仅用于测试环境,生产环境不建议禁用
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);1
2
2
其他问题
查看 完整常见问题
