Search code examples
symfonyfirebase-cloud-messagingpayloadsymfony-http-client

HTTP/2 400 returned for URL when using symfoy HTTP Client to make post request


I want to transform a http post request tested with post man to symfony action :

payload

I want to transform the payload to a json array in symfony to send data to url :

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Routing\Annotation\Route;

    class PushNotificationController extends AbstractController
    {
        /**
         * @Route("/api/push_notification", name="push_notification")
         */
        public function index()
        {
            $httpClient = HttpClient::create();
            $response = $httpClient->request('POST', 'https://fcm.googleapis.com/fcm/send', [
                'headers' => [
                    // 'Accept' => 'application/json',
                    // "Content-Type" => "application/json; charset=UTF-8",
                    'Authorization' => 'Bearer token'
                ],
                'json' => [
                    'notification' => [
                        'title' => 'Portugal vs. Denmark',
                        'message' => 'My Notification Message',
                        'body' => '5 to 1',
                    ],
                    'token' => 'token'
                ],
            ]);
    
            $statusCode = $response->getStatusCode();
            // $statusCode = 200
            $contentType = $response->getHeaders()['content-type'][0];
            // $contentType = 'application/json'
            $content = $response->getContent();
            // $content = '{"id":521583, "name":"symfony-docs", ...}'
            $content = $response->toArray();
            // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
    
            return $content;
        }
    }

I got this error :

I think it's an error about the payload . any suggestions please ?

error


Solution

  • Error 400 Invalid Json input:

    Only applies for JSON requests. Indicates that the request could not be parsed as JSON, or it contained invalid fields (for instance, passing a string where a number was expected). The exact failure reason is described in the response and the problem should be addressed before the request can be retried.

    so i guess you need to review your json that you sent. also , you can use some of the FCM Bundle from Knp or git.