繁体   English   中英

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

[英]Why doesn't my post request to an API using Guzzle not work?

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

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...)

在文档“ https://developers.invoicexpress.com/docs/versions/2.0.0/resources/invoices ”中说,要与发票一起创建新客户端, 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());

}

'form_params' 中没有 [] 并且只有 $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"}]}

尝试使用 'json' 重命名您的参数 'form_param'

比如:'form_params' => [$array] to 'json' => [$array]

嗨,对于有同样问题的人,请使用这个类通过 guzzle 发送数组

RequestOptions::JSON => your_array   

也使用 GET 方法,这里有一个例子:

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

如果这不起作用,请记住请求 url 必须具有 ssl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM