API 使用 Lumen + Guzzle 调用时出现数组到字符串转换错误

API Call with Lumen + Guzzle gives error Array to string conversion

我正在尝试将 https://api.binance.com/api/v3/ticker/price 作为 json 对象调用,但是当我使用 json_decode.我在这里做错了什么?

<?php namespace App\Helpers;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

class Ticker
{
    private $client;

    public function __construct()
    {
        $this->client = new Client(['base_uri' => 'https://api.binance.com/api/']);
    }

    public function update()
    {

        $response = json_decode($this->client->get('v3/ticker/price')->getBody());
        return $response;
    }
}

guzzle 响应的 getBody 方法不是 return 字符串,它 return 是一个流。

尝试:

$this->client->get('v3/ticker/price')->getBody()->getContents()

json_decode 正在将 guzzle 响应字符串转换为 php 数组。然后,您将从控制器方法中 returning 该数组。无论您从控制器 return 做什么,Laravel 都会尝试将其转换为字符串。因为您已经 return 编辑了一个数组,所以您得到了数组到字符串的转换错误。

要么不解码 guzzle 响应,要么将其转换为字符串或您想要的其他响应。