OAuth2 Token PHP



PHP Snippet 1:

$data = array(
    'grant_type' => 'password',
    'scope'      => 'read write',
    'username'   => $api,
    'password'   => $api,
);

PHP Snippet 2:

$base_url = 'https://example.com/oauth/token';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'client_id'     => YOUR-CLIENT-ID,
        'client_secret' => YOUR-CLIENT-SECRET,
        'username'      => YOUR-USERNAME-OR-EMAIL,
        'password'      => YOUR-PASSWORD,
        'grant_type'    => 'password'
));

$data = curl_exec($ch);

$auth_string = json_decode($data, true); // token will be with in this json

PHP Snippet 3:

$ch_curl = curl_init();
curl_setopt($ch_curl, CURLOPT_URL, "endpoint url");
curl_setopt($ch_curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_curl, CURLOPT_POSTFIELDS, "grant_type = your grant_type");
curl_setopt($ch_curl, CURLOPT_POST, 1);   
 
$headers = array(); 
$headers[] = "Accept: application/json";
// base64_encode client id and password
$headers[] = "Authorization: Basic ABCDEFGHIJKLM123456"; 
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch_curl, CURLOPT_HTTPHEADER, $headers);

$token = curl_exec($ch_curl);
echo $token;
curl_close($ch_curl);

PHP Snippet 4:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(        
    'grant_type'    => 'client_credentials',    # https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/        
    'scope'         => $scope,  
)));

$headers[] = "Authorization: Basic " . base64_encode($client_id . ":" . $client_secret);
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$data = curl_exec($ch);
$auth = json_decode($data, true); // token will be with in this json

var_dump( $auth );