为什么我对使用Guzzle的API发布请求不起作用?

时间:2018-06-18 13:36:19

标签: php laravel guzzle

我想向API发布请求以创建新客户端,但它出现错误:

Client error: `POST https://testname.app.invoicexpress.com/document-type.json?api_key=...` 
resulted in a `404 Not Found` response: <!doctype html> 
 <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en">
 <![endif]--> <!--[if IE 7]> <html class="n (truncated...)

在文档&#34; https://developers.invoicexpress.com/docs/versions/2.0.0/resources/invoices&#34;说要创建一个新的客户端以及发票,curl命令就像:

  curl --request POST \
      --url 'https://account_name.app.invoicexpress.com/:document-type.json?api_key=YOUR%20API%20KEY%20HERE' \
      --header 'accept: application/json' \
      --header 'content-type: application/json' \
      --data '{"invoice":{"date":"03/12/2017","due_date":"03/12/2017","client":{"name":"Client Name","code":"A1"},"items":[{"name":"Item Name","description":"Item Description","unit_price":"100","quantity":"5"}]}}'

但是使用下面的代码而不是curl命令,它会显示错误。

public function generateInvoice()
{

    $client = new \GuzzleHttp\Client();

    $array = [
        'invoice' => [
            'date' => '03/12/2017',
            'due_date' => '03/12/2017',
            'client' => [
                'name' => 'Client Name',
                'code' => 'A1'
            ],
            'items' => [
                [
                    'name' => 'Item Name',
                    'description' => 'Item Description',
                    'unit_price' => '100',
                    'quantity' => '5'
                ]
            ]
        ]
    ];

    $response = $client->request('POST', 'https://testname.app.invoicexpress.com/invoices.json', [
        'query' => ['api_key' => '...'], 'form_params' => [$array],
    ]);
    dd($response->getStatusCode());

}

Wihout []和&#39; form_params&#39;中的$ array所示:

 Client error: 
   `POST https://testname.app.invoicexpress.com/invoices.json?api_key=...` resulted 
   in a `422 Unprocessable Entity` 
   response: {"errors":[{"error":"Items element should be of type    array"}]}

2 个答案:

答案 0 :(得分:0)

尝试使用'json'

重命名param'form_param'

喜欢:'form_params'=&gt; [$ array] to'json'=&gt; [$阵列]

答案 1 :(得分:0)

嗨,对于遇到同样问题的人,请使用此类通过食口发送数组

RequestOptions::JSON => your_array   

也使用GET方法,这里是一个示例:

$response = $client->request('GET', $url, [
            'http_errors'        => true,
            RequestOptions::JSON => your_array,
        ]);

如果这不起作用,请记住请求网址必须包含ssl