【Spotify】spotify_token_swap.php

今日はこの前言っていたSpotifyのToken Swap and Refreshについて、デモソースのruby版をphpに書き換えてみたので試してみたい方は参考にしてみてください。オリジナルのruby版サンプルソースはこちら

swap

先ずは、swapです。redirect_uriはdashboardで設定したRedirect URIsの1つを設定してください。base64に変換かけてるところは1個目がClient ID、2個目がClient Secretを設定してください。どちらもdashboardに記載のあるやつです。

<?php
    $auth_code = $_POST['code'];

    $body_data = array(
         'grant_type' => 'authorization_code'
        ,'redirect_uri' => 'xxxx://xxxx'
        ,'code' => $auth_code
    );

    $headers = array(
         'Authorization: ' . 'Basic ' . @base64_encode('xxxx' . ':' . 'xxxx')
        ,'Content-Type: application/x-www-form-urlencoded'
    );

    $options = array(
         'http' => array(
             'method' => 'POST'
            ,'header' => implode(PHP_EOL, $headers)
            ,'content' => http_build_query($body_data)
         )
        ,'ssl' => array(
             'verify_peer' => false
            ,'verify_peer_name' => false
         )
    );
    
    $response = @file_get_contents('https://accounts.spotify.com/api/token', false, stream_context_create($options));   
    $json = json_decode($response);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($json);
?>

refresh

refresh側です。base64のところはswapと同じものを設定してください。

<?php
    $body_data = array(
         'grant_type' => 'refresh_token'
        ,'refresh_token' => $_POST['refresh_token']
    );

    $headers = array(
         'Authorization: ' . 'Basic ' . @base64_encode('xxxx' . ':' . 'xxxx')
        ,'Content-Type: application/x-www-form-urlencoded'
    );

    $options = array(
         'http' => array(
             'method' => 'POST'
            ,'header' => implode(PHP_EOL, $headers)
            ,'content' => http_build_query($body_data)
         )
        ,'ssl' => array(
             'verify_peer' => false
            ,'verify_peer_name' => false
         )
    );

    $response = @file_get_contents('https://accounts.spotify.com/api/token', false, stream_context_create($options));
    $json = json_decode($response);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($json);
?>

コメント

上記の2つのコードをphpの動くサーバのどこかにindex.phpで置いてあげて、自分のアプリから呼ぶようにしてあげれば、とりあえず動くと思います・・・動きましたでしょうか?

関連記事

Atomでterminal-plusが動かなくなったときの対処法

Ubuntu上でIntelliJを使った際に起きたエラー

SwiftでOpenALの簡単サンプルソース

【GraalVM】ちょっと弄ってみた

【Swift】UIAlertViewからUIAlertControllerへマイ...

【Homebrew】使い方メモ