如何使用(发送网格)php api在列表中添加联系人 [英] How to add contact in list using (Send Grid) php api

查看:108
本文介绍了如何使用(发送网格)php api在列表中添加联系人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add contact in list using php api but its throwing bellow snippet error


string(51){errors :[{message:请求正文无效}]}{email:hello@test.com,first_name:hh,last_name:User}

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

我使用的是以下片段代码:

I am using bellow snippet code:

$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;

任何人都可以告诉我如何解决这个问题。

Can any one tell me how to resolve this issue.

推荐答案

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

You should inspect the request that you are sending and compare the JSON in the body to a valid request to really see what's happening. The output of your json_encode here will be an array, but the API expects an object. Your request body needs to be

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

/ p>

And what you are doing right now is sending

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

您可以通过以下几种方法进行修复。你可以使用你最喜欢的字符串操作函数来添加方括号,也可以跳过编码并将JSON作为字符串发送(因为你指定了内容类型)。

You can fix this several ways. You could use your favorite string manipulation functions to append the brackets, or you could skip the encoding and send the JSON as a string (since you're specifying the content type).

这篇关于如何使用(发送网格)php api在列表中添加联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆