Привет, ребята (впервые задаю вопрос здесь) :) Пока мне удалось получить токен доступа, но я не могу использовать токен для доступа к плейлистам текущего пользователя. Как ни странно, хотя раньше мне удавалось запускать примеры кодов на веб-сайте API YouTube, сейчас я не могу этого сделать. Когда я пытаюсь запустить код, я получаю сообщение об ошибке 401:
{
"error": {
"code": 401,
"message": "Invalid Credentials",
"errors": [
{
"locationType": "header",
"domain": "global",
"message": "Invalid Credentials",
"reason": "authError",
"location": "Authorization"
}
]
}
}
Процесс выглядит следующим образом: 1. запустите authorise_yt. php 2. после отправки авторизации перенаправьте обратно на authorise_yt. php 3. запустите authenticate_youtube.py
Вот мой код:
(authorise_yt. php) Чтобы получить код:
<?php
if (!isset($_GET['code']) && !isset($_GET['error'])){
header("Location:https://accounts.google.com/o/oauth2/v2/auth?client_id=733558996900-792s9ooam6lpqk3eal5t8ein336jv0n3.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%2Fproject%2Fauthorise_yt.php&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&access_type=offline");
exit();
}
if (isset($_GET['code'])){
$code=$_GET['code'];
echo $result=shell_exec("C:\wamp64\www\project\authenticate_youtube.py $code 2>&1");
}elseif (isset($_GET['error'])){
echo "error";
}
?>
(authenticate_youtube.py):
import sys
import requests
import json
client_secret="<client secret>"
client_id="<client_id>"
code=sys.argv[1]
parameters={
"client_id":client_id,
"client_secret":client_secret,
"code":code,
"grant_type":"authorization_code",
"redirect_uri":"http://localhost/project/authorise_yt.php"
}
r=requests.post("https://oauth2.googleapis.com/token",data=parameters)
json_obj=r.json()
access_token=json_obj['access_token']
refresh_token=json_obj['refresh_token']
api_key="<api_key>"
def get_new_token(client_id,client_secret,refresh_token):
datas={
"client_id":client_id,
"client_secret":client_secret,
"grant_type":"refresh_token",
"refresh_token":refresh_token
}
r=requests.post("https://oauth2.googleapis.com/token",data=datas)
json_obj=r.json()
new_access_token=json_obj['access_token']
return new_access_token
def collect_playlist_info(access_token,api_key):
header={
"Authorization": "Bearer {}".format(access_token),
"Accept": "application/json"
}
r=requests.get("https://www.googleapis.com/youtube/v3/playlists?part=snippet%2CcontentDetails&maxResults=25&mine=true&key={}".format(api_key),headers=header)
json_obj=r.json()
playlists=json_obj['items']
return_list=[]
for playlist_json in playlists:
playlist=json.loads(playlist_json)
return_list.append(playlist)
return return_list
new_token=get_new_token(client_id,client_secret,refresh_token)
print(new_token)
collect_playlist_info(new_token,api_key)
Извините, если внутри много ошибок ... Большое спасибо! : D