Cấu hình tài khoản developer google
Kích hoạt Google Sheets API và Google Drive API trong list thư viện api của google
Tạo services account trong phần credentials
Quay lại trang quản lý credentials , chọn edit services account
Qua tab Keys -> add key -> create new key
Sẽ có bảng popup hiện lên, chọn json -> create
Ngay sau đó sẽ có 1 file json tự động được tải về máy , và hiện lên bảng popup này , cứ close bình thường
Đổi tên file json phía trên thành key.json rồi lưu vào folder nào đó trong project (mình lưu vào storage/app để sau này trỏ đường dẫn cho dễ)
Tạo 1 file excel trên drive , link sẽ có dạng: https://docs.google.com/spreadsheets/d/xxxxxxxxx/view (Đoạn màu đỏ là ID của file excel, sẽ được sử dụng trong phần code php)
Thay đổi quyền truy cập file excel thành public hoặc add quyền cho email bất kỳ , được phép chỉnh sửa (để có thể insert vào file). Add theo tài khoản email thì điền email của Services account tạo phía trên vào là đc.
Code phần php laravel
Cài đặt thư viện: composer require google/apiclient
Code php
$client = new \Google\Client();
$client->setApplicationName('Google Sheets API PHP');
$client->setScopes('https://www.googleapis.com/auth/spreadsheets');
$client->setAuthConfig(storage_path('app/key.json')); --- đường dẫn tới file json tải ở bước cấu hình $client->setAccessType('offline'); $client->setPrompt('select_account consent');
$service = new \Google\Service\Sheets($client);
$spreadsheetId = '1slnDI1QIWDFiwi09l2_EIwD-ACp1nr0jHFIpYnQhnlY'; ---- ID của file excel
$range = 'first!A2:F'; --- bôi đỏ là tên của sheet , phần phía sau là điều kiện giới hạn dữ liệu insert từ cột nào đến cột nào
$values = [['b1@gmail.com','a1','d1','c1','e1','1660053866']];
$body = new \Google_Service_Sheets_ValueRange(['values' => $values]); $params = ['valueInputOption' => 'RAW','insertDataOption' => 'INSERT_ROWS']; $result = $service->spreadsheets_values->append($spreadsheetId, $range,$body, $params); $response = $service->spreadsheets_values->get($spreadsheetId, $range);
Các tham số , hàm khác để thao tác với google sheet các bạn xem thêm trên document.
Bài viết demo trên laravel 9.0 , php 8.0