Laravel函数只返回NULL

时间:2017-09-25 17:29:07

标签: php laravel api response

我需要连接到API来申领优惠券。在API doc,我看到:

POST /api/v1/vouchers/{voucherId}/claim

{
    "Participant": {
        "FirstName": "John",
        "LastName": "James,
        "Telephone": "08456 127 127",
        "EmailAddress": "tim@asdasd.net",
        "PostCode": "ASD 9HX",
        "HouseNameNumber": "2",
        "Street": "Bridge Road2",
        "Locality": "LONDON",
        "Town": "Aylesbury",
        "County": "Bucks"
    },
    "ExperienceDate": "2017-10-01T00:00:00"
}

基于此,我使用Laravel框架编写我的函数:

public function testclaim()
    {

$client = new GuzzleHttp\Client;
$headers = ['Content-Type' => 'application/json'];
try {
$res = $client->post('https://api.example.com/api/v1/vouchers/244775_2-H8SC/claim', [
    'headers'=>$headers,
     'auth' => [
        'JAMES-JJ', 'ajhsdajsdhaj32423'
    ],
    'json' => [
    'Participant' => [
        "FirstName"=> "asdasd",
        "LastName"=> "asdasd",
        "Telephone"=> "08456 127 127",
        "EmailAddress"=> "tim@asdasd.net",
        "PostCode"=> "HP18 9HX",
        "HouseNameNumber"=> "1",
        "Street"=> "Bridge Road",
        "Locality"=> "Ickford",
        "Town"=> "Aylesbury",
        "County"=> "Bucks"
    ],
    'ExperienceDate' => '2017-11-01T00:00:00'
]
            ]);
$res = json_decode($res->getBody()->getContents(), true);

    return response()->json(['data' => $res]);

//dd($res);
}
catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $result =  json_decode($response->getBody()->getContents());

    return response()->json(['data' => $result]);

    }

    }

现在,当我运行此功能时,我得到:

{"data":null}

有人看到我的代码出了什么问题? 如何解决这个问题?

我也尝试不使用标头发送请求,但我再次从API获得相同的响应。

1 个答案:

答案 0 :(得分:0)

如果要将主体转换为数组,则不需要getContents()。