phpfacebookfacebook-graph-apifacebook-php-sdk

POST message with Facebook SDK PHP does not work as expected


This is my code:

$fb = new \Facebook\Facebook([
    'app_id'                         => $appId,
    'app_secret'                     => $secret,
    'default_graph_version'          => $default_graph_version,
    'pseudo_random_string_generator' => 'openssl',
    //'http_client'                    => new \Http\Client\Curl\Client(), //POST request with token error
    'http_client'                    => new \GuzzleHttp\Client() //POST request with token error
]);
$fb->setDefaultAccessToken($access_token);

// this response is OK

$namespace = $fb->get(
    '/'.$appId)->getGraphNode()->getField('namespace',
    $access_token
);

// this response with ERROR:

$data = ['message' => 'Hello World!'];
$response = $fb->post(
    '/'.$pageId.'/feed',
    $data,
    $page_access_token
);

This is error:

(#200) If posting to a group, requires app being installed in the group, and \ either publish_to_groups permission with user token, or both pages_read_engagement \ and pages_manage_posts permission with page token; If posting to a page, \ requires both pages_read_engagement and pages_manage_posts as an admin with
sufficient administrative permission.

All other GET requests are OK also.

When I make same POST request with curl like this, then response is OK and I got id of posted article.

$data = [
    'message' => 'Hello World!',
    'access_token' => $page_access_token,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$default_graph_version.'/'.$pageId.'/feed');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$strResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
curl_close($ch);

Now tell me why the POST request with Facebook SDK does not work, but the same request with curl works? And how to fix it?


Solution

  • Afted hard investigation I found, that some part of Guzzle library is wrong.

    \GuzzleHttp\Psr7\HttpFactory is:

    public function createRequest(string $method, $uri, array $headers = []): RequestInterface
    {
        return new Request($method, $uri, $headers);
    }
    

    but it shoul be like this:

    public function createRequest(string $method, $uri, array $headers = [], $body = null, $protocolVersion = '1.1'): RequestInterface
    {
        return new Request($method, $uri, $headers, $body, $protocolVersion);
    }
    

    After I changed this code, all post requests works as expected.