[GH-ISSUE #95] CronJob #51

Closed
opened 2026-02-27 19:25:47 +03:00 by kerem · 2 comments
Owner

Originally created by @karschti on GitHub (Aug 18, 2017).
Original GitHub issue: https://github.com/jwilsson/spotify-web-api-php/issues/95

I want to create a CronJob for a PHPScript.

Unfortunately, I do not get it.
I tried it with WGET.
Probably it is a problem with the callback.

It works in the browser.

Who can help - if possible with sample code

PHP Script

$session = new SpotifyWebAPI\Session(
    $config["spotify_client_id"],
    $config["spotify_client_secret"],
    'http://127.0.0.1/privat/playlisten/cronjob/schreibe_playliste.php'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();

if (isset($_GET['code'])) {
    // MySQL Daten aufbreiten und in $titel[] speichern
    $mysqli = new mysqli($config["mysql_server"],$config["mysql_user"],$config["mysql_password"],$config["mysql_db"]);
    if ($mysqli->connect_errno) {
            echo "Failed to connect to MySQL: " .  $mysqli->connect_error;
            return;
    }

    if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
    }

    $sql = "SELECT spotify_playliste.IDTITEL, Count(1) as anz
            FROM spotify_playliste INNER JOIN playlist ON spotify_playliste.ID = playlist.ID_SPOTIFY_PLAYLISTE
            WHERE 
                spotify_playliste.IDTITEL <> ''
                AND playlist.DATUM BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
            GROUP BY playlist.IDSENDER, spotify_playliste.RADIOTITEL, spotify_playliste.IDTITEL
            HAVING playlist.IDSENDER=1        
            ORDER BY Count(1) DESC
            LIMIT 100";

    $result = $mysqli->query($sql);
    if($result->num_rows == 0) return "<div>Keine Daten gefunden</div>";
    
    while ($row = $result->fetch_assoc()) {
        $titel[] =  $row["IDTITEL"];
    }

    // Spotify Playliste $titel[] übertragen
    $api = new SpotifyWebAPI\SpotifyWebAPI();
    $session->requestAccessToken($_GET['code']);
    $accessToken = $session->getAccessToken();
    $api->setAccessToken($accessToken);
    $me = $api->me();
    $id = $me->id;
    $api->replaceUserPlaylistTracks($id, $config["spotify_playliste_id"], $titel);
} else {
    $options = [
    'scope' => [
        'playlist-read-private',
        'user-read-private',
		'playlist-modify-public',
		'playlist-modify-private'
        ],
    ];
    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}
Originally created by @karschti on GitHub (Aug 18, 2017). Original GitHub issue: https://github.com/jwilsson/spotify-web-api-php/issues/95 I want to create a CronJob for a PHPScript. Unfortunately, I do not get it. I tried it with WGET. Probably it is a problem with the callback. It works in the browser. Who can help - if possible with sample code PHP Script ``` $session = new SpotifyWebAPI\Session( $config["spotify_client_id"], $config["spotify_client_secret"], 'http://127.0.0.1/privat/playlisten/cronjob/schreibe_playliste.php' ); $api = new SpotifyWebAPI\SpotifyWebAPI(); if (isset($_GET['code'])) { // MySQL Daten aufbreiten und in $titel[] speichern $mysqli = new mysqli($config["mysql_server"],$config["mysql_user"],$config["mysql_password"],$config["mysql_db"]); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; return; } if (!$mysqli->set_charset("utf8")) { printf("Error loading character set utf8: %s\n", $mysqli->error); exit(); } $sql = "SELECT spotify_playliste.IDTITEL, Count(1) as anz FROM spotify_playliste INNER JOIN playlist ON spotify_playliste.ID = playlist.ID_SPOTIFY_PLAYLISTE WHERE spotify_playliste.IDTITEL <> '' AND playlist.DATUM BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() GROUP BY playlist.IDSENDER, spotify_playliste.RADIOTITEL, spotify_playliste.IDTITEL HAVING playlist.IDSENDER=1 ORDER BY Count(1) DESC LIMIT 100"; $result = $mysqli->query($sql); if($result->num_rows == 0) return "<div>Keine Daten gefunden</div>"; while ($row = $result->fetch_assoc()) { $titel[] = $row["IDTITEL"]; } // Spotify Playliste $titel[] übertragen $api = new SpotifyWebAPI\SpotifyWebAPI(); $session->requestAccessToken($_GET['code']); $accessToken = $session->getAccessToken(); $api->setAccessToken($accessToken); $me = $api->me(); $id = $me->id; $api->replaceUserPlaylistTracks($id, $config["spotify_playliste_id"], $titel); } else { $options = [ 'scope' => [ 'playlist-read-private', 'user-read-private', 'playlist-modify-public', 'playlist-modify-private' ], ]; header('Location: ' . $session->getAuthorizeUrl($options)); die(); } ```
kerem 2026-02-27 19:25:47 +03:00
  • closed this issue
  • added the
    question
    label
Author
Owner

@jwilsson commented on GitHub (Aug 20, 2017):

Hi!
When the user authenticates, you'll get a refresh token which you should store and use to get a new access token when the old one has expired (the access token is valid for about an hour).

So, instead of authenticating the user in your cron job, I'd do something like this:

  1. Authenticate the user through another script which runs in the browser.
  2. In the callback script, save the refresh token in your database, tied to the user ID for example.
  3. In your cron job, request a new access token using the refresh token.
  4. Perform the playlist update in the same way as you're currently doing.

A quick example:

// authenticate.php

if (isset($_GET['code'])) {
    $session->requestAccessToken($_GET['code']);

    $refreshToken = $session->getRefreshToken();
    $accessToken = $session->getAccessToken();

    $api->setAccessToken($accessToken);

    $user = $api->me();

    save_refresh_token_in_database($refreshToken, $user->id);
} else {
    $options = [
    'scope' => [
        'playlist-read-private',
        'user-read-private',
		'playlist-modify-public',
		'playlist-modify-private'
        ],
    ];
    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}
// cron_job.php

$session = new SpotifyWebAPI\Session(
    $config["spotify_client_id"],
    $config["spotify_client_secret"],
    'http://127.0.0.1/privat/playlisten/cronjob/schreibe_playliste.php'
);

$refreshToken = get_refresh_token_from_database();

$session->refreshAccessToken($refreshToken);
$accessToken = $session->getAccessToken();

$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);

// Do the rest of your playlist updating as before

Hope this helps you out!

<!-- gh-comment-id:323581412 --> @jwilsson commented on GitHub (Aug 20, 2017): Hi! When the user authenticates, you'll get a refresh token which you should store and use to get a new access token when the old one has expired (the access token is valid for about an hour). So, instead of authenticating the user in your cron job, I'd do something like this: 1. Authenticate the user through another script which runs in the browser. 2. In the callback script, save the refresh token in your database, tied to the user ID for example. 3. In your cron job, request a new access token using the refresh token. 4. Perform the playlist update in the same way as you're currently doing. A quick example: ```php // authenticate.php if (isset($_GET['code'])) { $session->requestAccessToken($_GET['code']); $refreshToken = $session->getRefreshToken(); $accessToken = $session->getAccessToken(); $api->setAccessToken($accessToken); $user = $api->me(); save_refresh_token_in_database($refreshToken, $user->id); } else { $options = [ 'scope' => [ 'playlist-read-private', 'user-read-private', 'playlist-modify-public', 'playlist-modify-private' ], ]; header('Location: ' . $session->getAuthorizeUrl($options)); die(); } ``` ```php // cron_job.php $session = new SpotifyWebAPI\Session( $config["spotify_client_id"], $config["spotify_client_secret"], 'http://127.0.0.1/privat/playlisten/cronjob/schreibe_playliste.php' ); $refreshToken = get_refresh_token_from_database(); $session->refreshAccessToken($refreshToken); $accessToken = $session->getAccessToken(); $api = new SpotifyWebAPI\SpotifyWebAPI(); $api->setAccessToken($accessToken); // Do the rest of your playlist updating as before ``` Hope this helps you out!
Author
Owner

@karschti commented on GitHub (Aug 21, 2017):

Many Thanks
This was perfect

<!-- gh-comment-id:323764170 --> @karschti commented on GitHub (Aug 21, 2017): Many Thanks This was perfect
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotify-web-api-php#51
No description provided.