Skip to content

Instantly share code, notes, and snippets.

@jcchikikomori
Forked from ivanlebanov/custom-ajax-spotify.php
Created September 23, 2019 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcchikikomori/c18d15c4a775cad1e17c3c127d11e37f to your computer and use it in GitHub Desktop.
Save jcchikikomori/c18d15c4a775cad1e17c3c127d11e37f to your computer and use it in GitHub Desktop.
Spotify API integration with WordPress
<?php
function ajax_enquiry_init(){
wp_register_script('jquery', 'https://code.jquery.com/jquery-1.11.2.min.js' );
wp_enqueue_script('jquery');
wp_register_script('main', get_template_directory_uri() . '/js/main.js', array('jquery') );
wp_enqueue_script('main');
wp_localize_script( 'main', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
add_action( 'wp_ajax_nopriv_ajaxenquiry', 'ajaxenquiry' );
add_action('wp_ajax_ajaxenquiry', 'ajaxenquiry');
}
// Execute the action only if the user isn't logged in
add_action('init', 'ajax_enquiry_init');
function ajaxenquiry(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-enquiry-nonce', 'security' );
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$spot_api_redirect = 'your_spotify_redirect_uri';
$credentials = "your_spotify_client_id:your_spotify_client_secret";
$test = 'your_spotify_refresh_token';
$headers = array(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . base64_encode($credentials));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=refresh_token&refresh_token=' . $test .'&request_uri=' .urlencode($spot_api_redirect) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
$info = curl_getinfo($ch);
curl_close ($ch);
$server_output = json_decode($server_output, true);
update_option('token', $server_output['access_token']);
echo json_encode(array(
'token' => $server_output['access_token']
));
die();
}
$new_general_setting = new new_general_setting();
class new_general_setting {
function new_general_setting( ) {
add_filter( 'admin_init' , array( &$this , 'register_fields' ) );
}
function register_fields() {
register_setting( 'general', 'token', 'esc_attr' );
register_setting( 'general', 'secret', 'esc_attr' );
add_settings_field('token', '<label for="token">'.__('Spotify Token?' , 'token' ).'</label>' , array(&$this, 'token_html') , 'general' );
add_settings_field('secret', '<label for="secret">'.__('Spotify secret?' , 'secret' ).'</label>' , array(&$this, 'secret_html') , 'general' );
}
function token_html() {
$token = get_option( 'token', '' );
echo '<input type="text" id="token" name="token" value="'. $token . '" />';
}
function secret_html() {
$secret = get_option( 'secret', '' );
echo '<input type="text" id="secret" name="secret" value="' . $secret . '" />';
}
}
require_once( get_template_directory() . '/libs/custom-ajax-spotify.php' );
<script>
var token = <?php echo get_option('token'); ?>;
</script>
(function($) {
$(document).ready(function() {
function getNewToken(token) {
var action = 'ajaxenquiry';
var security = $('#security').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_auth_object.ajaxurl,
data: {
'action': action,
'security': security,
},
success: function (data) {
getCurrentSong(data.token);
}
});
}
function getCurrentSong(newtoken = null) {
// get the token from the option if non is passed
var token = (newtoken) ? newtoken : tokenGeneral;
// API enpoint
var url = 'https://api.spotify.com/v1/me/player/currently-playing';
// make a GET request to the API
$.ajax({
url: url,
method: "GET",
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8",
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
},
success: function (data) {
visualise(data);
},
error: function (jqXHR, textStatus, errorThrown) {
getNewToken(token);
}
});
}
/**
* Visualizing the response into the page
*
**/
function visualise(data) {
if(data){
let text = (data.is_playing) ? "Listening to." : "The last song I listened to.";
let artists = '';
for(let i = 0; i < data.item.artists.length; i++){
artists += data.item.artists[i].name;
if(i == data.item.artists.length - 1 ){
artists += '.';
}
else if (i == data.item.artists.length - 2) {
artists += ' & ';
}
else{
artists += ', ';
}
}
$('#title_spotify').text(artists);
$('#album_spotify').text(data.item.name);
$('#album_cover').attr('src', data.item.album.images[0].url);
$('#album_link').removeClass('hidden');
$('#title__main_spotify').text(text);
$('#album_link').attr('href', data.item.external_urls.spotify);
}else{
// during ads & when you play music with your phone
// the API call does return an empty response
let text = "This section is fancy." ;
$('#title_spotify').text('Unfortunately Spotify API returned an empty response.');
$('#title__main_spotify').text(text);
$('#album_spotify').text("Probably I haven't been listening to music for a while.");
$('#album_cover').attr('src', 'http://localhost:8888/lebanov/wp-content/themes/wp-ivan/img/no.jpg');
$('#album_link').addClass('hidden');
}
$('.spotify').removeClass('hidden');
}
getCurrentSong();
setInterval(function() {
getCurrentSong();
}, 30000);
});
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment