PHP-OAuth2 icon indicating copy to clipboard operation
PHP-OAuth2 copied to clipboard

Issue with POST json data

Open stanleyliu1006 opened this issue 9 years ago • 2 comments

Hi

I am using the snippet code below for POST an new event, but failed with 400 Error. just wondering if I missed something or can you please provide me the sample code of POST data?

My email address is: [email protected]

setAccessTokenType(2,$client->getClientSecret()); $param ='{"event":{"name":"ACF API Test","intro":"protect our environment","start_time":"2016-02-08T17:00:00-00:00","end_time":"2016-02-08T19:00:00-00:00","status":"unlisted"}}'; $response = $client->fetch($this->nb_baseapiUrl . '/api/v1/events/', $param, 'POST'); print_r($response); ?>

Regards Stanley

stanleyliu1006 avatar Jan 29 '16 01:01 stanleyliu1006

This library was not prepared to POST a data in JSON format using CURL

Here's a working sample:

$params = array(
    "firstName" => "John",
    "lastName" => "Doe",
    "email1" => array(
        "value" => "[email protected]",
        "default" => true
     )                          
);

$header = array( 
    'Content-Type' => 'application/json;charset=utf-8', 
    'Content-Length' => strlen(json_encode($params))
);

$response = $client->fetch('https://graph.facebook.com/me', $params, 'PUT', $header);

var_dump($response);

Modifications Function: executeRequest() File: Client.php Line: 424 to 427

From this code:

if(is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) {
    $parameters = http_build_query($parameters, null, '&');
}
$curl_options[CURLOPT_POSTFIELDS] = $parameters;

Replace it with this code:

if(strpos($http_headers['Content-Type'], 'x-www-form-urlencoded') !== false) {
    if(is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) {
        $parameters = http_build_query($parameters, null, '&');
    }
    $curl_options[CURLOPT_POSTFIELDS] = $parameters;
} else {
    $curl_options[CURLOPT_POSTFIELDS] = json_encode($parameters);

    if (is_array($parameters) && count($parameters) > 0) {
        $url .= '?' . http_build_query($parameters, null, '&');
    } elseif ($parameters) {
        $url .= '?' . $parameters;
    }
}

bcgoodmate avatar Apr 04 '16 09:04 bcgoodmate

By now, you can also pass the $parameters already JSON encoded AFAIK, if you also provide the JSON Content-Type header. You're already encoding it for the Content-Length header anyway. At least as long as you're not also using ACCESS_TOKEN_URI. That currently throws an exception in the Client::fetch() method.

DanMan avatar Oct 27 '22 12:10 DanMan