Spotify 访问和刷新令牌的问题

时间:2021-04-01 07:18:45

标签: javascript react-native request expo spotify

目前我正在尝试在我的 react 本机应用程序(带 expo) 上使用 spotify api。 当我想获取 Acess 和 Refresh 令牌时遇到了一些麻烦。

所以我按照官方文档获取第一个代码,然后获取刷新和访问令牌。 所以我使用 expo-auth-session 来管理 Spotify oauth:

const _handlePressButtonAsync = async () => {
        const queryParam = toQueryString({
            "response_type": "code",
            "client_id": Cred.spotify.client_id,
            "redirect_uri": AuthSession.makeRedirectUri({useProxy: true}),
            "scope": Cred.spotify.scope
        })

        const baseResquest = 'https://accounts.spotify.com/authorize'
        const authUrl = `${baseResquest}${queryParam}`

        const res = await AuthSession.startAsync({authUrl})
        if (res.type === "success") {
            const tokens = await requestToken(res.params.code, AuthSession.makeRedirectUri({useProxy: true}))
            callback(tokens)
        }
<块引用>

AuthSession.makeRedirectUri({useProxy: true})) 曾经有一个正确的 redirectUri 而不是 exp://localhost:port

一切似乎都正常工作,因为我收到了我的代码,所以我进入下一步。 这是我的问题。下一步说向 https://accounts.spotify.com/api/token 发送一个 POST 请求:

  • 身体:
    • grant_type 必须具有值“authorization_code”
    • 上一步中的代码选择
    • redirect_uri 必须与用于获取代码的相同
  • 标题:
    • 授权必须具有值“基本” + 转换后的 Base64 client_id:client_secret 您可以将它们(client_id 和 client_secret)放在正文中而不进行转换。

这是我的请求(使用 axios 发送):

    var options = {
        method: "post",
        url: "https://accounts.spotify.com/api/token",
        params: {
            grant_type: "authorization_code",
            code: code,
            redirect_uri: redirect_uri,
        },
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: "Basic " + Buffer.from(Cred.spotify.client_id + ":" + Cred.spotify.client_secret).toString("base64"),
        }
    }
    return await axios(options).then((res) => {
        console.log("REQUEST:", res)
        res
    }).catch((res) => {
        console.log(`ERROR REQUEST: ${res.response.status}, ${res.response.data.error}`)
        res
    })

ERROR REQUEST: 400 server_error

所以在互联网上我发现了一些对我不起作用的东西:

  • 将“参数”更改为“正文”
  • 在标题中添加 "Content-Type": "application/x-www-form-urlencoded"
  • 将 client_id 和 client_secret 放在正文而不是标题中

但我一直收到ERROR REQUEST: 400 server_error 或者当我使用 data 而不是 params ERROR REQUEST: 400 unsupported_grant_type

我真的不知道问题出在哪里,请求,我的数据,格式...

如果有人有解决方案或想法?

预先感谢您的帮助

0 个答案:

没有答案