duanan6043 2018-10-26 18:02
浏览 78
已采纳

在JSON返回Body中向SendGrid添加收件人无效

First and Foremost: I am using Laravel 5.7.10, Guzzle 6.3.3, PHP 7.2.9, and SendGrid 3.9.6

I only have about 6 months of API experience, so bear with me on the jargan :)

My client Request code which is failing:

 $client->request('POST', 'contactdb/recipients', [
  'headers' => [
    'Authorization' => [MyAPIKey - Correct and Valid],
    'Content-Type' => "application/json",
  ],
  'json' => json_encode(
    [
      'email' => $emailSent['email']
    ]
  ),
]);

Under the SendGrid API Documentation, (Contacts API - Recipients /post) (https://sendgrid.com/docs/API_Reference/api_v3.html):

The user should be added as json-encoded 'data' fields. I am trying to avoid sending cURL requests for obnoxious syntax reasons, as well as better error handling. (I have written this in cURL in the past and disliked it.)

However, when I sent a request to this url, which should theoretically add them as a user and assign them a recipient ID, I am having Laravel push this error back to me:

Client error: POST https://api.sendgrid.com/v3/contactdb/recipients resulted in a 400 BAD REQUEST response: {"errors":[{"message":"request body is invalid"}]}

I know for a fact that that variable is valid, as I have checked it before this request was sent, so the issue is not the variable as far as I can tell.

Any help would be appreciated - I think that this is a simple syntax error.

I have seen code similar to this

$client->setBody(xyz)

Is this something I should look at?

Edit: Thanks to help, I have learned and figured this out.

Correct and Valid Code that works for me: (Uri is an extension of the main one in contactdb/recipients)

$res = $client->request('POST', 'contactdb/recipients', [
  'headers' => [
    'Authorization' => My API Key,
  ],
  'json' => [
    [
        'email' => $emailSent['email']
    ]
  ],
]);

As mentioned in the comments and answers, by defining the post as json, you don't have to add the content type or encode it at all. Just comma separate with pipes! :)

  • 写回答

1条回答 默认 最新

  • dongzhe3573 2018-10-26 18:13
    关注

    You do not have to json_encode the body yourself, it is done by Guzzle. Just simply pass the array:

    $client->request('POST', 'contactdb/recipients', [
      'headers' => [
        'Authorization' => [MyAPIKey - Correct and Valid],
      ],
      'json' => [
          'email' => $emailSent['email']
      ],
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)