05.02.2020, 07:52
While this can be implemented with manual copying of tokens this solution might stop working at any point. The problem is that OAuth is means for end-user apps with UI not for server-to-server communication (Spotify server-to-server API does not provide player control). You will need a script to refresh the token periodically as it has a short expiration time.
This example might be helpful. It's for different OAuth service but quite similar. You need to put refresh token into storage variable and use access token from storage in scripts that send API requests.
This example might be helpful. It's for different OAuth service but quite similar. You need to put refresh token into storage variable and use access token from storage in scripts that send API requests.
Code:
url = require('socket.url')
http = require('ssl.https')
ltn12 = require('ltn12')
json = require('json')
refresh_token = storage.get('oauth_refresh_token')
if not refresh_token then
log('missing refresh_token')
return
end
local function buildqs(chunks)
local qs = {}
for k, v in pairs(chunks) do
qs[ #qs + 1 ] = url.escape(tostring(k)) .. '=' .. url.escape(tostring(v))
end
return table.concat(qs, '&')
end
payload = buildqs({
grant_type = 'refresh_token',
client_id = 'CLIENT_ID',
client_secret = 'CLIENT_SECRET',
refresh_token = refresh_token,
})
source = ltn12.source.string(payload)
headers = {
['content-length'] = tostring(#payload),
['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8',
}
sink, output = ltn12.sink.table()
local one, code, hdrs, status = http.request({
url = 'ENDPOINT_URL',
sink = sink,
source = source,
method = 'POST',
headers = headers,
})
res = table.concat(output)
if code == 200 then
res, err = json.pdecode(res)
if type(res) == 'table' then
storage.set('oauth_access_token', res.access_token)
storage.set('oauth_refresh_token', res.refresh_token)
else
log('json decode failed', res, err)
end
else
log('error', code, res)
end