Integrating Power BI with CodeIgniter: A Step-by-Step Guide

To integrate Power BI with a PHP CodeIgniter application, I’ll guide you through the steps and how you might share it effectively on your WordPress blog. This guide will cover authentication, embedding reports, and handling data securely.

Step 1: Prerequisites

  1. Power BI Account: Ensure you have a Power BI Pro or Premium account with access to the workspace containing the reports.
  2. Azure AD Application: Register an application in Azure Active Directory (AD) to authenticate your application and access Power BI reports.

Step 2: Registering an Application in Azure AD

  1. Go to the Azure portal, navigate to Azure Active Directory > App registrations.
  2. Click New registration and provide:
  • Name: Choose a name for your app.
  • Redirect URI: Set it to your callback URL, for example, https://your-codeigniter-app.com/auth/redirect.
  1. Once created, copy the Application (client) ID and Directory (tenant) ID.
  2. Navigate to Certificates & Secrets and create a new client secret. Copy this as well.

Step 3: Setting Up Power BI Permissions

  1. In the API permissions section, add Power BI Service > Delegated permissions.
  2. Select permissions like Report.Read.All or Dataset.ReadWrite.All depending on what access you need.

Step 4: Integrating Power BI in CodeIgniter

  1. Install GuzzleHTTP: Install Guzzle to handle HTTP requests.
   composer require guzzlehttp/guzzle
  1. Controller Setup: Create a new controller, PowerbiController.php, in CodeIgniter to handle the authentication and report embedding.

Step 5: Writing the Authentication Logic

In PowerbiController.php, add the following functions:

1. authenticate(): Fetch the access token using client credentials.

use GuzzleHttp\Client;

class PowerbiController extends CI_Controller {
    private $clientId = 'YOUR_CLIENT_ID';
    private $clientSecret = 'YOUR_CLIENT_SECRET';
    private $tenantId = 'YOUR_TENANT_ID';
    private $authorityUrl = 'https://login.microsoftonline.com/';
    private $scope = 'https://analysis.windows.net/powerbi/api/.default';

    public function authenticate() {
        $client = new Client();
        $response = $client->post($this->authorityUrl . $this->tenantId . '/oauth2/v2.0/token', [
            'form_params' => [
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret,
                'scope' => $this->scope,
                'grant_type' => 'client_credentials',
            ]
        ]);

        $token = json_decode($response->getBody())->access_token;
        return $token;
    }
}

2. embedReport($reportId, $groupId): Use the token to get an embeddable report.

public function embedReport($reportId, $groupId) {
    $token = $this->authenticate();

    $client = new Client();
    $response = $client->get("https://api.powerbi.com/v1.0/myorg/groups/{$groupId}/reports/{$reportId}", [
        'headers' => [
            'Authorization' => 'Bearer ' . $token
        ]
    ]);

    $reportDetails = json_decode($response->getBody());
    $embedUrl = $reportDetails->embedUrl;

    // Pass embedUrl to view
    $data['embedUrl'] = $embedUrl;
    $data['accessToken'] = $token;

    $this->load->view('powerbi_embed_view', $data);
}

Step 6: Embedding the Power BI Report in the View

Create powerbi_embed_view.php in your views folder to display the Power BI report.

<!DOCTYPE html>
<html>
<head>
    <title>Power BI Report</title>
    <script src="https://cdn.powerbi.com/libs/powerbi-client/2.19.0/powerbi.min.js"></script>
</head>
<body>
    <div id="reportContainer" style="height:600px; width:100%;"></div>

    <script>
        var models = window['powerbi-client'].models;
        var embedConfig = {
            type: 'report',
            tokenType: models.TokenType.Embed,
            accessToken: '<?= $accessToken ?>',
            embedUrl: '<?= $embedUrl ?>',
            settings: {
                filterPaneEnabled: false,
                navContentPaneEnabled: true
            }
        };

        var reportContainer = document.getElementById('reportContainer');
        powerbi.embed(reportContainer, embedConfig);
    </script>
</body>
</html>

Step 7: Adding Security Measures

For production environments, ensure:

  • Tokens are stored securely and refreshed regularly.
  • User permissions are validated before allowing access.

Posting on Your WordPress Blog

  1. Introduction: Explain why Power BI integration is valuable for web applications.
  2. Setup Steps: Use the steps provided here, breaking down each section for easy readability.
  3. Code Samples: Embed code snippets using a plugin like SyntaxHighlighter Evolved.
  4. Visuals: Add screenshots or a demo video to show the integration in action.
  5. Common Issues and Solutions: List possible errors like authentication failures or permission errors with solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *