繁体   English   中英

如何使用 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>

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

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

随意让它成为你自己的。 希望它只需进行最少的更改即可工作。

<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>

您需要对https://login.windows.net/common/oauth2/tokenhttps://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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM