Ошибка создания трансляции ошибка youtube api

I’m trying to create Youtube live stream through my webpage via Youtube Data API. Whatever I tried, keep getting that error:

{
  "error": {
    "code": 400,
    "message": "'{0}'",
    "errors": [
      {
        "message": "'{0}'",
        "domain": "youtube.part",
        "reason": "unknownPart",
        "location": "part",
        "locationType": "parameter"
      }
    ]
  }
}

Unfortunately, this error doesn’t explain anything, and I couldn’t find anything to help me to solve it. I hope someone can explain what is going on here.

I put all relative files down below and added some comments.

web.php

Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');

YoutubeController.php

class YoutubeController extends Controller
{
    private $youtube;

    public function __construct(Request $request)
    {
        // like YoutubeStreamService or YoutubeUploadService
        $this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
    }

    public function authenticate($task)
    {
        return redirect()->away($this->youtube->authenticate($task));
    }

    public function create(Request $request, $task)
    {
        $this->youtube->create($request, $task);
    }
}

I use an abstract class for authentication codes.

abstract class YoutubeAbstraction
{
    // Called from the controller.
    // Returns the url to google to authenticate the request. 
    public function authenticate($task)
    {
        return $this->client($task)->createAuthUrl();
    }

    // This code came from mostly Youtueb API documentation.
    protected function client($task)
    {
        $scopes = [
            'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
            'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
        ][$task];
        $client = new Google_Client();
        $client->setApplicationName("MyApp");
        $client->setScopes($scopes);
        $client->setAuthConfig(base_path("client_secret_{$task}.json"));
        $client->setAccessType('offline');

        return $client;
    }

    abstract public function create($request, $task); 
}

YoutubeStreamService.php

class YoutubeStreamService extends YoutubeAbstraction
{
    // This code came from Youtube API documentation completely.
    // It contains only the required fields and their hard-coded values.
    public function create($request, $task)
    {
        $client = $this->client($task);
        $client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));

        $service = new Google_Service_YouTube($client);        
        $liveBroadcast = new Google_Service_YouTube_LiveBroadcast();

        $liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
        $liveBroadcastSnippet->setTitle('my title');
        $liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
        $liveBroadcast->setSnippet($liveBroadcastSnippet);

        $liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
        $liveBroadcastStatus->setPrivacyStatus('private');
        $liveBroadcast->setStatus($liveBroadcastStatus);

        // If I add dd($liveBroadcast) here, I see the object.
        // So the error is thrown by the function down below.

        $response = $service->liveBroadcasts->insert('', $liveBroadcast);
        print_r($response);
    }
}

I’m trying to create Youtube live stream through my webpage via Youtube Data API. Whatever I tried, keep getting that error:

{
  "error": {
    "code": 400,
    "message": "'{0}'",
    "errors": [
      {
        "message": "'{0}'",
        "domain": "youtube.part",
        "reason": "unknownPart",
        "location": "part",
        "locationType": "parameter"
      }
    ]
  }
}

Unfortunately, this error doesn’t explain anything, and I couldn’t find anything to help me to solve it. I hope someone can explain what is going on here.

I put all relative files down below and added some comments.

web.php

Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');

YoutubeController.php

class YoutubeController extends Controller
{
    private $youtube;

    public function __construct(Request $request)
    {
        // like YoutubeStreamService or YoutubeUploadService
        $this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
    }

    public function authenticate($task)
    {
        return redirect()->away($this->youtube->authenticate($task));
    }

    public function create(Request $request, $task)
    {
        $this->youtube->create($request, $task);
    }
}

I use an abstract class for authentication codes.

abstract class YoutubeAbstraction
{
    // Called from the controller.
    // Returns the url to google to authenticate the request. 
    public function authenticate($task)
    {
        return $this->client($task)->createAuthUrl();
    }

    // This code came from mostly Youtueb API documentation.
    protected function client($task)
    {
        $scopes = [
            'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
            'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
        ][$task];
        $client = new Google_Client();
        $client->setApplicationName("MyApp");
        $client->setScopes($scopes);
        $client->setAuthConfig(base_path("client_secret_{$task}.json"));
        $client->setAccessType('offline');

        return $client;
    }

    abstract public function create($request, $task); 
}

YoutubeStreamService.php

class YoutubeStreamService extends YoutubeAbstraction
{
    // This code came from Youtube API documentation completely.
    // It contains only the required fields and their hard-coded values.
    public function create($request, $task)
    {
        $client = $this->client($task);
        $client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));

        $service = new Google_Service_YouTube($client);        
        $liveBroadcast = new Google_Service_YouTube_LiveBroadcast();

        $liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
        $liveBroadcastSnippet->setTitle('my title');
        $liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
        $liveBroadcast->setSnippet($liveBroadcastSnippet);

        $liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
        $liveBroadcastStatus->setPrivacyStatus('private');
        $liveBroadcast->setStatus($liveBroadcastStatus);

        // If I add dd($liveBroadcast) here, I see the object.
        // So the error is thrown by the function down below.

        $response = $service->liveBroadcasts->insert('', $liveBroadcast);
        print_r($response);
    }
}

#php #laravel #youtube-api #youtube-data-api

#php #laravel #youtube-api #youtube-data-api

Вопрос:

Я пытаюсь создать прямую трансляцию Youtube через свою веб-страницу через API данных Youtube. Что бы я ни пробовал, продолжайте получать эту ошибку:

 {
  "error": {
    "code": 400,
    "message": "'{0}'",
    "errors": [
      {
        "message": "'{0}'",
        "domain": "youtube.part",
        "reason": "unknownPart",
        "location": "part",
        "locationType": "parameter"
      }
    ]
  }
}
 

К сожалению, эта ошибка ничего не объясняет, и я не смог найти ничего, что помогло бы мне решить ее. Я надеюсь, что кто-нибудь может объяснить, что здесь происходит.

Я поместил все относительные файлы ниже и добавил несколько комментариев.

web.php

 Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
 

YoutubeController.php

 class YoutubeController extends Controller
{
    private $youtube;

    public function __construct(Request $request)
    {
        // like YoutubeStreamService or YoutubeUploadService
        $this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
    }

    public function authenticate($task)
    {
        return redirect()->away($this->youtube->authenticate($task));
    }

    public function create(Request $request, $task)
    {
        $this->youtube->create($request, $task);
    }
}
 

Я использую абстрактный класс для кодов аутентификации.

 abstract class YoutubeAbstraction
{
    // Called from the controller.
    // Returns the url to google to authenticate the request. 
    public function authenticate($task)
    {
        return $this->client($task)->createAuthUrl();
    }

    // This code came from mostly Youtueb API documentation.
    protected function client($task)
    {
        $scopes = [
            'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
            'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
        ][$task];
        $client = new Google_Client();
        $client->setApplicationName("MyApp");
        $client->setScopes($scopes);
        $client->setAuthConfig(base_path("client_secret_{$task}.json"));
        $client->setAccessType('offline');

        return $client;
    }

    abstract public function create($request, $task); 
}
 

YoutubeStreamService.php

 class YoutubeStreamService extends YoutubeAbstraction
{
    // This code came from Youtube API documentation completely.
    // It contains only the required fields and their hard-coded values.
    public function create($request, $task)
    {
        $client = $this->client($task);
        $client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));

        $service = new Google_Service_YouTube($client);        
        $liveBroadcast = new Google_Service_YouTube_LiveBroadcast();

        $liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
        $liveBroadcastSnippet->setTitle('my title');
        $liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00 03:00');
        $liveBroadcast->setSnippet($liveBroadcastSnippet);

        $liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
        $liveBroadcastStatus->setPrivacyStatus('private');
        $liveBroadcast->setStatus($liveBroadcastStatus);

        // If I add dd($liveBroadcast) here, I see the object.
        // So the error is thrown by the function down below.

        $response = $service->liveBroadcasts->insert('', $liveBroadcast);
        print_r($response);
    }
}
 

Ответ №1:

Согласно официальной спецификации, ваш вызов LiveBroadcasts.insert конечной точки API должен включать параметр запроса:

part (строка)

part Параметр служит двум целям в этой операции. Он определяет свойства, которые будет устанавливать операция записи, а также свойства, которые будет включать ответ API.

part Свойства, которые вы можете включить в значение параметра id , snippet , contentDetails , и status .

В PHP это требование сводится к вызову вашего API, подобного приведенному ниже:

 $response = $service->liveBroadcasts->insert(
    'id,snippet,status', $liveBroadcast);
 

Комментарии:

1. Спасибо, stvar, я почти сошел с ума.

Я пытаюсь создать прямую трансляцию Youtube через свою веб-страницу через API данных Youtube. Что бы я ни пробовал, продолжайте получать эту ошибку:

{
  "error": {
    "code": 400,
    "message": "'{0}'",
    "errors": [
      {
        "message": "'{0}'",
        "domain": "youtube.part",
        "reason": "unknownPart",
        "location": "part",
        "locationType": "parameter"
      }
    ]
  }
}

К сожалению, эта ошибка ничего не объясняет, и я не смог найти ничего, что помогло бы мне ее решить. Надеюсь, кто-нибудь сможет объяснить, что здесь происходит.

Я поместил все относительные файлы ниже и добавил несколько комментариев.

Web.php

Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');

YoutubeController.php

class YoutubeController extends Controller
{
    private $youtube;

    public function __construct(Request $request)
    {
        // like YoutubeStreamService or YoutubeUploadService
        $this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
    }

    public function authenticate($task)
    {
        return redirect()->away($this->youtube->authenticate($task));
    }

    public function create(Request $request, $task)
    {
        $this->youtube->create($request, $task);
    }
}

Я использую абстрактный класс для кодов аутентификации.

abstract class YoutubeAbstraction
{
    // Called from the controller.
    // Returns the url to google to authenticate the request. 
    public function authenticate($task)
    {
        return $this->client($task)->createAuthUrl();
    }

    // This code came from mostly Youtueb API documentation.
    protected function client($task)
    {
        $scopes = [
            'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
            'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
        ][$task];
        $client = new Google_Client();
        $client->setApplicationName("MyApp");
        $client->setScopes($scopes);
        $client->setAuthConfig(base_path("client_secret_{$task}.json"));
        $client->setAccessType('offline');

        return $client;
    }

    abstract public function create($request, $task); 
}

YoutubeStreamService.php

class YoutubeStreamService extends YoutubeAbstraction
{
    // This code came from Youtube API documentation completely.
    // It contains only the required fields and their hard-coded values.
    public function create($request, $task)
    {
        $client = $this->client($task);
        $client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));

        $service = new Google_Service_YouTube($client);        
        $liveBroadcast = new Google_Service_YouTube_LiveBroadcast();

        $liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
        $liveBroadcastSnippet->setTitle('my title');
        $liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00+03:00');
        $liveBroadcast->setSnippet($liveBroadcastSnippet);

        $liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
        $liveBroadcastStatus->setPrivacyStatus('private');
        $liveBroadcast->setStatus($liveBroadcastStatus);

        // If I add dd($liveBroadcast) here, I see the object.
        // So the error is thrown by the function down below.

        $response = $service->liveBroadcasts->insert('', $liveBroadcast);
        print_r($response);
    }
}

Right now I’m trying to figure out what i’m doing wrong when making transition of my YT broadcast to live.

So I make the request and get the following response:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "youtube.liveBroadcast",
    "message" : "Invalid transition",
    "reason" : "invalidTransition",
    "extendedHelp" : "https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/transition#params"
  } ],
  "message" : "Invalid transition"
}

Of course i’ve read docs many times so I’ve monitored the LiveStream and was waiting for its «active» state (and my Broadcast has lifeCycleStatus=»ready»).

Error message doesn’t explain real reason why cannot I do the transition.
And… of course I do not have access to logs of Youtube servers :)

What can you suggest?
How to find out where am I wrong?

So even if i’ve missed something, docs and error message do not help me to understand anything. So anyway it is kind of a «bug» for YT LiveStreaming API…

Hello! I’ve been using OBS Studios for a few months now running my streams at 8000kb/s without almost any issue. All of a sudden when I try to go live within the past few days, it either gives me failed to go live/youtube API error message or is running at extremely low rate (as low as 800kb/s) which is unwatchable and unstreamable. The logs gave me the error:
19:49:17.739: «YouTube API request failed: Operation timed out after 16000 milliseconds with 0 bytes received»

I’m just trying to figure out the cause of this issue becuase I haven’t made any changes to how I stream. I’m curious what could cause this massive issue out of nowhere. Any advice on the matter would be really appreciated!!!

(P.S.) My internet randomly crashed recently and the issue seemed to have started after that. I did a test on my internet speeds and it still says I get 300mb/s download and 4mb/s upload. Could my router possibly be going bad or something like that?

Attachments

  • 2022-06-28 19-48-46.txt

    95.5 KB · Views: 30

Cправка — YouTube

Войти

Справка Google

  • Справочный центр
    • Устранение проблем
    • Обучающие видео
    • Как управлять настройками канала
    • Режим родительского контроля на YouTube
    • YouTube Premium
    • Как начать вести свой канал
    • Как зарабатывать с помощью Партнерской программы YouTube
    • Правила, безопасность и авторское право
  • Сообщество
  • YouTube
  • Политика конфиденциальности
  • Условия использования YouTube
  • Отправить отзыв

Тема отзыва

Информация в текущем разделе Справочного центра

Общие впечатления о Справочном центре Google

  • Справочный центр
  • Сообщество
  • Советы авторам

YouTube

Сейчас к нам поступает очень много запросов. Возможно, вам придется ждать ответа дольше обычного.

#php #laravel #youtube-api #youtube-data-api

#php #laravel #youtube-api #youtube-data-api

Вопрос:

Я пытаюсь создать прямую трансляцию Youtube через свою веб-страницу через API данных Youtube. Что бы я ни пробовал, продолжайте получать эту ошибку:

 {
  "error": {
    "code": 400,
    "message": "'{0}'",
    "errors": [
      {
        "message": "'{0}'",
        "domain": "youtube.part",
        "reason": "unknownPart",
        "location": "part",
        "locationType": "parameter"
      }
    ]
  }
}
 

К сожалению, эта ошибка ничего не объясняет, и я не смог найти ничего, что помогло бы мне решить ее. Я надеюсь, что кто-нибудь может объяснить, что здесь происходит.

Я поместил все относительные файлы ниже и добавил несколько комментариев.

web.php

 Route::get('youtube/{task}', [YoutubeController::class, 'authenticate'])->name('youtube.authenticate');
Route::get('youtube/{task}/redirect', [YoutubeController::class, 'create'])->name('youtube.create');
 

YoutubeController.php

 class YoutubeController extends Controller
{
    private $youtube;

    public function __construct(Request $request)
    {
        // like YoutubeStreamService or YoutubeUploadService
        $this->youtube = new ("AppServicesYoutubeYoutube" . ucfirst($request->route()->parameter('task')) . "Service");
    }

    public function authenticate($task)
    {
        return redirect()->away($this->youtube->authenticate($task));
    }

    public function create(Request $request, $task)
    {
        $this->youtube->create($request, $task);
    }
}
 

Я использую абстрактный класс для кодов аутентификации.

 abstract class YoutubeAbstraction
{
    // Called from the controller.
    // Returns the url to google to authenticate the request. 
    public function authenticate($task)
    {
        return $this->client($task)->createAuthUrl();
    }

    // This code came from mostly Youtueb API documentation.
    protected function client($task)
    {
        $scopes = [
            'upload' => ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl'],
            'stream' => ['https://www.googleapis.com/auth/youtube.force-ssl']
        ][$task];
        $client = new Google_Client();
        $client->setApplicationName("MyApp");
        $client->setScopes($scopes);
        $client->setAuthConfig(base_path("client_secret_{$task}.json"));
        $client->setAccessType('offline');

        return $client;
    }

    abstract public function create($request, $task); 
}
 

YoutubeStreamService.php

 class YoutubeStreamService extends YoutubeAbstraction
{
    // This code came from Youtube API documentation completely.
    // It contains only the required fields and their hard-coded values.
    public function create($request, $task)
    {
        $client = $this->client($task);
        $client->setAccessToken($client->fetchAccessTokenWithAuthCode($request->code));

        $service = new Google_Service_YouTube($client);        
        $liveBroadcast = new Google_Service_YouTube_LiveBroadcast();

        $liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
        $liveBroadcastSnippet->setTitle('my title');
        $liveBroadcastSnippet->setScheduledStartTime('2021-04-04T20:00:00.00 03:00');
        $liveBroadcast->setSnippet($liveBroadcastSnippet);

        $liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
        $liveBroadcastStatus->setPrivacyStatus('private');
        $liveBroadcast->setStatus($liveBroadcastStatus);

        // If I add dd($liveBroadcast) here, I see the object.
        // So the error is thrown by the function down below.

        $response = $service->liveBroadcasts->insert('', $liveBroadcast);
        print_r($response);
    }
}
 

Ответ №1:

Согласно официальной спецификации, ваш вызов LiveBroadcasts.insert конечной точки API должен включать параметр запроса:

part (строка)

part Параметр служит двум целям в этой операции. Он определяет свойства, которые будет устанавливать операция записи, а также свойства, которые будет включать ответ API.

part Свойства, которые вы можете включить в значение параметра id , snippet , contentDetails , и status .

В PHP это требование сводится к вызову вашего API, подобного приведенному ниже:

 $response = $service->liveBroadcasts->insert(
    'id,snippet,status', $liveBroadcast);
 

Комментарии:

1. Спасибо, stvar, я почти сошел с ума.

Понравилась статья? Поделить с друзьями:
  • Ошибка создания трансляции youtube api obs
  • Ошибка создания трансляции donationalerts
  • Ошибка создания трансляции description is invalid
  • Ошибка соединения асфальт 9
  • Ошибка соединения xbox 360