WhatsApp From Google Apps Script: UrlFetchApp, a Sheet and Triggers
Send WhatsApp messages from Google Apps Script with UrlFetchApp and Meta’s Cloud API: token in Script Properties, templates from sheet rows, retries and quotas.

To send a WhatsApp message from Google Apps Script, call UrlFetchApp.fetch with method post on https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages, a JSON payload and an Authorization: Bearer header, with the token kept in Script Properties. No library or add-on is needed: Meta’s Cloud API is plain HTTPS and JSON, which Apps Script handles out of the box.
This guide writes the code: a send function, a template for each row of an orders sheet, retries for rate limits, a schedule, and Google’s quotas that decide how far it scales. It also explains why Apps Script is a poor place to receive WhatsApp webhooks. If you want contacts to sync between WhatsApp and a sheet without code, that’s a different job, covered in WhatsApp and Google Sheets integration.
Key takeaways
- Sending works well from Apps Script:
UrlFetchApp.fetchwithmuteHttpExceptions: trueso you can read Meta’s error codes. - Keep the access token in Script Properties, never in the code, and limit who can edit the project.
- To message people who haven’t written to you in the last 24 hours, send an approved template, and only to people who opted in.
- Google caps URL Fetch at 20,000 calls a day on a gmail.com account and 100,000 on Workspace, and each run at 6 minutes.
- Don’t use an Apps Script web app as Meta’s webhook: Google’s documented event object has no request headers, so you can’t check
X-Hub-Signature-256.
What Apps Script can and can’t do with the Cloud API
| Job | In Apps Script? | Why |
|---|---|---|
| Send a text inside the 24-hour window | Yes | One UrlFetchApp.fetch POST |
| Send a template to rows of a sheet | Yes | Loop over getValues() and write the result back to the row |
| Send on a schedule | Yes | A time-driven trigger, with timing that isn’t exact |
| Send when a Google Form is submitted | Yes | A form-submit installable trigger; see contact form to WhatsApp |
| Receive customer messages (Meta’s webhook) | Not safely | You can’t read the signature header, so you can’t prove a POST came from Meta |
| Send thousands of messages a day | With care | Daily URL Fetch quota and the 6-minute run limit |
So use Apps Script for what it’s good at: small, sheet-driven sends such as order updates, booking reminders or a daily summary to your own team. For two-way conversations, receive the webhook somewhere else; there’s more on that below.
Before you start: token and phone number ID in Script Properties
- A phone number ID from API Setup in your Meta app (it isn’t the phone number itself); see how to find your WhatsApp Business Account ID and phone number ID.
- A permanent system-user access token. The token in API Setup expires quickly, and an Apps Script job that runs on a schedule needs one that lasts; the Cloud API setup guide shows how.
- An approved template, for messages to people who haven’t written to you in the last 24 hours. While testing, send to your own phone from Meta’s test number.
Then store the two values outside your code, following Google’s steps:
- Open your Apps Script project (for a sheet, Extensions › Apps Script).
- Click Project Settings, the gear icon on the left.
- Under Script Properties, click Add script property.
- Add
WHATSAPP_TOKENwith your token as a plain string, then click Add script property again and addPHONE_NUMBER_IDwith the ID. - Click Save script properties.
A send function with UrlFetchApp
Paste this into Code.gs. Each row is one line of Apps Script.
| Line | Code.gs |
|---|---|
| 1 | const API_VERSION = 'v27.0'; |
| 2 | function sendWhatsApp(payload) { |
| 3 | const props = PropertiesService.getScriptProperties(); |
| 4 | const url = 'https://graph.facebook.com/' + API_VERSION + '/' + props.getProperty('PHONE_NUMBER_ID') + '/messages'; |
| 5 | const res = UrlFetchApp.fetch(url, { method: 'post', contentType: 'application/json', headers: { Authorization: 'Bearer ' + props.getProperty('WHATSAPP_TOKEN') }, payload: JSON.stringify(payload), muteHttpExceptions: true }); |
| 6 | const body = JSON.parse(res.getContentText()); |
| 7 | if (body.error) { const err = new Error('WhatsApp error ' + body.error.code + ': ' + body.error.message); err.code = body.error.code; throw err; } |
| 8 | return body.messages[0].id; |
| 9 | } |
contentType: 'application/json'matters: Google’s reference says UrlFetchApp sends form-encoded data by default, and Meta expects JSON.payload: JSON.stringify(payload)sends a JSON string. Passing the object itself would send it as form fields.muteHttpExceptions: truereturns Meta’s error reply instead of throwing a generic exception, so line 7 can readerror.code.- The returned ID (
wamid…) is what delivery statuses refer to. A success means Meta accepted the message, not that it was delivered.
To test it, add a function that sends yourself a text, pick it in the editor’s function menu and click Run. The first run asks you to authorise the script. Remember that a free-form text only arrives inside the 24-hour customer service window, so message your business number from your phone first:
| Line | Code.gs |
|---|---|
| 10 | function testText() { |
| 11 | const id = sendWhatsApp({ messaging_product: 'whatsapp', recipient_type: 'individual', to: '919800000000', type: 'text', text: { preview_url: false, body: 'Hi Priya, your table for 4 is booked for 8 pm tonight.' } }); |
| 12 | console.log('sent', id); |
| 13 | } |
Send a template to every row of a sheet
Here’s a sheet tab called Orders, with a header row and demo data:
| A: Phone | B: Name | C: Order | D: Opted in | E: Status | F: Message ID or error |
|---|---|---|---|---|---|
| 919800000000 | Priya | ORD-1042 | yes | ||
| 919800000001 | Arjun | ORD-1043 | no |
The template order_update has the body “Hi {{1}}, your order {{2}} has shipped.” This code builds the template message for a row and sends to every opted-in row that isn’t marked sent:
| Line | Code.gs |
|---|---|
| 14 | function orderTemplate(to, name, orderId) { |
| 15 | return { messaging_product: 'whatsapp', recipient_type: 'individual', to: String(to), type: 'template', template: { name: 'order_update', language: { code: 'en' }, components: [{ type: 'body', parameters: [{ type: 'text', text: String(name) }, { type: 'text', text: String(orderId) }] }] } }; |
| 16 | } |
| 17 | function sendOrderUpdates() { |
| 18 | const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Orders'); |
| 19 | const rows = sheet.getDataRange().getValues(); |
| 20 | for (let i = 1; i < rows.length; i++) { |
| 21 | const [phone, name, orderId, optedIn, status] = rows[i]; |
| 22 | if (optedIn !== 'yes' || status === 'sent') continue; |
| 23 | try { sheet.getRange(i + 1, 5, 1, 2).setValues([['sent', sendWithRetry(orderTemplate(phone, name, orderId))]]); } |
| 24 | catch (e) { sheet.getRange(i + 1, 5, 1, 2).setValues([['error', e.message]]); } |
| 25 | } |
| 26 | } |
- Row
i + 1:getValues()starts at 0 while sheet rows start at 1, so array row 1 is sheet row 2, just under the headers. - Re-runnable: rows marked
sentare skipped, so if a run stops halfway, running it again picks up where it left off, and rows markederrorare tried again. Fix or clear rows with permanent errors such as 131047 or 132001, or they use URL Fetch quota on every run. - Opt-in check: the script only sends to rows with
yesin column D. If you use a checkbox, test fortrueinstead. Templates must still be APPROVED, with a name and language code that match WhatsApp Manager exactly. - Named variables: for a template made with names instead of numbers, add
parameter_name: 'first_name'to each value.
Buttons and image headers are extra components; the JSON is in how to send a WhatsApp template message with the API.
Errors, retries and Apps Script quotas
Line 23 calls sendWithRetry, which waits and tries again only when Meta says to slow down. Utilities.sleep takes milliseconds, up to 300,000:
| Line | Code.gs |
|---|---|
| 27 | function sendWithRetry(payload) { |
| 28 | for (let attempt = 1; ; attempt++) { |
| 29 | try { return sendWhatsApp(payload); } |
| 30 | catch (e) { if (attempt === 4 || (e.code !== 130429 && e.code !== 131056)) throw e; Utilities.sleep(e.code === 131056 ? 6000 : 1000 * Math.pow(2, attempt - 1)); } |
| 31 | } |
| 32 | } |
| Code in column F | Meaning | Fix |
|---|---|---|
| 190 | Access token expired | Replace it with a permanent system-user token in Script Properties |
| 131047 | More than 24 hours since the customer last replied | Send a template, not a text |
| 132001 | Template doesn’t exist in that language or isn’t approved | Check the name, language code and status |
| 130429 | Cloud API throughput reached (80 messages a second by default) | Retried automatically; slow down if it keeps happening |
| 131056 | Too many messages to the same person in a short time | Retried automatically after 6 seconds; space out messages to that person |
Apps Script has its own limits, from Google’s quotas page. Google says they can change at any time without notice, so check the page before you plan a big send:
| Limit | gmail.com account | Google Workspace |
|---|---|---|
| URL Fetch calls | 20,000 a day | 100,000 a day |
| Script runtime | 6 minutes per run | 6 minutes per run |
| Trigger total runtime | 90 minutes a day | 6 hours a day |
| Triggers per user per script | 20 | 20 |
Each message is one URL Fetch call, plus retries. A long list may not finish within 6 minutes; because the script is re-runnable, a trigger can simply carry on with the next run. More on Meta’s side in WhatsApp API rate limits and WhatsApp API error codes.
Run it on a schedule
Open Triggers (the clock icon), click Add Trigger, choose sendOrderUpdates and a time-driven source, then Save. Or create it once from code:
| Line | Code.gs |
|---|---|
| 33 | function installTrigger() { ScriptApp.newTrigger('sendOrderUpdates').timeBased().everyHours(6).create(); } |
- Timing isn’t exact. Google may run a 9 am trigger any time between 9 and 10, so don’t promise customers a precise minute.
- Installable triggers run under the account of the person who created them, so that account’s quotas apply.
- Edits by scripts or the Sheets API don’t fire triggers. If another tool adds rows, use a time-driven trigger rather than an edit trigger.
Why not receive WhatsApp webhooks in Apps Script?
An Apps Script web app can accept a POST through doPost(e), so it’s tempting to paste its /exec URL into Meta’s webhook settings. Don’t. Meta signs every webhook with an X-Hub-Signature-256 header, an HMAC-SHA256 of the raw body made with your app secret, and you should reject any POST whose signature doesn’t match. The event object Google documents for doPost holds the query string, parameters and body, but no request headers, so your script can’t check the signature. Anyone who finds the URL could post fake “customer messages” into your sheet.
Better options for the receiving side:
- A small serverless function that checks the signature, such as a Supabase Edge Function, or a server in Node.js or Python. It can then write rows to your sheet if you need them there.
- A platform that receives Meta’s webhooks for you, so you only deal with the messages; see below.
How Meta’s webhooks work, with payloads and retries, is in WhatsApp Cloud API webhooks.
Apps Script with Automate AI, or no code at all
If the goal is simply contacts in a sheet, Automate AI’s Google Sheets integration keeps contacts in sync with a sheet on a schedule, both ways, and can add every new lead from a chatbot as a row with the columns you choose; see integrations. Template sends to a list are campaigns, with scheduling and delivery reports, and Automate AI receives Meta’s webhooks into a shared inbox.
If you still want your own Apps Script, it can call Automate AI’s REST API with the same UrlFetchApp.fetch pattern, using an API key instead of Meta’s token, to send messages and templates or manage contacts. The API and developer webhooks come with the AI + Automation Plan and Series 4; see pricing.
Frequently asked questions
Can Google Apps Script send WhatsApp messages?
Yes. Use UrlFetchApp.fetch to POST JSON to Meta’s Cloud API at https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with a Bearer token and contentType: 'application/json'.
Where should I keep the WhatsApp token in Apps Script?
In Script Properties (Project Settings › Script Properties), read with PropertiesService.getScriptProperties().getProperty(). Never in the code or a cell, and limit who can edit the project.
Why does UrlFetchApp throw an exception instead of showing Meta’s error?
By default it throws on a failure status. Add muteHttpExceptions: true and read error.code from the JSON reply.
How many WhatsApp messages can Apps Script send a day?
Google allows 20,000 URL Fetch calls a day on a gmail.com account and 100,000 on Workspace, and each run stops at 6 minutes. Meta’s own limits and your messaging limit still apply.
Can I receive WhatsApp messages in Apps Script?
Not safely. Google’s documented doPost event object has no request headers, so you can’t verify Meta’s X-Hub-Signature-256 signature. Receive webhooks in a function or server that can.
Do I need an add-on or library?
No. Meta’s Cloud API is plain HTTPS and JSON, and UrlFetchApp is built into Apps Script.
Sources
- Meta: Send messages
- Meta: Templates overview
- Meta: Create a webhook endpoint
- Meta: Error codes
- Google: Apps Script quotas
- Google: UrlFetchApp reference
- Google: Properties service
- Google: Web apps
WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.


