Clojure spotify API获得信任



我正在尝试获得Spotify证书API以在Clojure中工作,但遇到了一些困难。目前已经在链接页面上实现了以下(由于明显的原因删除了creds(来模仿JS版本,但一直得到状态400的响应。如果有人能帮我,那就太棒了!

(ns api-test.spotify
(:require [clj-http.client :as client])
(:require [clojure.string :as string])
(:import java.util.Base64))
(def app-creds 
{:id     "id creds here"
:secret "secret creds here"})
(def token-url "https://accounts.spotify.com/api/token")
(defn encode [to-encode]
(.encodeToString (Base64/getEncoder) (.getBytes to-encode)))
(defn app-creds->encoded
[app-creds]
(encode (str (:id app-creds) ":" (:secret app-creds))))
(defn get-token
[app-creds]
(client/post token-url {:basic-auth (app-creds->encoded app-creds)}))

根据您共享的文档,您缺少所需的"grant_ type";请求正文中的参数。

此外,还要求将内容类型报头设置为"0";x-www-form-url-encoded";但这是cljhttp开箱即用的东西。

最后,您也不必手动构造Authorization标头,因为cljhttp支持这样做。

这是对我有效的代码:

(defn get-token [{:keys [id secret] :as creds}]
(:body (http/post "https://accounts.spotify.com/api/token"
{#_#_:content-type :x-www-form-urlencoded
:as :json
:basic-auth [id secret]
:form-params {"grant_type" "client_credentials"}})))
(comment
(get-token {:id "xxx"
:secret "yyy"})
;; => {:access_token
;;     "BQB...",
;;     :token_type "Bearer",
;;     :expires_in 3600}
)

在所有情况下,请阅读服务器错误响应正文-当我没有通过";grant_ type";参数正确:

"{"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}",

您可以使用clj-spotify:

依赖项:[clj-spotify "0.1.10"]

(clj-spotify.util/get-access-token id-here secret-here)

如果您对实现感兴趣,请参阅来源:

(ns clj-spotify.util
(:require [clj-http.client :as client]
[clojure.data.codec.base64 :as b64]
[clojure.java.io :as io])
(:import [org.apache.commons.io IOUtils]))
(defn get-access-token
"Requests an access token from Spotify's API via the Client Credentials flow.
The returned token cannot be used for endpoints which access private user information;
use the OAuth 2 Authorization Code flow for that."
[client-id client-secret]
(-> "https://accounts.spotify.com/api/token"
(client/post {:form-params {:grant_type "client_credentials"}
:basic-auth [client-id client-secret]
:as :json})
:body
:access_token))

最新更新