Dưới đây là hướng dẫn chi tiết cách thiết lập Google Apps Script để nhận dữ liệu từ form trên website và lưu vào Google Sheets.
function doPost(e) {
try {
// Lấy dữ liệu từ request
const data = JSON.parse(e.postData.contents);
// Mở Google Sheet hiện tại
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Sheet1"); // Thay đổi tên sheet nếu cần
// Lấy thời gian hiện tại theo múi giờ Việt Nam
const timestamp = Utilities.formatDate(new Date(), "GMT+7", "dd/MM/yyyy HH:mm:ss");
// Thêm dữ liệu vào sheet
sheet.appendRow([
data.phone,
timestamp,
"Mới"
]);
// Trả về kết quả thành công
return ContentService
.createTextOutput(JSON.stringify({ result: "success" }))
.setMimeType(ContentService.MimeType.JSON);
} catch (error) {
// Trả về lỗi nếu có
return ContentService
.createTextOutput(JSON.stringify({ result: "error", error: error.toString() }))
.setMimeType(ContentService.MimeType.JSON);
}
}
src/components/cta.astro
.const scriptURL = 'YOUR_GOOGLE_SCRIPT_URL';
.YOUR_GOOGLE_SCRIPT_URL
bằng URL bạn đã sao chép ở bước trước.Sau khi thiết lập, hãy thử gửi form trên website để đảm bảo dữ liệu được lưu vào Google Sheet. Nếu có lỗi, hãy kiểm tra console của trình duyệt để xem thông báo lỗi.