Deezer Now Playing Card
Tags: music, webdev, php
Published: 2024-02-09 00:11:35

### Learn how to create a Deezer Now Playing Card API using PHP.

## Introduction

Deezer offers a powerful music streaming platform, and as a developer, you can tap into its capabilities by creating a Deezer app. In this guide, we'll walk you through the steps to set up a Deezer app and obtain an access token using PHP. This access token will allow you to access a user's listening history, a useful feature for music-related applications.

If you'd like to see the showcase for the card, visit this [GitHub repo](https://github.com/VukMar/deezer-now-playing-card).

## Step 1: Create a Deezer Developer App

Before you can interact with Deezer's API, you need to create a developer app on Deezer's developer platform. Follow these steps:

1. Log in to your Deezer account or create one if you don't have one.
2. Go to the Deezer Developer Portal and log in with your Deezer credentials.
3. Click on 'My Apps' and then 'Create an App.'
4. Fill in the required information for your app, including the name, description, and website.
5. Accept the terms and conditions, and click 'Create App.'

You will be asked to enter the Terms Of Use for your app when registering. Don't be alarmed, below is a link to the template for Terms of Use: [Terms of Use TEMPLATE](https://docs.google.com/document/d/1nkBFHzSH283_mBmJ0o_aviBaYN5OmEQ41Jo2hdp0EUg/edit?usp=sharing).

## Step 2: Obtain the App ID and Secret

After creating your Deezer app, you'll receive an App ID and App Secret. These are essential for authenticating your app with Deezer's API. Keep them safe and do not share them publicly.

![paragraph-image](https://backend.vukmaric.rs/api/blog/topic-images/deezer-now-playing-card/app-info-showcase.png)

## Step 3: PHP Script to Get an Access Token

```php
<?php
$app_id = 'YourAppID';
$app_secret = 'YourAppSecret';
$my_url = 'https://your-redirect-url.com/callback.php';
session_start();
$code = $_REQUEST['code'];
if (empty($code)) {
    $_SESSION['state'] = md5(uniqid(rand(), TRUE));
    $dialog_url = 'https://connect.deezer.com/oauth/auth.php?app_id=' . $app_id  . '&redirect_uri=' . urlencode($my_url) . '&perms=email,offline_access,listening_history' . '&state=' . $_SESSION['state'];
    header('Location: ' . $dialog_url);
    exit;
} else {
    if ($_REQUEST['state'] == $_SESSION['state']) {
        $token_url = 'https://connect.deezer.com/oauth/access_token.php?app_id='
            . $app_id . '&secret=' . $app_secret . '&code=' . $code;
        $ch = curl_init($token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            die('cURL error: ' . curl_error($ch));
        }
        curl_close($ch);
        parse_str($response, $token_data);
        if (isset($token_data['access_token'])) {
            $access_token = $token_data['access_token'];
            $token_data = ['access_token' => $access_token];
            file_put_contents('token.json', json_encode($token_data));
            echo 'Access token obtained successfully and stored.';
        } else {
            echo 'Access token not found in the response.';
        }
    } else {
        echo 'The state does not match. You may be a victim of CSRF.';
    }
}
?>
```

## Step 4: Fetching User's Listening History

```php
<?php
$token_file = 'token.json';

if (file_exists($token_file)) {
    $token_data = json_decode(file_get_contents($token_file), true);

    if (isset($token_data['access_token'])) {
        $access_token = $token_data['access_token'];

        $api_url = "https://api.deezer.com/user/me/history?access_token=" . $access_token;

        $ch = curl_init($api_url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $user_info_response = curl_exec($ch);

        if (curl_errno($ch)) {
            die('cURL error: ' . curl_error($ch));
        }

        curl_close($ch);

        $user_history = json_decode($user_info_response, true);

        $jsonFileName = 'Track.json';
        $newTrackData = [
            "data" => $user_history['data'][0],
            "date" => date('d-m-Y H:i')
        ];

        if (file_exists($jsonFileName)) {
            $jsonData = file_get_contents($jsonFileName);

            $storedTrackData = json_decode($jsonData, true);

            if ($storedTrackData !== null) {
                if ($storedTrackData['data']['id'] === $newTrackData['data']['id']) {
                    $date1 = $storedTrackData['date'];
                    $date2 = $newTrackData['date'];

                    $dateTime1 = DateTime::createFromFormat('d-m-Y H:i', $date1);
                    $dateTime2 = DateTime::createFromFormat('d-m-Y H:i', $date2);
                    $interval = $dateTime1->diff($dateTime2);
                    $totalMinutesPassed = $interval->days * 24 * 60 + $interval->h * 60 + $interval->i;

                    if ($totalMinutesPassed > 10) {
                        $data = [
                            "data" => null,
                            "date" => date('d-m-Y H:i')
                        ];
                        echo json_encode($data);
                    } else {
                        echo json_encode($storedTrackData);
                    }
                } else {
                    file_put_contents($jsonFileName, json_encode($newTrackData));
                    echo json_encode($newTrackData);
                }
            } else {
                file_put_contents($jsonFileName, json_encode($newTrackData));
                echo json_encode($newTrackData);
            }
        } else {
            file_put_contents($jsonFileName, json_encode($newTrackData));
            echo json_encode($newTrackData);
        }
    } else {
        echo "Access token not found in the JSON file.";
    }
} else {
    echo "Token file not found.";
}
?>
```

Make sure to replace `'YourAppID'`, `'YourAppSecret'`, and `'https://your-redirect-url.com/callback.php'` with your actual Deezer app ID, app secret, and redirect URL respectively. Also, replace `'token.json'` and `'Track.json'` with appropriate file paths as per your project structure.

Since the Deezer API does not allow directly fetching info from the user's player, we need to approach this from a different angle.

Fetch the user history:

```php
$api_url = "https://api.deezer.com/user/me/history?access_token=" . $access_token";
```

Then use the last entry (meaning the newest song that the user has listened to):

```php
$newTrackData = [
    "data" => $user_history['data'][0],
    "date" => date('d-m-Y H:i') // Use 24-hour format

 (H:i)
];
```

And to make sure the last track isn't infinitely returned to the user, the PHP script stores the fetched track to the `Track.json` with the date it is obtained on. This allows us to check if the same song is being returned even after 10 minutes and then stop returning the track to the user, meaning the player is not playing anything anymore.

```php
if ($totalMinutesPassed > 10) {
   //rest of code...
```

This is the workaround that I did for this purpose so the Deezer users can have somewhat the same API as Spotify users. I realize that this will not always work as intended but in most cases, it will. This script is also run by a cron job on the hosting server. The script runs every minute to ensure that the info is always up to date!

## Conclusion

Congratulations! You've learned how to create a Deezer developer app, obtain an access token, and use PHP to access a user's listening history. This knowledge opens up a world of possibilities for creating music-related applications and enhancing the user experience.

---