使用 Indexing API 的事前準備

使用 Indexing API 之前,您必須先完成以下程序:

為用戶端建立專案

您必須先向 Google 提供用戶端的相關資訊,並啟用 Indexing API 的存取權,才能開始對 API 發出要求。如要完成上述操作,請透過 Google API 控制台建立一個「專案」(專案指的是一種具名的集合,其中含有各種設定及 API 存取權的相關資訊),並註冊您的應用程式。

如要開始使用 Indexing API,請使用設定工具;這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

建立服務帳戶

  1. 開啟「服務帳戶」頁面。如果出現系統提示,請選取您要使用的專案。
  2. 按一下 [ 建立服務帳戶],然後輸入服務帳戶的名稱和說明。您可以使用預設的服務帳戶 ID,也可以自行選擇其他不重複的名稱。完成後,請按一下 [建立]
  3. 系統會隨即顯示「服務帳戶權限」部分,不過您不一定要設定這些權限。請按一下 [繼續]。
  4. 在「將這個服務帳戶的存取權授予使用者」畫面中,向下捲動至「建立金鑰」部分。按一下 [ 建立金鑰]
  5. 在隨即顯示的側邊面板中選取金鑰格式;建議您選擇 [JSON]
  6. 按一下 [建立],接著,系統就會為您產生一對新的公開/私密金鑰,並下載至您的電腦中;這是金鑰的唯一副本,如要瞭解安全儲存的方式,請參閱管理服務帳戶金鑰
  7. 在 [已將私密金鑰儲存至您的電腦中] 對話方塊中按一下 [關閉],然後再按一下 [完成],即可返回您的服務帳戶表格。

將服務帳戶新增為網站擁有者

如何將服務帳戶新增為網站擁有者:

  1. 請先透過 Search Console 驗證網站擁有權,然後
  2. 將服務帳戶新增為擁有者。

1. 證明您是網站的擁有者

透過 Search Console 驗證網站擁有權。您可以使用 Search Console 支援的任何驗證方法,並且可以建立網域資源 (example.com) 或網址前置字元資源 (https://example.comhttps://example.com/some/path/) 來代表網站。請注意,「資源」是網站在 Search Console 中的稱呼。

2. 將擁有者狀態授予服務帳戶

接下來,請將服務帳戶新增為 (委派) 網站擁有者:

  1. 開啟網站管理員中心
  2. 按一下您已驗證擁有權的資源。
  3. 在 [已驗證擁有者] 清單中,按一下 [新增擁有者]
  4. 提交做為委派擁有者的服務帳戶電子郵件。您可以在以下兩個位置找到服務帳戶的電子郵件地址:
    • 建立專案時所下載 JSON 私密金鑰中的 client_email 欄位。
    • Developers Console 中,「服務帳戶」檢視畫面的「服務帳戶 ID」資料欄。
    這個電子郵件地址使用的格式如下:
    my-service-account@project-name.google.com.iam.gserviceaccount.com
    範例: my-service-account@test-project-42.google.com.iam.gserviceaccount.com

取得存取權杖

所有傳送至 Indexing API 的呼叫都必須使用 OAuth 權杖進行驗證;這個權杖是以私密金鑰交換而得,且每個權杖只會在一定時間內有效。您可以透過 Google 提供的 API 用戶端程式庫取得數種程式語言的 OAuth 權杖。

需求條件

向 Indexing API 提交要求時,請確認您的要求符合以下條件:

  1. 使用 https://www.googleapis.com/auth/indexing 做為範圍。
  2. 採用使用 API 一文所描述的其中一個端點。
  3. 包含服務帳戶存取憑證
  4. 按照使用 API 一文中的說明定義要求主體。

範例

下列範例說明如何取得 OAuth 存取憑證:

Python

使用適用於 Python 的 Google API 用戶端程式庫取得 OAuth 憑證:

from oauth2client.service_account import ServiceAccountCredentials
import httplib2

SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"

# service_account_file.json is the private key that you created for your service account.
JSON_KEY_FILE = "service_account_file.json"

credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)

http = credentials.authorize(httplib2.Http())

# Define contents here as a JSON string.
# This example shows a simple update request.
# Other types of requests are described in the next step.

content = """{
  \"url\": \"http://example.com/jobs/42\",
  \"type\": \"URL_UPDATED\"
}"""

response, content = http.request(ENDPOINT, method="POST", body=content)

Java

使用適用於 Java 的 API 用戶端程式庫取得 OAuth 憑證:

String scopes = "https://www.googleapis.com/auth/indexing";
String endPoint = "https://indexing.googleapis.com/v3/urlNotifications:publish";

JsonFactory jsonFactory = new JacksonFactory();

// service_account_file.json is the private key that you created for your service account.
InputStream in = IOUtils.toInputStream("service_account_file.json");

GoogleCredential credentials =
  GoogleCredential.fromStream(in, this.httpTransport, jsonFactory).createScoped(Collections.singleton(scopes));

GenericUrl genericUrl = new GenericUrl(endPoint);
HttpRequestFactory requestFactory = this.httpTransport.createRequestFactory();

// Define content here. The structure of the content is described in the next step.
String content = "{"
  + "\"url\": \"http://example.com/jobs/42\","
  + "\"type\": \"URL_UPDATED\","
  + "}";

HttpRequest request =
  requestFactory.buildPostRequest(genericUrl, ByteArrayContent.fromString("application/json", content));

credentials.initialize(request);
HttpResponse response = request.execute();
int statusCode = response.getStatusCode();

PHP

使用適用於 PHP 的 API 用戶端程式庫取得 OAuth 憑證:

require_once 'google-api-php-client/vendor/autoload.php';

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig('service_account_file.json');
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = '{
  "url": "http://example.com/jobs/42",
  "type": "URL_UPDATED"
}';

$response = $httpClient->post($endpoint, [ 'body' => $content ]);
$status_code = $response->getStatusCode();

Node.js

使用 Node.js 用戶端程式庫取得 OAuth 憑證:

var request = require("request");
var { google } = require("googleapis");
var key = require("./service_account.json");

const jwtClient = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  ["https://www.googleapis.com/auth/indexing"],
  null
);

jwtClient.authorize(function(err, tokens) {
  if (err) {
    console.log(err);
    return;
  }
  let options = {
    url: "https://indexing.googleapis.com/v3/urlNotifications:publish",
    method: "POST",
    // Your options, which must include the Content-Type and auth headers
    headers: {
      "Content-Type": "application/json"
    },
    auth: { "bearer": tokens.access_token },
    // Define contents here. The structure of the content is described in the next step.
    json: {
      "url": "http://example.com/jobs/42",
      "type": "URL_UPDATED"
    }
  };
  request(options, function (error, response, body) {
    // Handle the response
    console.log(body);
  });
});

上述範例除了示範如何取得憑證,也說明了可以在哪裡加入要求訊息的主體。如要瞭解您可以傳送的呼叫類型有哪些,以及這些呼叫的訊息主體結構為何,請參閱使用 API 一文。