title: Using the Spotify API with Laravel
body: <p>I am new to web development and have a few question which i hope someone can answer.So I have been building a website using Lavarel and now I have been researching into the Spotify API. Here is a link to the guide  <a href="https://developer.spotify.com/documentation/web-api/quick-start/" rel="nofollow noreferrer">https://developer.spotify.com/documentation/web-api/quick-start/</a> </p>
  
  <p>I have completed this guide and now I was just wondering how do I use this with my own website without having to use call the NodeJs file from command prompt. This may be a silly question but i've been researching this for while now. </p>
  
  <p>Below is my JS file (app.js) which is theAuthorization Code example which can be found in the link above , I must also not that I have not include my client id and client secret for security reasons.</p>
  
  <pre><code>/**
   * This is an example of a basic node.js script that performs
   * the Authorization Code oAuth2 flow to authenticate against
   * the Spotify Accounts.
   *
   * For more information, read
   * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
   */
  
  var express = require('express'); // Express web server framework
  var request = require('request'); // "Request" library
  var cors = require('cors');
  var querystring = require('querystring');
  var cookieParser = require('cookie-parser');
  
  var client_id = ''; // Your client id
  var client_secret = ''; // Your secret
  var redirect_uri = ''; // Your redirect uri
  
  /**
   * Generates a random string containing numbers and letters
   * @param  {number} length The length of the string
   * @return {string} The generated string
   */
  var generateRandomString = function(length) {
    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
    for (var i = 0; i &lt; length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
  };
  
  var stateKey = 'spotify_auth_state';
  
  var app = express();
  
  app.use(express.static(__dirname + '/public'))
     .use(cors())
     .use(cookieParser());
  
  app.get('/login', function(req, res) {
  
    var state = generateRandomString(16);
    res.cookie(stateKey, state);
  
    // your application requests authorization
    var scope = 'user-read-private user-read-email';
    res.redirect('https://accounts.spotify.com/authorize?' +
      querystring.stringify({
        response_type: 'code',
        client_id: client_id,
        scope: scope,
        redirect_uri: redirect_uri,
        state: state
      }));
  });
  
  app.get('/callback', function(req, res) {
  
    // your application requests refresh and access tokens
    // after checking the state parameter
  
    var code = req.query.code || null;
    var state = req.query.state || null;
    var storedState = req.cookies ? req.cookies[stateKey] : null;
  
    if (state === null || state !== storedState) {
      res.redirect('/#' +
        querystring.stringify({
          error: 'state_mismatch'
        }));
    } else {
      res.clearCookie(stateKey);
      var authOptions = {
        url: 'https://accounts.spotify.com/api/token',
        form: {
          code: code,
          redirect_uri: redirect_uri,
          grant_type: 'authorization_code'
        },
        headers: {
          'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
        },
        json: true
      };
  
      request.post(authOptions, function(error, response, body) {
        if (!error &amp;&amp; response.statusCode === 200) {
  
          var access_token = body.access_token,
              refresh_token = body.refresh_token;
  
          var options = {
            url: 'https://api.spotify.com/v1/me',
            headers: { 'Authorization': 'Bearer ' + access_token },
            json: true
          };
  
          // use the access token to access the Spotify Web API
          request.get(options, function(error, response, body) {
            console.log(body);
          });
  
          // we can also pass the token to the browser to make requests from there
          res.redirect('/#' +
            querystring.stringify({
              access_token: access_token,
              refresh_token: refresh_token
            }));
        } else {
          res.redirect('/#' +
            querystring.stringify({
              error: 'invalid_token'
            }));
        }
      });
    }
  });
  
  app.get('/refresh_token', function(req, res) {
  
    // requesting access token from refresh token
    var refresh_token = req.query.refresh_token;
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
      form: {
        grant_type: 'refresh_token',
        refresh_token: refresh_token
      },
      json: true
    };
  
    request.post(authOptions, function(error, response, body) {
      if (!error &amp;&amp; response.statusCode === 200) {
        var access_token = body.access_token;
        res.send({
          'access_token': access_token
        });
      }
    });
  });
  
  console.log('Listening on 8888');
  app.listen(8888); 
  </code></pre>
  
  <p>Then this is the index.html that spotify provide to display users details if you want (I just added this to show were it redirects the user on authorization)</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;Example of the Authorization Code flow with Spotify&lt;/title&gt;
      &lt;link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"&gt;
      &lt;style type="text/css"&gt;
        #login, #loggedin {
          display: none;
        }
        .text-overflow {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 500px;
        }
      &lt;/style&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;div class="container"&gt;
        &lt;div id="login"&gt;
          &lt;h1&gt;This is an example of the Authorization Code flow&lt;/h1&gt;
          &lt;a href="/login" class="btn btn-primary"&gt;Log in with Spotify&lt;/a&gt;
        &lt;/div&gt;
        &lt;div id="loggedin"&gt;
          &lt;div id="user-profile"&gt;
          &lt;/div&gt;
          &lt;div id="oauth"&gt;
          &lt;/div&gt;
          &lt;button class="btn btn-default" id="obtain-new-token"&gt;Obtain new token using the refresh token&lt;/button&gt;
        &lt;/div&gt;
      &lt;/div&gt;
  
      &lt;script id="user-profile-template" type="text/x-handlebars-template"&gt;
        &lt;h1&gt;Logged in as {{display_name}}&lt;/h1&gt;
        &lt;div class="media"&gt;
          &lt;div class="pull-left"&gt;
            &lt;img class="media-object" width="150" src="{{images.0.url}}" /&gt;
          &lt;/div&gt;
          &lt;div class="media-body"&gt;
            &lt;dl class="dl-horizontal"&gt;
              &lt;dt&gt;Display name&lt;/dt&gt;&lt;dd class="clearfix"&gt;{{display_name}}&lt;/dd&gt;
              &lt;dt&gt;Id&lt;/dt&gt;&lt;dd&gt;{{id}}&lt;/dd&gt;
              &lt;dt&gt;Email&lt;/dt&gt;&lt;dd&gt;{{email}}&lt;/dd&gt;
              &lt;dt&gt;Spotify URI&lt;/dt&gt;&lt;dd&gt;&lt;a href="{{external_urls.spotify}}"&gt;{{external_urls.spotify}}&lt;/a&gt;&lt;/dd&gt;
              &lt;dt&gt;Link&lt;/dt&gt;&lt;dd&gt;&lt;a href="{{href}}"&gt;{{href}}&lt;/a&gt;&lt;/dd&gt;
              &lt;dt&gt;Profile Image&lt;/dt&gt;&lt;dd class="clearfix"&gt;&lt;a href="{{images.0.url}}"&gt;{{images.0.url}}&lt;/a&gt;&lt;/dd&gt;
              &lt;dt&gt;Country&lt;/dt&gt;&lt;dd&gt;{{country}}&lt;/dd&gt;
            &lt;/dl&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/script&gt;
  
      &lt;script id="oauth-template" type="text/x-handlebars-template"&gt;
        &lt;h2&gt;oAuth info&lt;/h2&gt;
        &lt;dl class="dl-horizontal"&gt;
          &lt;dt&gt;Access token&lt;/dt&gt;&lt;dd class="text-overflow"&gt;{{access_token}}&lt;/dd&gt;
          &lt;dt&gt;Refresh token&lt;/dt&gt;&lt;dd class="text-overflow"&gt;{{refresh_token}}&lt;/dd&gt;
        &lt;/dl&gt;
      &lt;/script&gt;
  
      &lt;script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"&gt;&lt;/script&gt;
      &lt;script src="http://code.jquery.com/jquery-1.10.1.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
        (function() {
  
          /**
           * Obtains parameters from the hash of the URL
           * @return Object
           */
          function getHashParams() {
            var hashParams = {};
            var e, r = /([^&amp;;=]+)=?([^&amp;;]*)/g,
                q = window.location.hash.substring(1);
            while ( e = r.exec(q)) {
               hashParams[e[1]] = decodeURIComponent(e[2]);
            }
            return hashParams;
          }
  
          var userProfileSource = document.getElementById('user-profile-template').innerHTML,
              userProfileTemplate = Handlebars.compile(userProfileSource),
              userProfilePlaceholder = document.getElementById('user-profile');
  
          var oauthSource = document.getElementById('oauth-template').innerHTML,
              oauthTemplate = Handlebars.compile(oauthSource),
              oauthPlaceholder = document.getElementById('oauth');
  
          var params = getHashParams();
  
          var access_token = params.access_token,
              refresh_token = params.refresh_token,
              error = params.error;
  
          if (error) {
            alert('There was an error during the authentication');
          } else {
            if (access_token) {
              // render oauth info
              oauthPlaceholder.innerHTML = oauthTemplate({
                access_token: access_token,
                refresh_token: refresh_token
              });
  
              $.ajax({
                  url: 'https://api.spotify.com/v1/me',
                  headers: {
                    'Authorization': 'Bearer ' + access_token
                  },
                  success: function(response) {
                    userProfilePlaceholder.innerHTML = userProfileTemplate(response);
  
                    $('#login').hide();
                    $('#loggedin').show();
                  }
              });
            } else {
                // render initial screen
                $('#login').show();
                $('#loggedin').hide();
            }
  
            document.getElementById('obtain-new-token').addEventListener('click', function() {
              $.ajax({
                url: '/refresh_token',
                data: {
                  'refresh_token': refresh_token
                }
              }).done(function(data) {
                access_token = data.access_token;
                oauthPlaceholder.innerHTML = oauthTemplate({
                  access_token: access_token,
                  refresh_token: refresh_token
                });
              });
            }, false);
          }
        })();
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>