Меню

Ошибка создания трансляции ошибка 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);
    }
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка создания трансляции обс
  • Ошибка социал клаб код ошибки 1005