gpt4 book ai didi

php - 如何使用(发送网格)php api 在列表中添加联系人

转载 作者:行者123 更新时间:2023-12-03 00:08:14 24 4
gpt4 key购买 nike

我正在尝试使用 php api 在列表中添加联系人,但它抛出以下代码段错误

string(51) "{"errors":[{"message":"request body is invalid"}]} " {"email":"hello@test.com","first_name":"hh","last_name":"User"}

我正在使用以下代码片段:

$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists/12345/recipients'; //12345 is list_id
$params = array(
'email' => 'hello@test.com',
'first_name' => 'hh',
'last_name' => 'User'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.XXXXXXXX");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;

谁能告诉我如何解决这个问题。

最佳答案

您应该检查您发送的请求,并将正文中的 JSON 与有效请求进行比较,以真正了解发生了什么。此处 json_encode 的输出将是一个数组,但 API 需要一个对象。您的请求正文需要是

[{"email":"hello@test.com","first_name":"hh","last_name":"User"}]

你现在正在做的是发送

{"email":"hello@test.com","first_name":"hh","last_name":"User"}

您可以通过多种方式解决此问题。您可以使用您最喜欢的字符串操作函数来附加括号,也可以跳过编码并将 JSON 作为字符串发送(因为您指定了内容类型)。

关于php - 如何使用(发送网格)php api 在列表中添加联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37805193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com