mkHun
mkHun

Reputation: 5927

Get acess token from BOX API using php?

I'm trying to get the access token from box API the following curl is working when I run it on terminal

curl https://api.box.com/oauth2/token \
-d  'grant_type=authorization_code&code=CODE&client_id=CLIENT_ID&client_secret=secret_ID' \
-X POST  # This is working.

Above one is working but the same thing I have tried with PHP but which is throws the following error {"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}1 the following code I have tried

$access_token_url = "https://api.box.com/oauth2/token";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'grant_type'=>'authorization_code', 
    'code'=>'code',
    'client_id'=>'id',
    'client_secret'=>'secret'
    ));
$response = curl_exec($ch);
curl_close($ch);

I don't know what is the actual problem.

Upvotes: 0

Views: 792

Answers (3)

simondarke
simondarke

Reputation: 56

I think it's because the command line example is making a POST request but the PHP curl request isn't. The below code should hopefully get you on the right track.

<?php
$access_token_url = "https://api.box.com/oauth2/token";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 
    array(
    'grant_type'=>'authorization_code', 
    'code'=>'code',
    'client_id'=>'id',
    'client_secret'=>'secret'));

$response = curl_exec($ch);
curl_close($ch);
?>

Upvotes: 1

Neodan
Neodan

Reputation: 5252

The data you must set as the POST parameters, not the HEADER parameters

$access_token_url = "https://api.box.com/oauth2/token";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'grant_type'=>'authorization_code', 
    'code'=>'code',
    'client_id'=>'id',
    'client_secret'=>'secret'
]));
$response = curl_exec($ch);
curl_close($ch);

Upvotes: 1

Elzo Valugi
Elzo Valugi

Reputation: 27856

You are sending different parameters together. -d option sends a POST request so you cannot mix all params in a GET. Do the request as in the provided example:

curl https://api.box.com/oauth2/token \
-d 'grant_type=authorization_code' \
-d 'code=<MY_AUTH_CODE>' \
-d 'client_id=<MY_CLIENT_ID>' \
-d 'client_secret=<MY_CLIENT_SECRET>' \
-X POST

Upvotes: 0

Related Questions