【问题标题】:Using Guzzle in Laravel with POST在 Laravel 中使用 Guzzle 和 POST
【发布时间】:2020-11-19 20:53:13
【问题描述】:

我想向外部 API 发送 POST 请求

这是我的调用方法

public function recursub(Request $request) {

  $users = User::where('cancel_trial', 1)->get();
  foreach($users as $user) {    
    //dd($user->email);
    $url= 'https://api.paystack.co/subscription';
     $client = new Client();
     $response = $client->request('POST', $url, [
       'headers' => [
        'Content-Type' => 'application/json',
         'Authorization' => 'Bearer sk_test_0994##############',
       ],
       'form_params' => [
        'customer' => '233########',
        'plan' => 'PLN_###########',
     ]
     ]);
     dd($response->getBody());
     //dd($response->getBody()->getContents());
    }


  }

但是当我调用端点时,我不断收到此错误

GuzzleHttp\Exception\ClientException (400) 客户端错误:POST https://api.paystack.co/subscription 导致 400 Bad Request 响应:{ "status": false, "message": "请求正文无法解析。确保请求正文与指定的 content-ty 匹配(截断...)

【问题讨论】:

  • 你用的是什么 laravel 版本?
  • Laravel 6.90 版

标签: laravel


【解决方案1】:

您似乎向 API 发送了错误的请求。

如果你设置了 application/json 也许你应该在 body 中传递参数,而不是在 form 参数中:

$response = $client->request('POST', $url, [
       'headers' => [
        'Content-Type' => 'application/json',
         'Authorization' => 'Bearer sk_test_0994##############',
       ],
       'body' => json_encode([
           'customer' => '233########',
           'plan' => 'PLN_###########',
     ])
]);

另一个可能有用的信息是您可以使用 ['http_errors' => false] 选项 (http://docs.guzzlephp.org/en/stable/request-options.html#http-errors) 禁用异常。

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2020-03-28
    • 2015-07-18
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2018-11-02
    • 2016-02-13
    • 2016-02-14
    相关资源
    最近更新 更多