Forum Discussion

wingmanzz's avatar
wingmanzz
Regular Visitor
5 years ago
Solved

PHP, Curl to get embed token via API GenerateToken returns 404 using service principal

Hi all,   This snippet of code:   <?php /* Get token using a POST request */ $clientId = 'xxx'; $clientSecret = 'xxx'; $tenantId = 'xxxx'; $urlAccessToken = "https://login.windows.net/$tena...
  • wingmanzz's avatar
    wingmanzz
    5 years ago

    So we dug into this a little bit more and were able to debug it..it was an error in the curl_setopts. posting fixed code here, in case anyone runs across this issue.

    <?php
    /* Get token using a POST request */
    
    $clientId = 'xxx';
    $clientSecret = 'xxx';
    $tenantId = 'xxxx';
    $urlAccessToken = "https://login.windows.net/$tenantId/oauth2/token";
    $resource = 'https://analysis.windows.net/powerbi/api';
    $group = 'xxx';
    $report ='xxx';
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://login.microsoftonline.com/$tenantId/oauth2/token");
    
    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(
    'resource' => $resource,
    'client_id' => $clientId,
    'client_secret' => $clientSecret,
    'grant_type' => 'client_credentials'
    ));
    
    $data = curl_exec($ch);
    curl_close($ch);
    
    $data_obj = json_decode($data);
    $access_token = $data_obj->{"access_token"};
    $headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer $access_token"
    );
    
    
    $url = "https://api.powerbi.com/v1.0/myorg/groups/$group/reports/$report/GenerateToken";
    #$url ="https://api.powerbi.com/v1.0/myorg/groups/$group/reports";
    $post_params = array(
    'accessLevel' => 'View'
    );
    
    $payload = json_encode($post_params);
    
    $ch2 = curl_init( $url );
    curl_setopt( $ch2, CURLINFO_HEADER_OUT, true);
    curl_setopt( $ch2, CURLOPT_POSTFIELDS, $payload);
    curl_setopt( $ch2, CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch2, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch2, CURLOPT_FAILONERROR, true);
    $response = curl_exec( $ch2 );
    
    if (curl_errno($ch2)) {
        $error_msg = curl_error($ch2);
    }
    echo $response;
    curl_close($ch2);
    
    if (isset($error_msg)) {
        echo $error_msg;
    }
    
    ?>