PHP Client 操作 Google APIs (4) 使用 Google Search Console APIs

這系列的最後一篇,原本以為已經寫完了,今天發現這篇躺在草稿裡 … 還不清楚怎麼回事的朋友可以看前面幾篇 PHP Client 操作 Google APIs (1) 開啟與測試 APIPHP Client 操作 Google APIs (2) 安裝 Google API Client for PHPPHP Client 操作 Google APIs (3) Google APIs Credentials 介紹,這篇記錄如何使用 Google Search Console APIs。

我們在前幾篇裡面瞭解了 Google APIs、安裝 Client for PHP 以及申請了 Google APIs Credentials 裡的 Service Account 並下載了 JSON (一定要好好保存,遺失了只能刪除再產生一次,沒辦法再次下載喔),開始使用!

Google APIs 大致流程

使用 Google APIs 大致上的流程都差不多

  • 載入 Google APIs Client for PHP (或其他語言版本)
  • 加入 Service Account
  • 建立並初始化物件
  • 設定篩選條件
  • 取得並解析結果

只要把握這幾個原則,之後若要使用 Google APIs 就不會再霧沙沙了 (但 API 還是要查,每個 API 的 Scope 跟條件設定上會有很大的不同)

載入 Google APIs Client for PHP

這個在前面 PHP Client 操作 Google APIs (2) 安裝 Google API Client for PHP 的時候已經講過了,在程式碼裡面很簡單,開頭放上這行就可以了,為了更方便 debug,可以多設定兩行條件,只要使用上出現錯誤,就會直接在網頁上呈現

// 顯示錯誤
ini_set('display_errors', '1');
// 所有錯誤都顯示
error_reporting(E_ALL);
// 載入 Google Client
require_once '../googleapiclient/vendor/autoload.php';

加入 Service Account

小蛙前面提到這次要做的事情是讓程式不經人工自動執行,而 Search Console 能使用的方式只有 OAuth 與 Service Account (忘記差別的這邊請 PHP Client 操作 Google APIs (3) Google APIs Credentials 介紹),要不需人工介入只有 Service Account 了,而要讓 Service Account 存取 Search Console 資料的話,就必須將該帳號加入 Search Console 裡面囉!

首先進入 Search Console 要使用的資源,左邊選單下面找到「設定」

點擊「使用者與權限」

點擊「新增使用者」並把從 GCP Credentials 那邊得到的 Service Account 貼上,權限選擇「完整」

建立並初始化物件

回到 PHP 的部份加入金鑰及設定 Scope

// 設定金鑰
putenv('GOOGLE_APPLICATION_CREDENTIALS=存放金鑰的路徑/server_secrets.json');
session_start();

// 建立基本 Google Client
$client = new Google_Client();
// 載入預設金鑰位置
$client->useApplicationDefaultCredentials();
// 設定 Scope
$client->addScope([Google_Service_Webmasters::WEBMASTERS_READONLY, Google_Service_Webmasters::WEBMASTERS]);
$client->setAccessType('offline');
// 建立基本 Google Service Webmasters 物件
$master = new Google_Service_Webmasters($client);

設定篩選條件

建立完要用的 Google Service Webmasters 物件之後,對!以前 Google Search Console 叫做 Google Webmaster,雖然我們說要操作 Search Console 但建立的物件跟設定的 Scope 可以看出都還是 Webmasters。

$search = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$search->setStartDate( '2021-07-06' );
$search->setEndDate( '2021-08-06' );
$search->setDimensions( ['QUERY'] );
$search->setAggregationType( 'BY_PROPERTY' );
$search->setRowLimit(10);

至於有哪些條件或是要怎麼操作取得自己要的內容,就自己到 API Explorer 測試,或到 PHP Client 操作 Google APIs (1) 開啟與測試 API 複習吧!

取得並解析結果

最後把他們全部串起來~丟回的結果可以先用 print_r 印出來看看,或是直接到 這邊 看回傳的結果 ~

$data = $master->searchanalytics->query('https://noter.tw/', $search);

$result = [];
$rows = $data->rows;
foreach ($rows as $row){
    // 剖析資料
}

到這邊基本上就大功告成了,上面的功能是取得網站上特定區間的關鍵字資訊 ~ 需要其他資料的話,釣竿已經在手了,就要靠自己囉!Good Luck ~

2 則留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *