Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 6 min read

Building a secure incoming webhook in Zoho Books

Two different things in Zoho Books often get confused: Direction What it is Where it lives Trigger Incoming Someone outside POSTs data to Books Settings β†’ Developer & Data β†’ Incoming Webhooks Their request Outg

Two different things in Zoho Books often get confused:

Direction What it is Where it lives Trigger
Incoming Someone outside POSTs data to Books Settings β†’ Developer & Data β†’ Incoming Webhooks Their request
Outgoing Books sends data to someone outside Settings β†’ Automation β†’ Workflow Rules + Custom Function A record changing

This post covers incoming: receiving data from another system into Books.

Setup

  1. Settings β†’ Connections (under Developer & Data). Create the connection first, because the script needs it to call the Books API back.
    • Service: Zoho OAuth
    • Link name: lowercase, no spaces. This exact string goes in the script.
    • Scopes: only what the script touches.
  2. Settings β†’ Developer & Data β†’ Incoming Webhooks β†’ New
  3. Name it, describe it, paste the Deluge.
  4. Save. Books returns two URLs: an OAuth URL and a ZAPI key URL.

Which URL

Books gives you two. Which one you hand out depends on who is calling.

ZAPI key URL

For anyone outside your Zoho account. The key is in the URL, so the URL is the credential. Never email it, never commit it, and add a second check inside the script.

This is the right choice for third-party senders, who have no business holding credentials in your org.

OAuth URL

For callers inside Zoho that you control. Most often that is another of your own orgs, or another Zoho service.

The caller authenticates with a Zoho OAuth token instead of a key in a URL. In Deluge that costs nothing extra. The sending org creates a Zoho OAuth connection authorised as a user who has access to the receiving org, and the push just names it:

resp = invokeurl
[
    url :"<<OAUTH WEBHOOK URL>>"
    type :POST
    parameters:payload.toString()
    connection:"<<SENDING ORG CONNECTION NAME>>"
];

What you get for it:

  • No shared secret to store, rotate or leak. The token is the identity.
  • Revoking access means revoking the connection, not editing a custom field.
  • Nothing sensitive in the URL, so it survives being pasted into a ticket.

What it costs:

  • The caller needs a Zoho login with access to your org. Fine for your own orgs, a non-starter for third parties.
  • Check which scope Books expects for the webhook and set the connection to match before you wire it up.

Rule of thumb: OAuth inside your own Zoho estate, ZAPI key for everyone else.

What the script receives

Variable Contents
body The request body. body.toMap() to parse JSON.
headers Request headers as a map.

Header names are not matched literally. headers.get("X-My-Header") returns null. Loop over the keys and compare in lowercase.

sentSecret = "";
if(headers != null)
{
    for each hk in headers.keys()
    {
        if(hk.toString().toLowerCase() == "x-webhook-secret")
        {
            sentSecret = headers.get(hk).toString();
        }
    }
}

Authenticating the sender

If you handed out the OAuth URL, the token already identifies the caller and you can skip this section.

For the ZAPI key URL, the URL is not authentication. Have the sender send a shared secret in a header, and check it before you write anything.

Where the secret lives depends on how many senders you have.

One sender: an org custom field

For a single trusted system. Most often that's your own second Zoho org, Books talking to Books across orgs.

Add an org-level custom field labelled webhook-secret, then read it off the organization map:

storedSecret = "";
for each cf in ifnull(organization.get("custom_fields"),List())
{
    if(ifnull(cf.get("label"),"").toString().trim().equalsIgnoreCase("webhook-secret"))
    {
        storedSecret = ifnull(cf.get("value"),"").toString().trim();
    }
}

Match on label. The same values also appear as custom_field_hash with positional keys (cf_1, cf_2…), and those shift when someone reorders the fields.

Books has no org variables. That's a Zoho CRM feature (zoho.crm.getOrgVariable), and an org custom field is the Books equivalent.

If organization isn't in scope where your script runs, GET /books/v3/organizations/{organization_id} returns the same custom_fields array.

For Zoho-to-Zoho, do it on both sides: each org keeps the shared value in its own custom field, and neither script has a credential in it.

It is one secret for everyone, though. Rotating it breaks every sender at once, and anyone who can open org settings can read it. Fine for your own org, not for third parties.

Several senders: a field on the contact

For unrelated third parties. Put a Webhook Secret custom field on each sender's contact and look it up by the email in their payload:

storedSecret = "";
lookup = invokeurl
[
    url :"https://www.zohoapis.com/books/v3/contacts?organization_id=" + orgId + "&email=" + encodeUrl(senderEmail) + "&contact_type=vendor"
    type :GET
    connection:"<<YOUR CONNECTION LINK NAME>>"
];
contacts = lookup.get("contacts");
if(contacts != null && contacts.size() > 0)
{
    detail = invokeurl
    [
        url :"https://www.zohoapis.com/books/v3/contacts/" + contacts.get(0).get("contact_id") + "?organization_id=" + orgId
        type :GET
        connection:"<<YOUR CONNECTION LINK NAME>>"
    ];
    for each cf in ifnull(detail.get("contact").get("custom_fields"),List())
    {
        if(ifnull(cf.get("api_name"),"").toString() == "cf_webhook_secret")
        {
            storedSecret = ifnull(cf.get("value"),"").toString();
        }
    }
}

Onboarding a sender is then: create the contact, paste a secret. The script never changes, and you rotate one sender without touching the rest. Costs two API calls per request.

Either way

if(storedSecret == "" || storedSecret != sentSecret)
{
    result.put("status","unauthorised");
    result.put("message","Sender not recognised or secret invalid.");
    proceed = false;
}

Don't say which was wrong. Separating "unknown sender" from "bad secret" lets someone probe for valid addresses.

Generating a secret

32 bytes of cryptographic randomness, hex-encoded. That gives you 64 characters.

$b = New-Object byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($b)
-join ($b | ForEach-Object { $_.ToString("x2") })
openssl rand -hex 32
  • One secret per sender. Shared secrets can't be rotated independently.
  • Generate it on the receiving side. You're the one enforcing it.
  • Never use an identifier as a secret. Not a record ID, not an account number. Those travel in payloads and exports, and can't be rotated without breaking something else.
  • Send it separately from the endpoint URL.
  • Rotate by pasting a new value into the field. Nothing else changes.

Shape of a receiver

Validate, dedupe, write, reply. Nothing clever.

orgId  = "<<YOUR BOOKS ORG ID>>";
result = Map();
proceed = true;
payload = body.toMap();

// 1. authenticate (above)
// 2. validate required fields, collect what is missing
// 3. find an existing record on a stable external key -> PUT, else POST
// 4. return a readable status

return result;

Return a status plus a plain-English message. The HTTP code is always 200, so the body is the only signal the sender gets. Useful status values: created, updated, rejected (with missing_fields), unauthorised, error.

Log real errors with info, and give the sender a generic message. Internal field names and stack traces aren't theirs to see.

What the sender needs to know

  • Your ZAPI endpoint URL and their secret, both sent privately.
  • A stable ID from their side. The same value on a revision, a new value on a genuinely new record. That ID decides create versus update on your side.
  • Resends replace all line items. Always send the complete set.
  • Read the status in the response body, not the HTTP code.

If the sender also runs Zoho Books

They don't need anything bespoke: a workflow rule on the relevant module, with a custom function that POSTs to your endpoint.

endpoint = "<<YOUR ZAPI URL>>";
secret   = "<<THEIR SECRET>>";

payload = Map();
// ...fields from the record the workflow passes in

h = Map();
h.put("content-type","application/json");
h.put("X-Webhook-Secret",secret);

try
{
    resp = invokeurl
    [
        url :endpoint
        type :POST
        headers:h
        parameters:payload.toString()
    ];
    info "Response: " + resp;
}
catch (e)
{
    info "Push failed: " + e;
}

Testing

Have the sender fire one record while you watch the list in Books. Confirm the record appears, then have them edit and resend the same record. It must update, not duplicate. That one round trip proves the whole contract.

Checklist

  • [ ] Connection created, scopes correct, authorised
  • [ ] Secret field on the sender's contact
  • [ ] Script authenticates before writing anything
  • [ ] Validation rejects with a list of what is missing
  • [ ] Dedupe on a stable external key so retries update rather than duplicate
  • [ ] Tested: valid, bad secret, missing fields, resend
πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.