上传视频

借助 YouTubeVideoUploadService ,您可以通过 Google Ads API 将视频直接上传到 YouTube。然后,您可以使用这些 视频在各种广告类型(例如 效果最大化广告系列或 需求开发广告系列)中创建视频素材资源。

此服务通过处理 YouTube 上传流程来简化视频广告的制作工作流程,确保视频与您的账号正确关联。

主要概念

在开始之前,请务必了解如何管理视频上传以及视频可能经历的不同状态。

端到端的工作流程

上传视频文件并在广告中投放需要按顺序执行以下四个步骤:

步骤 服务和方法 摘要
1. 启动并上传视频字节 YouTubeVideoUploadService 上的 CreateYouTubeVideoUpload 上传视频元数据和二进制文件,以创建 YouTubeVideoUpload 资源 (customers/{customer_id}/youTubeVideoUploads/{video_upload_id})。
**2. 轮询处理状态 GoogleAdsService 上的 SearchStream 查询 you_tube_video_upload,直到 state = 'PROCESSED' 且 11 个字符的 YouTube video_id 填充完毕。
3. 创建可重复使用的视频素材资源 AssetService 上的 MutateAssets 创建 YoutubeVideoAsset (youtube_video_id = video_id) 以获取素材资源名称 (customers/{customer_id}/assets/{asset_id})。
4. 将素材资源关联到广告系列或广告 AssetGroupAssetService 上的 MutateAssetGroupAssets 或 AdGroupAdService 上的 MutateAdGroupAds 将素材资源关联到效果最大化广告系列 AssetGroupAsset (field_type = YOUTUBE_VIDEO) 或需求开发广告系列 DemandGenVideoResponsiveAdInfo (videos[].asset)。

频道所有权

上传视频时,您可以使用 channel_id字段YouTubeVideoUpload 指定目标 YouTube 频道:

  • 广告客户拥有的(品牌)频道 :提供广告客户拥有的现有 YouTube 频道的 channel_id。此功能仅支持 用户身份验证流程, 不能与服务账号搭配使用。
  • Google 管理的频道 :如果省略 channel_id,视频将上传到与 Google Ads 账号关联的 Google 管理的 YouTube 频道。

上传状态

state 字段用于跟踪 YouTube 视频上传的生命周期。The YouTubeVideoUploadState 枚举定义了以下状态:

状态 说明
PENDING 正在上传视频。
UPLOADED 视频已成功上传,YouTube 正在处理该视频。
PROCESSED 视频已成功处理,可以使用。
FAILED 上传或处理失败,无法完成。
REJECTED 由于验证或政策原因,视频被拒绝。
UNAVAILABLE 视频状态不可用;视频可能已从 YouTube 中移除。

隐私设置

video_privacy 字段用于控制哪些人可以观看上传的视频。 YouTubeVideoPrivacy 枚举支持:

  • PUBLIC:YouTube 上的任何人都可以观看该视频。(仅允许品牌频道使用)。
  • UNLISTED:该视频无法搜索,但拥有链接的任何人都可以观看。这是 Google 管理的频道的默认选项,也是唯一选项。

生成式内容披露

从 v26 开始,根据《欧盟 AI 法案》等法规,广告客户可以披露上传的视频内容是否包含 AI 生成的媒体或合成媒体。

YouTubeVideoUpload 中的 video_content_metadata 字段包含 VideoContentMetadata。使用 YouTubeVideoUploadGenerativeContentDisclosure 枚举设置其嵌套 generative_content_disclosure字段:

值 说明
NON_GENERATIVE_CONTENT 广告客户披露该视频并非由 AI 生成。
GENERATIVE_CONTENT 广告客户披露该视频由 AI 生成。

上传视频

如需上传视频,您必须使用多部分请求向 CreateYouTubeVideoUpload 方法发送请求。该请求包含上传的元数据和视频文件本身。

1. 启动上传

使用以下字段构建 CreateYouTubeVideoUploadRequest:

字段 要求 说明和限制
customer_id 必填 10 位数字的 Google Ads 客户 ID(不含连字符)。
you_tube_video_upload.video_title 必填(INPUT_ONLY、IMMUTABLE) YouTube 上上传的视频的标题(最多 100 个字符;不能包含 < 或 >)。
you_tube_video_upload.video_description 选填(INPUT_ONLY、IMMUTABLE) YouTube 上视频的说明(最多 5,000 个字符;不能包含 < 或 >)。
you_tube_video_upload.channel_id 选填(IMMUTABLE) 广告客户拥有的品牌频道的目标 24 个字符的 YouTube 频道 ID(以 UC 开头)。如果省略,则上传到 Google 管理的频道。
you_tube_video_upload.video_privacy 选填(可在品牌频道上更改) YouTubeVideoPrivacy 设置(默认值为 UNLISTED,对于广告客户拥有的品牌频道,则为 PUBLIC)。
you_tube_video_upload.video_content_metadata 选填(INPUT_ONLY、IMMUTABLE) 从 v26 开始提供:VideoContentMetadata,其中 generative_content_disclosure 设置为 YouTubeVideoUploadGenerativeContentDisclosure 值(NON_GENERATIVE_CONTENT 或 GENERATIVE_CONTENT)。

如果您使用的是客户端库,请调用 CreateYouTubeVideoUpload 方法,传递您的视频文件,视频上传将在 内部处理。

Java

String videoUploadResourceName;
try (YouTubeVideoUploadServiceClient youTubeVideoUploadServiceClient =
    googleAdsClient.getLatestVersion().createYouTubeVideoUploadServiceClient()) {
  YouTubeVideoUpload youTubeVideoUpload =
      YouTubeVideoUpload.newBuilder()
          .setVideoTitle("Test Video")
          .setVideoDescription("Test Video Description")
          .setVideoPrivacy(YouTubeVideoPrivacy.UNLISTED)
          .build();

  CreateYouTubeVideoUploadRequest createUploadRequest =
      CreateYouTubeVideoUploadRequest.newBuilder()
          .setCustomerId(Long.toString(customerId))
          .setYouTubeVideoUpload(youTubeVideoUpload)
          .build();

  CreateYouTubeVideoUploadResponse response =
      youTubeVideoUploadServiceClient.createYouTubeVideoUpload(
          createUploadRequest, () -> new FileInputStream(videoFile), null);

  videoUploadResourceName = response.getResourceName();
  System.out.printf("Created YouTube video upload: %s%n", videoUploadResourceName);
}
      

C#

YouTubeVideoUploadServiceClient ytService = client.GetService(
    Services.V26.YouTubeVideoUploadService);

CreateYouTubeVideoUploadRequest createUploadRequest =
    new CreateYouTubeVideoUploadRequest()
    {
        CustomerId = customerId.ToString(),
        YouTubeVideoUpload = new YouTubeVideoUpload()
        {
            VideoTitle = "Test Video",
            VideoDescription = "Test Video Description",
            VideoPrivacy = YouTubeVideoPrivacy.Unlisted
        }
    };

string videoUploadResourceName;
using (FileStream stream = File.OpenRead(videoFilePath))
{
    ResumableUploadSession<CreateYouTubeVideoUploadRequest, CreateYouTubeVideoUploadResponse> session =
        ytService.CreateYouTubeVideoUpload();
    CreateYouTubeVideoUploadResponse response =
        session.BeginUploadAsync(createUploadRequest, stream).Result;

    videoUploadResourceName = response.ResourceName;
    Console.WriteLine($"Created YouTube video upload: {videoUploadResourceName}");
}
      

PHP

$youTubeVideoUploadServiceClient = $googleAdsClient->getYouTubeVideoUploadServiceClient();

$youTubeVideoUpload = new YouTubeVideoUpload([
    'video_title' => 'Test Video',
    'video_description' => 'Test Video Description',
    'video_privacy' => YouTubeVideoPrivacy::UNLISTED
]);

$createYouTubeVideoUploadRequest = CreateYouTubeVideoUploadRequest::build(
    $customerId,
    $youTubeVideoUpload
);

/** @var ResumableUpload $resumableUpload */
$resumableUpload = $youTubeVideoUploadServiceClient->createYouTubeVideoUpload(
    $createYouTubeVideoUploadRequest
);

$stream = Utils::streamFor(fopen($videoFilePath, 'rb'));
/** @var CreateYouTubeVideoUploadResponse $response */
$response = $resumableUpload->startUpload($stream);

$videoUploadResourceName = $response->getResourceName();
printf("Created YouTube video upload: '%s'%s", $videoUploadResourceName, PHP_EOL);
      

Python

yt_service: YouTubeVideoUploadServiceClient = client.get_service(
    "YouTubeVideoUploadService"
)

create_upload_request: CreateYouTubeVideoUploadRequest = (
    youtube_video_upload_service.CreateYouTubeVideoUploadRequest()
)
create_upload_request.customer_id = customer_id
create_upload_request.you_tube_video_upload.video_title = "Test Video"
create_upload_request.you_tube_video_upload.video_description = (
    "Test Video Description"
)
create_upload_request.you_tube_video_upload.video_privacy = (
    client.enums.YouTubeVideoPrivacyEnum.UNLISTED
)

video_upload_resource_name: str
with open(video_file_path, "rb") as stream:
    response: CreateYouTubeVideoUploadResponse = (
        yt_service.create_you_tube_video_upload(
            stream=stream,
            request=create_upload_request,
            retry=None,
        )
    )
    video_upload_resource_name = response.resource_name
    print(f"Created YouTube video upload: {video_upload_resource_name}")
      

Ruby

video_upload = client.resource.you_tube_video_upload do |v|
  v.video_title = "Test Video"
  v.video_description = "Test Video Description"
  v.video_privacy = :UNLISTED
end

upload = client.service.you_tube_video_upload.create_you_tube_video_upload(
  customer_id: customer_id,
  you_tube_video_upload: video_upload,
)

video_upload_resource_name = nil
File.open(video_file_path, "rb") do |stream|
  response = upload.start(
    stream: stream,
    content_type: "application/octet-stream",
  )
  video_upload_resource_name = response.resource_name
  puts "Created YouTube video upload: #{video_upload_resource_name}"
end
      

Perl

This example is not yet available in Perl; you can take a look at the other languages.
    

curl

# 
# Use the --i curl parameter to capture response headers in the $RESPONSE
# variable.
FILE_SIZE=$(wc -c < "${VIDEO_FILE_NAME}" | tr -d '\r')
RESPONSE=$(curl -i -f -v -s --request POST \
"https://googleads.googleapis.com/resumable/upload/v${API_VERSION}/customers/${CUSTOMER_ID}/youTubeVideoUploads:create" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--header "X-Goog-Upload-Protocol: resumable" \
--header "X-Goog-Upload-Command: start" \
--header "X-Goog-Upload-Header-Content-Length: ${FILE_SIZE}" \
--data @- <<EOF
{
  "customer_id": "${CUSTOMER_ID}",
  "you_tube_video_upload": {
    "video_title": "${VIDEO_TITLE}",
    "video_description": "${VIDEO_DESCRIPTION}",
    "video_privacy": "UNLISTED"
  }
}
EOF
)

# Extract the value of the "x-goog-upload-url" header from the HTTP response.
UPLOAD_URL=$(echo "${RESPONSE}" \
  | grep -i '^x-goog-upload-url' \
  | awk '{print $2}' \
  | tr -d '\r')
CHUNK_SIZE=$(echo "${RESPONSE}" \
  | grep -i '^x-goog-upload-chunk-granularity' \
  | awk '{print $2}' \
  | tr -d '\r')
      

如果您使用的是 REST,请参阅以下部分,了解如何管理视频上传。

2. 上传视频

使用 REST 上传时,CreateYouTubeVideoUpload 使用两步 可续传上传协议:

  1. 启动上传会话: 向 CreateYouTubeVideoUpload上传端点 (/upload/v26/customers/{customer_id}/youTubeVideoUploads:create) 发送初始POST请求,并使用x-goog-upload-command: start(还可以选择使用 x-goog-upload-header-content-length声明文件大小)。响应会在 x-goog-upload-url HTTP 响应标头中返回上传会话网址,以及预期 chunk 大小等元数据。
  2. 流式传输并最终确定视频字节 :向 x-goog-upload-url 端点发送二进制视频有效负载,并使用 x-goog-upload-command: upload, finalize。上传完成后,响应会返回创建的 resource_name (customers/{customer_id}/youTubeVideoUploads/{video_upload_id})。

如需详细了解视频上传协议中使用的 HTTP 标头,请参阅以下代码示例:

# Take the first ${CHUNK_SIZE} bytes of the video file and upload them.
head -c ${CHUNK_SIZE} ${VIDEO_FILE_NAME} | curl -i -v -X PUT "${UPLOAD_URL}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--header "X-Goog-Upload-Offset: 0" \
--header "X-Goog-Upload-Command: upload" \
--header "Content-Length: ${CHUNK_SIZE}" \
--data-binary @-

# Query the status of the upload.
QUERY_RESPONSE=$(curl -i -s -X POST "${UPLOAD_URL}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--header "X-Goog-Upload-Command: query")

# Extract the value of the "x-goog-upload-size-received" header from the HTTP
# response.
UPLOADED_BYTES=$(echo "${QUERY_RESPONSE}" \
  | grep -i '^x-goog-upload-size-received' \
  | awk '{print $2}' \
  | tr -d '\r')

echo "Uploaded ${UPLOADED_BYTES} bytes."

REMAINING_BYTES=$((FILE_SIZE - UPLOADED_BYTES))
echo "${REMAINING_BYTES} bytes remaining to upload."

FINALIZE_RESPONSE=$(tail -c ${REMAINING_BYTES} ${VIDEO_FILE_NAME} | curl -v -X PUT "${UPLOAD_URL}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--header "X-Goog-Upload-Offset: ${UPLOADED_BYTES}" \
--header "X-Goog-Upload-Command: upload, finalize" \
--data-binary @-)
UPLOADED_VIDEO_RESOURCE_NAME=$(echo $FINALIZE_RESPONSE | jq -r '.resourceName')
      

3. 检索视频上传状态

开始上传视频后,请使用 GAQL 查询 you_tube_video_upload资源的可选字段 (resource_name、video_upload_id、channel_id、video_id、state 和 video_privacy),以轮询其处理状态,直到 state = 'PROCESSED'(无法在 GAQL 中选择 INPUT_ONLY 字段):

Java

// Retrieve the metadata of the newly uploaded video.
String query =
    String.format(
        "SELECT "
            + "you_tube_video_upload.resource_name, "
            + "you_tube_video_upload.video_id, "
            + "you_tube_video_upload.state "
            + "FROM you_tube_video_upload "
            + "WHERE you_tube_video_upload.resource_name = '%s'",
        videoUploadResourceName);

try (GoogleAdsServiceClient googleAdsServiceClient =
    googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
  SearchGoogleAdsStreamRequest request =
      SearchGoogleAdsStreamRequest.newBuilder()
          .setCustomerId(Long.toString(customerId))
          .setQuery(query)
          .build();

  ServerStream<SearchGoogleAdsStreamResponse> stream =
      googleAdsServiceClient.searchStreamCallable().call(request);

  for (SearchGoogleAdsStreamResponse response : stream) {
    for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
      YouTubeVideoUpload video = googleAdsRow.getYouTubeVideoUpload();
      System.out.printf(
          "Video with ID %s was found in state %s.%n",
          video.getVideoId(), video.getState());
    }
  }
}
      

C#

// Retrieve the metadata of the newly uploaded video.
string query = $@"
    SELECT
      you_tube_video_upload.resource_name,
      you_tube_video_upload.video_id,
      you_tube_video_upload.state
    FROM you_tube_video_upload
    WHERE you_tube_video_upload.resource_name = '{videoUploadResourceName}'";

GoogleAdsServiceClient gaService = client.GetService(
    Services.V26.GoogleAdsService);

gaService.SearchStream(customerId.ToString(), query,
    delegate (SearchGoogleAdsStreamResponse resp)
    {
        foreach (GoogleAdsRow row in resp.Results)
        {
            Console.WriteLine(
                $"Video with ID {row.YouTubeVideoUpload.VideoId} was found in " +
                $"state {row.YouTubeVideoUpload.State}.");
        }
    }
);
      

PHP

// Retrieve the metadata of the newly uploaded video.
$query = sprintf(
    "SELECT you_tube_video_upload.resource_name, "
    . "you_tube_video_upload.video_id, "
    . "you_tube_video_upload.state "
    . "FROM you_tube_video_upload "
    . "WHERE you_tube_video_upload.resource_name = '%s'",
    $videoUploadResourceName
);

$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
$stream = $googleAdsServiceClient->searchStream(
    SearchGoogleAdsStreamRequest::build($customerId, $query)
);

foreach ($stream->iterateAllElements() as $googleAdsRow) {
    /** @var GoogleAdsRow $googleAdsRow */
    printf(
        "Video with ID '%s' was found in state '%s'.%s",
        $googleAdsRow->getYouTubeVideoUpload()->getVideoId(),
        YouTubeVideoUploadState::name($googleAdsRow->getYouTubeVideoUpload()->getState()),
        PHP_EOL
    );
}
      

Python

# Retrieve the metadata of the newly uploaded video.
query: str = f"""
    SELECT
      you_tube_video_upload.resource_name,
      you_tube_video_upload.video_id,
      you_tube_video_upload.state
    FROM you_tube_video_upload
    WHERE you_tube_video_upload.resource_name = '{video_upload_resource_name}'"""

ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")
stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
    customer_id=customer_id, query=query
)

for row in itertools.chain.from_iterable(batch.results for batch in stream):
    video = row.you_tube_video_upload
    print(
        f"Video with ID {row.you_tube_video_upload.video_id} was found in state {row.you_tube_video_upload.state}."
    )
      

Ruby

# Retrieve the metadata of the newly uploaded video.
query = <<~EOQ
  SELECT
    you_tube_video_upload.resource_name,
    you_tube_video_upload.video_id,
    you_tube_video_upload.state
  FROM you_tube_video_upload
  WHERE you_tube_video_upload.resource_name = '#{video_upload_resource_name}'
EOQ

responses = client.service.google_ads.search_stream(
  customer_id: customer_id,
  query: query,
)

responses.each do |batch|
  batch.results.each do |row|
    puts "Video with ID #{row.you_tube_video_upload.video_id} was found in " \
      "state #{row.you_tube_video_upload.state}."
  end
end
      

Perl

This example is not yet available in Perl; you can take a look at the other languages.
    

curl

curl -i -v -X POST \
"https://qa-prod-googleads.sandbox.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search" \
--header "Content-Type: application/json" \
  --header "Developer-Token: ${DEVELOPER_TOKEN}" \
  --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
  --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
  --data @- <<EOF
{
  "query": "SELECT you_tube_video_upload.resource_name, you_tube_video_upload.video_id, you_tube_video_upload.state FROM you_tube_video_upload WHERE you_tube_video_upload.resource_name = '$UPLOADED_VIDEO_RESOURCE_NAME'"
}
EOF
      

管理上传

视频上传完成后,您可以将其用作视频素材资源。

使用上传的视频

视频达到 PROCESSED 状态后,您可以在 YouTubeVideoUpload 资源的 video_id 字段中找到其 11 个字符的 YouTube 视频 ID。

使用此 video_id 通过 YoutubeVideoAsset 创建 MutateAssets,并将生成的素材资源名称 (customers/{customer_id}/assets/{asset_id}) 关联到您的广告系列或广告:

  1. 通过将 youtube_video_id 传递给 AssetService.MutateAssets**创建 YoutubeVideoAsset**:

    POST https://googleads.googleapis.com/v26/customers/{customer_id}/assets:mutate
    {
      "operations": [
        {
          "create": {
            "name": "Product Launch Video",
            "youtubeVideoAsset": {
              "youtubeVideoId": "dQw4w9WgXcQ"
            }
          }
        }
      ]
    }
    
  2. 将 Asset 关联到 AssetGroup 或 AdGroupAd:

    • 效果最大化广告系列 :使用 AssetGroupAssetService.MutateAssetGroupAssets 创建 AssetGroupAsset,并将 field_type 设置为 YOUTUBE_VIDEO:

      POST https://googleads.googleapis.com/v26/customers/{customer_id}/assetGroupAssets:mutate
      {
        "operations": [
          {
            "create": {
              "assetGroup": "customers/{customer_id}/assetGroups/{asset_group_id}",
              "asset": "customers/{customer_id}/assets/{asset_id}",
              "fieldType": "YOUTUBE_VIDEO"
            }
          }
        ]
      }
      
    • 需求开发广告系列 :调用 AdGroupAdService.MutateAdGroupAds 时,在 DemandGenVideoResponsiveAdInfo 对象的 videos 列表中引用 customers/{customer_id}/assets/{asset_id}:

      POST https://googleads.googleapis.com/v26/customers/{customer_id}/adGroupAds:mutate
      {
        "operations": [
          {
            "create": {
              "adGroup": "customers/{customer_id}/adGroups/{ad_group_id}",
              "status": "PAUSED",
              "ad": {
                "name": "Demand Gen Video Ad",
                "finalUrls": ["https://www.example.com"],
                "demandGenVideoResponsiveAd": {
                  "videos": [
                    {
                      "asset": "customers/{customer_id}/assets/{asset_id}"
                    }
                  ],
                  "logoImages": [
                    {
                      "asset": "customers/{customer_id}/assets/{logo_asset_id}"
                    }
                  ],
                  "headlines": [
                    {
                      "text": "Example Headline"
                    }
                  ],
                  "longHeadlines": [
                    {
                      "text": "Example Long Headline"
                    }
                  ],
                  "descriptions": [
                    {
                      "text": "Example Description"
                    }
                  ],
                  "businessName": {
                    "text": "Example Business"
                  }
                }
              }
            }
          }
        ]
      }
      
  3. 使用 GoogleAdsService.SearchStream**查询现有 YOUTUBE_VIDEO 素材资源**:

    SELECT
      asset.id,
      asset.resource_name,
      asset.name,
      asset.type,
      asset.youtube_video_asset.youtube_video_id,
      asset.youtube_video_asset.youtube_video_title
    FROM asset
    WHERE asset.type = 'YOUTUBE_VIDEO'
      AND asset.youtube_video_asset.youtube_video_id = '{video_id}'
    

更新元数据

您可以使用 UpdateYouTubeVideoUpload 方法更新通过此 API 上传的视频的隐私设置,并将 update_mask 设置为 "video_privacy"。创建后,只能更新 video_privacy 字段(对于上传到广告客户拥有的品牌频道的视频,为 PUBLIC 或 UNLISTED);video_title、video_description、channel_id 和 video_content_metadata 是不可变的。

移除上传

如果您需要删除使用 Google Ads API 上传的视频,请在 customers/{customer_id}/youTubeVideoUploads/{video_upload_id} 字段中传递其 资源名称 的resource_namesRemoveYouTubeVideoUpload方法。这会从 Google Ads 素材资源库和 YouTube 中移除视频。