Webhook Google Sheets: Nhận Dữ Liệu Từ Form, Zalo OA, Facebook
Webhook Là Gì Và Tại Sao Dùng Google Apps Script?
Webhook là cơ chế một ứng dụng tự động gửi dữ liệu đến URL khác khi có sự kiện xảy ra. Google Apps Script cho phép tạo Web App (URL endpoint) để nhận webhook mà không cần server riêng — hoàn toàn miễn phí và không cần kiến thức backend phức tạp.
Tạo Webhook Endpoint Với Apps Script
// doPost: xử lý POST request (webhook)
function doPost(e) {
try {
const data = JSON.parse(e.postData.contents);
const sheet = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName('WebhookData');
// Thêm dữ liệu vào Google Sheets
sheet.appendRow([
new Date(), // Timestamp
data.source || '', // Nguồn (zalo/facebook/form)
data.name || '', // Tên khách hàng
data.phone || '', // Số điện thoại
data.email || '', // Email
data.message || '', // Nội dung
JSON.stringify(data) // Raw data
]);
// Trả về response thành công
return ContentService
.createTextOutput(JSON.stringify({ status: 'ok', message: 'Data received' }))
.setMimeType(ContentService.MimeType.JSON);
} catch (err) {
return ContentService
.createTextOutput(JSON.stringify({ status: 'error', message: err.toString() }))
.setMimeType(ContentService.MimeType.JSON);
}
}
// doGet: để test webhook bằng browser
function doGet(e) {
return ContentService
.createTextOutput('Webhook is running!')
.setMimeType(ContentService.MimeType.TEXT);
}
Deploy Webhook Trên Apps Script
- Vào Extensions → Apps Script
- Paste code trên vào editor
- Click Deploy → New deployment
- Type: Web app
- Execute as: Me
- Who has access: Anyone
- Copy URL webhook
Nhận Dữ Liệu Từ Zalo OA
// Xử lý payload từ Zalo OA webhook
function processZaloPayload(data) {
// Zalo gửi event khi user nhắn tin OA
if (data.event_name === 'user_send_text') {
const userId = data.sender.id;
const message = data.message.text;
const timestamp = new Date(data.timestamp);
return {
source: 'zalo_oa',
userId: userId,
message: message,
timestamp: timestamp
};
}
// Zalo Form submission
if (data.event_name === 'form_submit') {
return {
source: 'zalo_form',
name: data.info.name,
phone: data.info.phone,
message: JSON.stringify(data.info)
};
}
}
Nhận Lead Từ Facebook Lead Ads
// Facebook gửi leadgen webhook
function processFacebookLead(data) {
const entry = data.entry[0];
const changes = entry.changes[0];
if (changes.field === 'leadgen') {
const leadId = changes.value.leadgen_id;
const formId = changes.value.form_id;
// Fetch chi tiết lead từ Graph API
const accessToken = PropertiesService.getScriptProperties()
.getProperty('FB_ACCESS_TOKEN');
const leadData = JSON.parse(UrlFetchApp.fetch(
`https://graph.facebook.com/${leadId}?access_token=${accessToken}`
).getContentText());
// Parse field_data
const fields = {};
leadData.field_data.forEach(f => {
fields[f.name] = f.values[0];
});
return {
source: 'facebook_lead',
name: fields['full_name'] || fields['name'] || '',
phone: fields['phone_number'] || '',
email: fields['email'] || '',
message: JSON.stringify(fields)
};
}
}
Thông Báo Realtime Khi Có Lead Mới
function notifyNewLead(leadData) {
const salesTeamEmail = 'sales@company.com';
GmailApp.sendEmail(
salesTeamEmail,
`🔔 Lead mới từ ${leadData.source}: ${leadData.name}`,
`Tên: ${leadData.name}
Điện thoại: ${leadData.phone}
Email: ${leadData.email}
Nguồn: ${leadData.source}`
);
}
Câu Hỏi Thường Gặp (FAQ)
Webhook Apps Script có timeout không?
Có. Apps Script Web App timeout sau 6 phút cho tài khoản cá nhân, 30 phút cho Google Workspace. Đủ dùng cho hầu hết webhook use case vì mỗi request chỉ mất vài giây.
Có thể nhận nhiều webhook cùng lúc không?
Apps Script xử lý đồng thời được, nhưng có giới hạn concurrent executions (30 cho tài khoản thường). Nếu cần xử lý lượng lớn, nên dùng trigger để xử lý hàng đợi thay vì xử lý realtime.
Dữ liệu webhook có bảo mật không?
URL webhook là public, bất kỳ ai có URL đều có thể gửi data. Để bảo mật, thêm secret token validation: kiểm tra header Authorization hoặc signature trước khi xử lý dữ liệu.
Chia sẻ bài viết:
Tuân Hoang
Đội ngũ SheetStore
Bạn thấy bài viết hữu ích?
Đăng ký nhận thông báo khi có bài viết mới.