Web sitesine anlık olarak Spotify etkinliği aktarma

vandoraa

Decapat
Katılım
23 Nisan 2023
Mesajlar
102
Çözümler
1
Yer
Ankara, Turkey
Daha fazla  
Sistem Özellikleri
Palit RTX 2060 DUAL 192 Bit GDDR6 6 GB
AMD Ryzen 5 3600X Six Core 3.80 GHz Processor
Asus Tuf Gaming B550M-PLUS AMD AM4 DDR4 Micro ATX,
Kingston Hyperx Predator 8 GB 3200 MHz DDR4 CL16 HX432C16PB3/8 Ram (x2)
High Power HPE-600BR-A12S 600 W Power Supply
Dark Guardian Pro DKCHGRPRO Player Case
Cinsiyet
Erkek
Meslek
Graphic Designer
Selam dostlar;

Kendime ait kişisel bir web sitem var. Bu siteye Spotify da anlık olarak dinlediğim şarkıyı Discord'taki gibi aktarmak istiyorum. Spotify developerstan bir uygulama oluşturdum ama gerisini yapamadım. Yardımcı olabilir misiniz?
 

Dosya Ekleri

  • resim_2023-10-15_203142256.png
    144,6 KB · Görüntüleme: 94
Bunun için Access Tokena ve süresi bittiğinde yenilemek için Refresh Token a ihtiyacımız var. Bu iki veriyi de aldıktan sonra basit html istekleri ile dinlediğiniz şarkıyı json olarak Spotify Apisinden çekebiliyorsunuz.
Sizin için örnek bir kod yazdım:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body onload="OnPageLoad()">
    <label for="clientId"></label>
    <input id="clientId" type="text" placeholder="Client ID" required>
    <label for="clientSecret"></label>
    <input id="clientSecret" type="text" placeholder="Client Secret" required>
    <label for="uri"></label>
    <input id="uri" type="text" placeholder="Current uri" required>
    <button onclick="getCode()">Get Code</button>

    <h3>Code: </h3><h3 id="code"></h3>
    <h3>Access Token: </h3><h3 id="access_token"></h3>
    <h3>Refresh Token: </h3><h3 id="refresh_token"></h3>

    <button>Log currently playing (requires Access Token)</button>
</body>
<script>
    var ClientId = document.getElementById("clientId");
    var ClientSecret = document.getElementById("clientSecret");
    var Uri = document.getElementById("uri");

    const urlParams = new URL(window.location.toString()).searchParams;
    const code = urlParams.get('code');

    var AccessToken= document.getElementById("access_token");
    var RefreshToken= document.getElementById("refresh_token");

    function getCode(){
        localStorage.setItem("clientId",ClientId.value);
        localStorage.setItem("clientSecret",ClientSecret.value);
        localStorage.setItem("uri",Uri.value);
        location.href = "https://accounts.spotify.com/authorize"+"?client_id="+ClientId.value+"&response_type=code&scope=user-read-currently-playing&redirect_uri="+Uri.value;
    }
    function OnPageLoad(){

        let c_id=  localStorage.getItem("clientId");
        if(c_id != null){
            ClientId.value=c_id;
        }

        let c_secret=  localStorage.getItem("clientSecret");
        if(c_secret != null){
            ClientSecret.value=c_secret;
        }

        let uri=  localStorage.getItem("uri");
        if(uri != null){
            Uri.value= uri;
        }

        let aT=  localStorage.getItem("access_token");
        if(aT != null){
            document.getElementById("access_token").innerHTML= aT;
        }
        let rT=  localStorage.getItem("refresh_token");
        if(rT != null){
            document.getElementById("refresh_token").innerHTML= rT;
        }

        if(code!= null){
        document.getElementById("code").innerHTML=code;
        getToken();
        }
    }
    async function getToken() {
    const url = 'https://accounts.spotify.com/api/token';

    const data = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + encodeURI(Uri.value) + "&client_id=" + ClientId.value + "&client_secret=" + ClientSecret.value;

    let response = await fetch(url, {
        method: 'POST',
        headers: {
            'Authorization': 'Basic ' + btoa(ClientId.value + ":" + ClientSecret.value),
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: data,
    });

    let responseData = await response.json();
    localStorage.setItem("access_token",responseData.access_token);
    localStorage.setItem("refresh_token",responseData.refresh_token);
    AccessToken.innerHTML = responseData.access_token;
    RefreshToken.innerHTML = responseData.refresh_token;
    }

    async function logCP(){
        if(localStorage.getItem("access_token")!=null){
            let response = await fetch("https://api.spotify.com/v1/me/player/currently-playing",{
                method:"GET",
                headers:{
                    "Authorization":"Bearer "+localStorage.getItem("access_token"),
                }
            })
            console.log(await response.json())
        }
    }

</script>
</html>
Biraz karışık olmuş olabilir kusura bakmayın. Visual Studio Code kullandığınızı varsayıyorum (yok ise başka uygulamalar da kullanabilirsiniz). bu kodu localhosta hostlayın. Client id ve secret kısmını spotify developers kısmında açtığınız uygulamanınkiler ile doldurun. Current uri yazan kısıma ise adres çubuğundaki url yi girin (örnek: http://127.0.0.1:5000/spotifyApiCredentials.html). "Get code" butonuna basmadan önce Spotify developer uygulamanızın "Redirect URI's" kısmına adres çubuğundaki url yi eklemeyi unutmayın. Butona tıkladıktan sonra tarayıcınızdan Spotifya giriş yapmadıysanız yapmanız istenecek. bu işlemden sonra ise izin vermeniz gerekiyor. İzin verdikten sonra sayfaya geri yönlendirileceksiniz ve Access + Refresh Tokenınız gelmiş olacak. Zamanım olmadığı için refresh token ile tekrar access token almayı yapmadım (Spotify dökümanlarından bakabilirsiniz) ama access token geldikten sonra consolu açıp
Log currently playing butonuna basarsanız (bu sırada spotifyda bir müzik dinlemeniz gerekmekte) dinlediğiniz şarkının bilgileri konsola loglanacaktır. Kodu inclerseniz hangi endpointe nasıl bir istek yaptığını anladıktan sonra server tarafında aynı istekleri yapıp clienta yansıtabilirsiniz.
 
Bu siteyi kullanmak için çerezler gereklidir. Siteyi kullanmaya devam etmek için çerezleri kabul etmelisiniz. Daha Fazlasını Öğren.…