简体   繁体   中英

I am using php to connect to spotify's API with PHP and with the client credentials flow

I am new to using an sort of REST protocol and am having trouble getting my access token back from the cURL request.

This is using WAMP. I have already enabled the cURL extension and that works now. I also have already made a spotify application and have my client ID and secret ID.

<?php

/* Spotify Application Client ID and Secret Key */
$client_id     = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; 
$client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

/* Get Spotify Authorization Token */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,            'https://accounts.spotify.com/api/token' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     'grant_type=client_credentials' );
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret)));

$result=curl_exec($ch);
$json = json_decode($result, true);

 echo "Results of json:  ". + $json['access_token'];

/* Get Spotify Artist Photo */
echo "<pre>";
exec('curl -i "https://api.spotify.com/v1/search?<br>q=Maycon+%26+Vinicius+&limit=1&type=artist" -H "Accept: application/json" -H "Authorization: Bearer '.$json['access_token'].'" -H "Content-Type: application/json" 2>&1', $pp);
echo implode("\r\n", $pp);
?>

The error that I get is:

""status": 400, "message": "Only valid bearer authentication supported""

When I try to print out the results of my json resource variable $json[access_token] it prints 0.

Here is the full error message.

HTTP/2 400
www-authenticate: Bearer realm="spotify", error="invalid_request",
error_description="Only valid bearer authentication supported"
access-control-allow-origin: *
access-control-allow-headers: Accept, App-Platform, Authorization, Content-
Type, Origin, Retry-After, Spotify-App-Version
access-control-allow-methods: GET, POST, OPTIONS, PUT, DELETE, PATCH
access-control-allow-credentials: true
access-control-max-age: 604800
content-type: application/json
content-length: 99
date: Sat, 26 Oct 2019 15:55:39 GMT
via: 1.1 google
alt-svc: clear

Have you tried other requests and run into similar authentication errors? To test I took your query and simplified it a bit to test it on my system and it returned one artist, so it looks like it's working.

curl -i "https://api.spotify.com/v1/search?q=Maycon+%26+Vinicius+&limit=1&type=artist" -H "Accept: application/json" -H "Authorization: Bearer $AccessToken" -H "Content-Type: application/json"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM