Spotify API unsupported_grant_type

Spotify API unsupported_grant_type

我正在使用 client credentials flow 对 Spotify API 进行身份验证。我已经把我需要的一切都设置好了,但是每当我发送 rquest 时,我仍然会收到以下错误。

400 Bad Request: {"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}

相关代码如下:

sub get_spotify_token{
    my $data={grant_type => "client_credentials"};

    my $req=HTTP::Request->new("POST",AUTH_TOKEN_URL,[
        "Content-Type" => "application/x-www-form-urlencoded",
        "Authorization" => "Basic $ENV{SPOTIFY_CLIENT_B64}",
    ],encode_utf8 encode_json $data);

    # send request
    my $res=$ua->request($req);

    # return token or die on error
    if($res->is_success){
        return %{decode_json $res->content}{"access_token"};
    }else{
        die $res->status_line.": ".$res->content."\n";
    }
}

API 期望 application/x-www-form-urlencoded (grant_type=client_credentials) 正如您声称的那样,但您提供的是 JSON ({"grant_type":"client_credentials"})。

HTTP::Request::CommonPOST 可以轻松构建 application/x-www-form-urlencoded 响应。

use HTTP::Request::Common qw( POST );

my $req = POST(AUTH_TOKEN_URL,
    [
        grant_type => "client_credentials",
    ],
    Authorization => "Basic $ENV{SPOTIFY_CLIENT_B64}",
    Content_Type  => 'application/x-www-form-urlencoded',
);

use HTTP::Request::Common qw( POST );

my $req = POST(AUTH_TOKEN_URL,
    Authorization => "Basic $ENV{SPOTIFY_CLIENT_B64}",
    Content_Type  => 'application/x-www-form-urlencoded',
    Content => [
        grant_type => "client_credentials",
    ],
);