尝试通过SendGrid联系人API添加新联系人时出现错误400



每当我试图通过API添加新联系人时,我都会收到400错误。

到目前为止,这是我的代码:

$emails = json_decode('{
"list_ids": [
"LIST_ID_HERE",
],
"contacts": [
{
"email": "example@example.com",
}
]
}');
$sendgrid = new SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->client->marketing()->contacts()->put($emails);;
print $response->statusCode();
print_r($response->headers());
print $response->body();
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."n";
}

我试过使用和不使用list_ids,但得到了相同的响应。以下是该代码的确切输出:

400Array ( [0] => HTTP/1.1 400 Bad Request [1] => Server: nginx [2] => Date: Sun, 28 Aug 2022 02:41:11 GMT [3] => Content-Type: application/json [4] => Content-Length: 50 [5] => Connection: keep-alive [6] => x-amzn-requestid: 919d1e69-9f8e-46a0-b2d2-72dcca1753c3 [7] => access-control-allow-origin: * [8] => access-control-allow-headers: AUTHORIZATION, Content-Type, On-behalf-of, x-sg-elas-acl, X-Recaptcha, X-Request-Source [9] => x-amz-apigw-id: XjZXMHBWPHcF_pQ= [10] => access-control-allow-methods: PUT,OPTIONS,DELETE,OPTIONS [11] => access-control-expose-headers: Link, Location [12] => x-amzn-trace-id: Root=1-630ad5c7-5825916353f578786cb7c908;Sampled=0 [13] => x-envoy-upstream-service-time: 105 [14] => referrer-policy: strict-origin-when-cross-origin [15] => x-content-type-options: nosniff [16] => x-ratelimit-limit: 200 [17] => x-ratelimit-remaining: 199 [18] => x-ratelimit-reset: 49 [19] => [20] => ) {"errors":[{"field":"","message":"invalid JSON"}]}

我假设我做错了什么,但这些代码大部分是直接从SendGrid API文档中复制的。

我很感激任何帮助,我只是想在下周上线之前把它做好。我不想把这个功能排除在生产构建之外。

谢谢!

我认为您的JSON无效。JSON不处理尾随逗号,因此列表ID后面和电子邮件地址后面的逗号会使其无效。遗憾的是,当给定无效的JSON时,json_decode不会抛出错误,它只是返回null

试试这个:

$emails = json_decode('{
"list_ids": [
"LIST_ID_HERE"
],
"contacts": [
{
"email": "example@example.com"
}
]
}');

相关内容

  • 没有找到相关文章

最新更新