Cách tạo API, cấp quyền, cài đặt thư viện và sử dụng PHP để đọc/ghi dữ liệu trên Google Sheets.
📌1. Tạo Google Sheets API và Credentials
🔹 Bước 1: Tạo dự án trên Google Cloud
👉 https://console.cloud.google.com/
👉Chọn hoặc tạo một dự án mới.
👉Nhấn vào Chọn dự án (Select a project).
👉Nhấn Tạo dự án mới (New Project) → Nhập tên dự án → Nhấn Tạo.
🔹 Bước 2: Bật Google Sheets API (Drive API cần thiết nếu bạn muốn cấp quyền truy cập file.)
👉Đi đến "API & Services" > "Library".
👉Tìm Google Sheets API, nhấn Enable (Bật).
👉Tìm Google Drive API, nhấn Enable (Bật).
🔹 Bước 3: Tạo Credentials (Thông tin xác thực)
📌 4. Viết Code PHP để Kết Nối Google Sheets API
🔹 Bước 6: Viết file
🔹 Bước 7: Viết code đọc dữ liệu
🔹 Bước 8: Viết code ghi dữ liệu vào Google Sheets
👉Tìm Google Sheets API, nhấn Enable (Bật).
👉Tìm Google Drive API, nhấn Enable (Bật).
🔹 Bước 3: Tạo Credentials (Thông tin xác thực)
👉Đi đến "API & Services" > "Credentials".
👉Nhấn "Create Credentials" (Tạo thông tin xác thực) > Chọn "Service Account".
👉Nhập tên Service Account (VD:
👉Nhấn "Create" > "Continue" > "Done".
👉Tạo Private Key:
- Trong danh sách Service Account, nhấn vào tài khoản vừa tạo.
- Chuyển đến tab "Keys" > Nhấn "Add Key" > Chọn "JSON".
- File JSON sẽ được tải về máy bạn. (Lưu file này cẩn thận, nó chứa key API).
👉Nhấn "Create Credentials" (Tạo thông tin xác thực) > Chọn "Service Account".
👉Nhập tên Service Account (VD:
google-sheets-access).👉Nhấn "Create" > "Continue" > "Done".
👉Tạo Private Key:
- Trong danh sách Service Account, nhấn vào tài khoản vừa tạo.
- Chuyển đến tab "Keys" > Nhấn "Add Key" > Chọn "JSON".
- File JSON sẽ được tải về máy bạn. (Lưu file này cẩn thận, nó chứa key API).
📌2. Cấp quyền cho Google Sheets API
🔹 Bước 4: Cấp quyền truy cập cho Service Account
👉Mở Google Sheets của bạn.
👉Nhấn "Share" (Chia sẻ).
👉Thêm email của Service Account (tìm thấy trong file JSON).
👉Cấp quyền "Editor" (Chỉnh sửa) để API có thể ghi dữ liệu vào Sheets.
👉Nhấn "Share" (Chia sẻ).
👉Thêm email của Service Account (tìm thấy trong file JSON).
👉Cấp quyền "Editor" (Chỉnh sửa) để API có thể ghi dữ liệu vào Sheets.
📌 3. Cài Đặt Google Sheets API vào PHP
🔹 Bước 5: Cài đặt thư viện Google API Client
composer require google/apiclient
(Nếu bạn chưa cài Composer, tải về tại https://getcomposer.org/).
Sau khi cài đặt thành công, bạn sẽ thấy thư mục
vendor/ xuất hiện.🔹 Bước 6: Viết file
config.php để kết nốirequire 'vendor/autoload.php';
use Google\Client;use Google\Service\Sheets;
define('SPREADSHEET_ID', '1abcxyz...'); // Thay bằng ID Google Sheets của bạndefine('SHEET_NAME', 'licenses'); // Thay bằng tên sheet bạn muốn sử dụngdefine('SERVICE_ACCOUNT_FILE', 'credentials.json'); // Đổi tên file JSON đúng
function getGoogleSheetsService() { $client = new Client(); $client->setApplicationName("Google Sheets API PHP"); $client->setScopes([Sheets::SPREADSHEETS]); $client->setAuthConfig(SERVICE_ACCOUNT_FILE); $client->setAccessType('offline');
return new Sheets($client);}SPREADSHEET_ID: ID của file Google Sheets (lấy từ URL Google Sheets).
SHEET_NAME: Tên sheet cần truy cập (VD: "licenses").
SERVICE_ACCOUNT_FILE: Đường dẫn tới file JSON bạn đã tải về.
🔹 Bước 7: Viết code đọc dữ liệu
require 'config.php';
$service = getGoogleSheetsService();$range = SHEET_NAME . "!A:F"; // Lấy dữ liệu từ cột A đến F$response = $service->spreadsheets_values->get(SPREADSHEET_ID, $range);$values = $response->getValues();
// Hiển thị dữ liệuif (empty($values)) { echo "Không có dữ liệu.";} else { foreach ($values as $row) { echo implode(" | ", $row) . "<br>"; }}🔹 Bước 8: Viết code ghi dữ liệu vào Google Sheets
require 'config.php';
$service = getGoogleSheetsService();$range = SHEET_NAME . "!A1"; // Vị trí cần ghi dữ liệu$values = [["ebb598df42ac...", "ChatGPT", "2026-05-25", "2025-03-06", "email@example.com", "Tuấn - Cty"]];
$body = new Google_Service_Sheets_ValueRange([ 'values' => $values]);$params = ['valueInputOption' => 'RAW'];
$service->spreadsheets_values->update(SPREADSHEET_ID, $range, $body, $params);echo "✅ Ghi dữ liệu thành công!";📌 6. Xóa Dữ Liệu trên Google Sheets
require 'config.php';
$service = getGoogleSheetsService();$range = SHEET_NAME . "!A2:F2"; // Xóa dữ liệu hàng 2
$clearRequest = new Google_Service_Sheets_ClearValuesRequest();$service->spreadsheets_values->clear(SPREADSHEET_ID, $range, $clearRequest);echo "✅ Xóa dữ liệu thành công!";📌 7. Xóa Hoàn Toàn Một Hàng
🎯 Tổng Kết
✅ Cấp quyền truy cập cho Service Account.
✅ Cài đặt thư viện
✅ Viết PHP để đọc, ghi và xóa dữ liệu trên Google Sheets.
require 'config.php';
$service = getGoogleSheetsService();$rowToDelete = 2; // Xóa hàng số 2
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ 'requests' => [ [ 'deleteDimension' => [ 'range' => [ 'sheetId' => SHEET_ID, // Thay bằng Sheet ID của bạn 'dimension' => 'ROWS', 'startIndex' => $rowToDelete - 1, // Google Sheets index bắt đầu từ 0 'endIndex' => $rowToDelete // Xóa 1 hàng ] ] ] ]]);
$service->spreadsheets->batchUpdate(SPREADSHEET_ID, $requestBody);echo "✅ Xóa hoàn toàn hàng số $rowToDelete thành công!";🎯 Tổng Kết
✅ Cấp quyền truy cập cho Service Account.
✅ Cài đặt thư viện
google/apiclient.✅ Viết PHP để đọc, ghi và xóa dữ liệu trên Google Sheets.
✅ Bật Google Sheets API và tạo Credentials.
0 Comments