如何使用 javascript 和 PHP 自动生成嵌入令牌?

How to auto generate embed token using javascript and PHP?

我也在 PowerBI 社区上发布了这个,但没有得到任何关注:https://community.powerbi.com/t5/Developer/Auto-Generate-Embed-Token-using-Javascript-and-PHP/td-p/1316556

我的报告在测试中使用 Microsoft Embed Token - Generate Token(此处 https://docs.microsoft.com/en-us/rest/api/power-bi/embedtoken/generatetoken)和 PowerShell 命令生成的令牌进行测试。

我得到了正确的格式,更改了一些配置并使它在本地主机上按照我想要的方式运行。

为了弄清楚,我还通过 powerbi.com(这里是 https://app.powerbi.com/embedsetup/appownsdata)使用了自动嵌入式设置。我玩弄了下载的 vs 文件,这些文件表明可以动态生成令牌,但都是 ASP.net 和 C#,我不知道如何转换它。

现在我正在尝试将它部署到我使用 PHP 和 javascript 的站点中。

有没有人有一些示例或任何可以替换我的 ReportId、GroupId 等的东西?脚本小子风格...

这是我正在使用的完美运行的工具,除了过期的手动生成的令牌:

<script src="./dist/powerbi.js"></script>
<div id="reportContainer" style="height: 1400px; width: 1000px;"></div>

  <script>
      // Get models. models contains enums that can be used.
      var models = window['powerbi-client'].models;

      // Embed configuration used to describe what and how to embed.
      // This object is used when calling powerbi.embed.
      // This also includes settings and options such as filters.
      // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
      var embedConfiguration = {
          type: 'report',
          tokenType: models.TokenType.Embed,
          accessToken: '<manually generated token here>',
          embedUrl: 'https://app.powerbi.com/reportEmbed',
          id: '<report id here>',
          permissions: models.Permissions.Read,
          settings: {
              // filterPaneEnabled: false,
              // navContentPaneEnabled: true,
              background: models.BackgroundType.Transparent,
              panes:{
                bookmarks: {
                  visible: false
                },
                fields: {
                  expanded: false
                },
                filters: {
                  expanded: false,
                  visible: false
                },
                pageNavigation: {
                  visible: true
                },
                selection: {
                  visible: false
                },
                syncSlicers: {
                  visible: false
                },
                visualizations: {
                  expanded: false
                }
              }

          }
      };

      // Get a reference to the embedded report HTML element
      var $reportContainer = $('#reportContainer')[0];

      // Embed the report and display it within the div container.
      var report = powerbi.embed($reportContainer, embedConfiguration);
  </script>

您需要对 https://login.windows.net/common/oauth2/token and https://api.powerbi.com/v1.0/myorg/groups/{YourGroupID}/reports/ 进行两次 cURL 调用以生成嵌入访问令牌。 YourGroupID 需要更改为您要从中嵌入的 WorkspaceId。您还需要将 clientidusernamepassword 设置为适当的值。下面的代码将为您动态设置 $embedUrl$embed 变量。 ReportIdEmbedUrl 的设置方式还有一些改进空间,但这足以使嵌入正常工作。

/* Get oauth2 token using a POST request */

$curlPostToken = curl_init();

curl_setopt_array($curlPostToken, array(

CURLOPT_URL => "https://login.windows.net/common/oauth2/token",

CURLOPT_RETURNTRANSFER => true,

CURLOPT_ENCODING => "",

CURLOPT_MAXREDIRS => 10,

CURLOPT_TIMEOUT => 30,

CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

CURLOPT_CUSTOMREQUEST => "POST",

CURLOPT_POSTFIELDS => array(

grant_type => 'password',

scope => 'openid',

resource => 'https://analysis.windows.net/powerbi/api',

client_id => '', // Registered App ApplicationID

username => '', // for example john.doe@yourdomain.com

password => '' // Azure password for above user

)

));

$tokenResponse = curl_exec($curlPostToken);

$tokenError = curl_error($curlPostToken);

curl_close($curlPostToken);

// decode result, and store the access_token in $embeddedToken variable:

$tokenResult = json_decode($tokenResponse, true);

$token = $tokenResult["access_token"];

$embeddedToken = "Bearer "  . ' ' .  $token;

/*      Use the token to get an embedded URL using a GET request */

$curlGetUrl = curl_init();

 

curl_setopt_array($curlGetUrl, array(

CURLOPT_URL => "https://api.powerbi.com/v1.0/myorg/groups/YourGroupID/reports/",

CURLOPT_RETURNTRANSFER => true,

CURLOPT_ENCODING => "",

CURLOPT_MAXREDIRS => 10,

CURLOPT_TIMEOUT => 30,

CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

CURLOPT_CUSTOMREQUEST => "GET",

CURLOPT_HTTPHEADER => array(

"Authorization: $embeddedToken",

"Cache-Control: no-cache",

),

));

$embedResponse = curl_exec($curlGetUrl);

$embedError = curl_error($curlGetUrl);

curl_close($$curlGetUrl);

if ($embedError) {

echo "cURL Error #:" . $embedError;

} else {

$embedResponse = json_decode($embedResponse, true);

$embedUrl = $embedResponse['value'][0]['embedUrl']; // this is just taking the first value. you need logic to find the report you actually want to embed. This EmbedUrl needs to match the corresponding ReportId you later use in the JavaScript.

}

现在,在您进行嵌入的 javascript 中,您可以传入 ReportID、$embedUrl$token 以成功嵌入报告。

script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<script src="scripts/powerbi.js"></script>

<div id="reportContainer"></div>

 

<script>

// Get models. models contains enums that can be used.

var models = window['powerbi-client'].models;

// Embed configuration used to describe the what and how to embed.

// This object is used when calling powerbi.embed.

// This also includes settings and options such as filters.

// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.

var embedConfiguration= {

type: 'report',

id: 'YourReportId', // the report ID

embedUrl: "<?php echo $embedUrl ?>",

accessToken: "<?php echo $token; ?>" ,

};

var $reportContainer = $('#reportContainer');

var report = powerbi.embed($reportContainer.get(0), embedConfiguration);

</script>

感谢@vvvv4d 让我走上正轨。对于其他人,下面是我使用的格式的工作代码。在将 5 个值更改为适用于您的报告的值后,它应该主要是即插即用的。

请注意,由于似乎与本地主机和 PowerBI 服务器之间的身份验证问题有关的错误,我无法让它在本地主机上工作。它确实适用于实时站点。

您可以随意制作自己的作品。希望它只需进行极少的更改即可工作。

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="./dist/powerbi.js"></script>

<div id="reportContainer" style="height: 1400px; width: 1000px;"></div>

<?php
    // All the values used below can be generated at https://app.powerbi.com/embedsetup/appownsdata
    
    /* Get oauth2 token using a POST request */
    $curlPostToken = curl_init();
    curl_setopt_array($curlPostToken, array(
        CURLOPT_URL => "https://login.windows.net/common/oauth2/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array(
            grant_type => 'password',
            scope => 'openid',
            resource => 'https://analysis.windows.net/powerbi/api',
            
            // Make changes Start
            client_id => '#####################', // Registered App Application ID
            username => 'john.doe@yourdomain.com', // for example john.doe@yourdomain.com
            password => '#####################', // Azure password for above user
            // Make changes End
        )
    ));

    $tokenResponse = curl_exec($curlPostToken);
    $tokenError = curl_error($curlPostToken);
    curl_close($curlPostToken);

    // decode result, and store the access_token in $embeddedToken variable:
    $tokenResult = json_decode($tokenResponse, true);
    $token = $tokenResult["access_token"];
    $embeddedToken = "Bearer "  . ' ' .  $token;

    /* Use the token to get an embedded URL using a GET request */
    $curlGetUrl = curl_init();
    curl_setopt_array($curlGetUrl, array(
        
        // Make changes Start
        CURLOPT_URL => "https://api.powerbi.com/v1.0/myorg/groups/#####################/reports/", // Enter your Workspace ID, aka Group ID
        // Make changes End
        
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Authorization: $embeddedToken",
            "Cache-Control: no-cache",
        ),
    ));

    $embedResponse = curl_exec($curlGetUrl);
    $embedError = curl_error($curlGetUrl);
    curl_close($$curlGetUrl);
    if ($embedError) {
        echo "cURL Error #:" . $embedError;
        } else {
            $embedResponse = json_decode($embedResponse, true);
            $embedUrl = $embedResponse['value'][0]['embedUrl']; // this is just taking the first value. you need logic to find the report you actually want to embed. This EmbedUrl needs to match the corresponding ReportId you later use in the JavaScript.
        }
?>



<script>
    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.

    var embedConfiguration= {
        type: 'report',
        
        // Make changes Start
        id: '#####################', // the report ID
        // Make changes End
        
        embedUrl: "<?php echo $embedUrl ?>",
        accessToken: "<?php echo $token; ?>",
        permissions: models.Permissions.Read,
        settings: {
            background: models.BackgroundType.Transparent,
            panes:{
                bookmarks: {
                    visible: false
                },
                fields: {
                    expanded: false
                },
                filters: {
                    expanded: false,
                    visible: false
                },
                pageNavigation: {
                    visible: false
                },
                selection: {
                    visible: false
                },
                syncSlicers: {
                    visible: false
                },
                visualizations: {
                    expanded: false
                }
            }
        }
    };

    var $reportContainer = $('#reportContainer');
    var report = powerbi.embed($reportContainer.get(0), embedConfiguration);

</script>