CRADמפתחים
עברית

Handle notifications and consent

Keep booking success independent of WhatsApp delivery, show truthful message states and let customers manage permission.

לפני שימוש חי — בדקו יכולות פרוסות, הרשאות ומוכנות של החיבור שלכם.

בדקו את היכולות הפרוסות, הרשאות המפתח ומוכנות העסק בסביבה שלכם. דוגמאות HTTP נלכדו בבדיקות מבודדות; הסימון local-unreleased שלהן אינו אומר שה־API אינו פועל, ואינו מאשר את החיבור שלכם. במסלול הלקוח מאמתים טלפון בתבנית WhatsApp שהעסק הגדיר; SMS אינו נתמך. רישום בידי אדמין מורשה הוא פעולה נפרדת ללא קוד.

Send order updates or your own OTP without bookings

Use a server-only CRAD_API_KEY with contacts:record and conversations:read/write/send. Booking permissions and a booking bot are not required. This messaging release is a controlled pilot: confirm granted scopes and connection readiness before use. The reference does not certify business activation or live delivery.

Record/link your customer, then pass receipt.businessCustomerId to open-contact. Use receipt.result.conversationId to read the thread. Take human control if needed, re-read the quoted ETag, and send with the original persisted operation UUID and If-Match. Record/link is an administrative action, not proof of phone ownership or messaging consent.

An approved Authentication COPY_CODE template accepts {template:{name,language,parameters:[code]}}. Obtain the actual name/language from the catalogue and agreed template; never assume one exists. Supply one 1–15 character ASCII alphanumeric code. CRAD puts the same value in the body and copy button. Your application generates, stores, expires and verifies codes and limits attempts; match any printed template expiry. This is separate from CRAD booking-session phone verification.

CRAD administrators can choose the external_messaging workspace purpose for Cloud API businesses. It keeps appointment bot/AI off and removes appointment setup. The controlled pilot permits explicitly granted messaging/contact-record, attachment-read, WhatsApp connection, managed-template and business-profile scopes; existing keys gain nothing automatically. Existing businesses keep their default purpose. The shop owns orders and support settings; a saved API key or number does not establish Meta readiness. The downloaded ZIP includes ORDER_CONFIRMATION_INTEGRATION.md for order/callback integration and MESSAGING_CONNECTIVITY_DEVELOPER_GUIDE.md for the management APIs; the files retain their original evidence provenance.

Confirm one current order from a verified button click

Use an approved Utility template whose catalogue quickReplyButtons has exactly two entries, ordered by index 0 and 1. For the Arabic confirmation flow the labels are تأكيد الطلب and استفسارات اخرى. Keep six body values separate: customer name, shop name, order reference, products, complete cash-on-delivery amount/currency and address. Meta must approve the real template; a shared template never shares customer data, sender identity or keys.

Send {template:{name,language,parameters:[...],quickReplyPayloads:[confirmToken,supportToken]}}. The two tokens must be distinct, unguessable and 1–128 characters drawn from ASCII letters/digits/underscore/hyphen. The substituted body must fit 1024 Unicode code points. These are CRAD bounds, not a claim about current Meta maxima. Plain and Authentication templates refuse the extra field. Preserve both values/order with the original send UUID and ETag; CRAD rechecks approved button metadata before dispatch.

Bind each action token in your own database to the business, intended recipient, order ID/revision, action and expiry. After verifying and durably storing a message.received webhook, match data.content.interactive_id to that token and the verified sender. Confirm the current awaiting-confirmation order atomically once. Free text, an order reference, the phone’s latest order and delivery/read statuses never confirm it. A customer can have multiple orders and click them in reverse order.

Persist and acknowledge duplicate, cancelled, expired or superseded business outcomes with 2xx; a business refusal must not cause transport retries. Optional content.reply_to_id can corroborate a reliably mapped original provider message, but an early valid click must not wait for asynchronous status correlation. Retained conversation GET/search also carries interactive_id and reply_to_id.

A support click reads your current supportPhone from your own authorized settings API and replies with that number; it does not confirm the order or start a call. Keep this number separate from the WhatsApp sender and CRAD’s internal contact. Missing/invalid settings require handling, never a guessed personal number. Freeze each reply body and UUID before sending, including when support settings later change. Check current human control and the live 24-hour window before plaintext replies; do not silently fall back to another template.

Receive signed message and delivery callbacks

First give CRAD the exact public HTTPS callback URL for this integration. The URL must be canonical, with a lowercase DNS hostname and no credentials, non-default port, IP literal, query, fragment or redirect. After approval through the signed-in CRAD owner setting or the existing CRAD review, register using PUT /v1/management/messaging-webhook with {callbackUrl,signingSecret,enabled:true} and a persisted UUID Idempotency-Key. The separate random secret is 32 bytes encoded as 64 lowercase hex characters. Read needs conversations:read; configuration and retry also need conversations:write. These endpoints reject Origin and If-Match.

Check GET messaging-webhook for supported, approvedCallbackUrl, callbackUrl, registered, enabled, pending and failed. Installed support, URL approval and active receipt are separate states. The registering key remains the delivery authority; revoked/expired keys or lost read permission stop dispatch. After key rotation, register with the new authorized key. Pause stops new capture and delivery but keeps unexpired backlog. It does not replay messages that arrived while disabled.

Verify the exact raw request body before JSON parsing. X-CRAD-Webhook-Signature is v1= followed by lowercase hex HMAC-SHA256(secret string, timestamp + "." + rawBody). The HMAC key is the literal 64-character string, not hex-decoded bytes. Use X-CRAD-Webhook-Timestamp as Unix seconds, a bounded tolerance such as five minutes, constant-time signature comparison and an event ID check against X-CRAD-Webhook-Id.

Store/deduplicate eventId durably before returning 2xx, including for valid duplicates. Process the stored event asynchronously. Delivery is at least once and can arrive out of order; an older delivered event must not regress read. Committed capture schedules an immediate internal dispatch wake. Durable storage survives wake failure; scheduled maintenance is fallback, with bounded continuation and fairness between integrations and incoming/status traffic. No measured latency SLA is asserted. Eight attempts form a retry round; exhausted or permanent failures remain inspectable.

Inspect GET messaging-webhook/deliveries?state=failed&limit=50. This is an oldest-first bounded list, not a cursor feed. After repairing the endpoint, POST messaging-webhook/deliveries/{eventId}/retry with {}, its own persisted Idempotency-Key and no If-Match. The subscription must be enabled and the event failed and unexpired. A new round gives at most eight further attempts for the same event ID/body, not another WhatsApp send. Source retention can expire payloads before receipt.

Read the callback envelope and preserve unknown identities

Both event types use {schemaVersion:1,eventId,type,subscriptionId,siteId,integrationId,occurredAt,data}. IDs are UUIDs; occurredAt and the data timestamps are ISO date-time strings. The downloadable OpenAPI callback definition contains the complete field constraints. These message callbacks are separate from the HALA data-sync wake-up and do not provide booking lifecycle notifications.

For message.received, data contains messageId, conversationId, providerMessageId, from:{phone,userId}, kind, text, content, providerTimestamp and receivedAt. It captures live inbound messages, not historical imports. text can be null; content is bounded retained metadata, not a raw provider payload or public media URL. Download attachments through the authenticated media route with conversations:media:read.

For message.status, data contains messageId, conversationId, operationId, providerMessageId, phoneNumberId, recipient:{phone,userId}, status and providerTimestamp. status is sent, delivered, read, played or failed. operationId, when present, is the original CRAD send Idempotency-Key. The three CRAD IDs may be null when the provider status arrived before a reliable mapping. Store such events as unlinked. If a later retained message resolves a previously attempted event, a new event ID carries the resolved identity; the earlier body is unchanged. A lost provider response can leave an event permanently unlinked.

For from/recipient, phone contains digits without a leading plus and may be null; userId may also be null, but at least one is present. Never use null CRAD IDs to guess which customer or send operation was intended.

Show a retained inbox in your own admin

Request explicit conversations:read for the whole business; provider selection does not narrow this access. Control/read commands and their recovery additionally require conversations:write. Sending and attachment downloads have separate permissions below. Keep the Management key on your backend. Start with availability: enabled:false requires CRAD inbox setup, not repeated API calls. Availability and reading do not activate a business or send messages.

List/search threads and open one by conversation ID or canonical customer ID. Messages are newest first; nextCursor loads older retained messages. Reading does not mark them read. The inbox is limited by retentionDays, not a full WhatsApp archive. A disconnected channel does not remove saved history. Separate botMode, serviceWindow and connection in your UI; an open window does not guarantee sending.

To mark observed messages read, pass the latest verified live inbound CRAD message ID actually displayed, with non-null liveReceivedAt. Outgoing messages and imported-only messages without verified live arrival are refused, and newer arrivals remain unread. This advances the shared CRAD read state only. Appointment context needs a separate current calendar grant; nextAppointment:null may mean withheld.

Opening a contact thread does not take over from the bot or open the 24-hour window. For a deliberate control change, read the current version and send it quoted in If-Match. human pauses this conversation’s bot; bot restores its control under global channel rules. Busy or unresolved-send guards remain in force. A stale CONTROL_CHANGED response requires refreshing and reviewing the new state.

Before each write save one Idempotency-Key UUID, exact body, path and any If-Match. After uncertainty check conversation-operations/{operationId}; this read repeats nothing. not_found does not cancel an in-flight request. Offer only an explicit exact retry. Keep the immutable receipt separate from current, which may have changed or been removed. Receipt recovery survives transcript retention and key rotation within the same authorized integration.

Reply through WhatsApp

Sending requires conversations:send plus conversations:read. It does not grant control changes or attachment downloads. Take human control deliberately using a key that also has conversations:write, then retain the current quoted control version. Existing keys gain no additional scopes.

Send exactly one text, CRAD upload handle or supported approved template. Text and files require the live 24-hour customer window; templates still follow connection, customer consent and marketing rules. Browse available templates before composing one. Unsupported formats are omitted; complete:false signals an incomplete provider listing.

Before sending, save one operation UUID, the exact body and original If-Match. After a lost response, check conversation-sends/{operationId}. Checking never sends. Only not_found permits an explicit retry with the same request; pending/unknown must never create a replacement send. accepted means provider acceptance, not delivered or read.

Offer a separate, explicit review action for an uncertain send. It acknowledges uncertainty and permits subsequent work under the existing guards; it does not resend, confirm delivery or change control. Recovery for the review itself uses conversation-operations. A later provider callback can still settle the original attempt.

Upload and display attachments

Upload with conversations:send plus read, a fresh saved operation UUID and multipart/form-data containing one file. Current human control, a ready connection and a live customer window are required. Let your HTTP library set the multipart boundary. Upload alone sends nothing. Keep the original bytes and metadata until resolved. JPEG/PNG: up to 5 MiB; supported audio, video and documents: up to 16 MiB.

Check conversation-uploads/{operationId} after a lost response. Only ready supplies a usable mediaId. The handle belongs to this integration, conversation and current account binding and expires after 24 hours. pending/unknown never triggers automatic re-upload or sending. The operator can explicitly start a new upload UUID after uncertainty, possibly leaving an unused provider object.

To display a retained attachment, call GET /v1/management/conversations/{conversationId}/messages/{messageId}/media with your server-held Bearer credential and both conversations:read and conversations:media:read. Use the internal CRAD conversationId and messageId UUIDs returned in the thread or message.received event, not providerMessageId or a provider media ID. Authorize your own application user before proxying the bytes, preserving Content-Type and no-store. Successful downloads are binary; errors are JSON. Content-Length describes the returned byte count. This endpoint returns no public or signed URL.

Incoming images and documents use kind:image and kind:document. Voice notes use kind:audio with content.voice:true; do not expect a separate voice message kind. Retained content may include mime_type, filename and caption when available. These optional fields can be missing; duration and size are not promised transcript fields. Use the download response MIME type and byte length rather than inventing metadata.

Downloads remain subject to supported MIME types, media size limits, transcript retention, provider availability and the current connection binding. Upload handles expire after 24 hours; this is not a guarantee that every retained incoming attachment is downloadable for 24 hours. Reading a thread or receiving a webhook does not archive the file or extend retention. If an attachment is no longer available, show that state rather than treating retained metadata as usable bytes.

Request a template from your own admin

Template requests ask CRAD staff to help prepare a template. They neither submit a template to Meta nor send a customer message. Display open as awaiting handling and done as handled by CRAD; never translate done as approved by Meta. Only CRAD platform staff complete these requests.

Use a server-side Management key with template-requests:read for the business request list and details. Creating and recovering a request additionally requires template-requests:write. No provider selection or calendar grant is required, and existing keys gain no permission. Check installed templateRequestsRead/templateRequestsWrite capabilities separately from the key’s scopes.

Save one operation UUID and the exact purpose, optional exampleText and selected languages before POST. The purpose is trimmed and limited to 300 Unicode characters; the optional example is trimmed and limited to 1,024, with blank text stored as null. Select one to three unique languages from he, ar and en. A first acceptance returns 201; an exact normalized replay returns 200. No If-Match is needed.

After a timeout, GET template-request-operations/{operationId}. This check creates nothing. not_found does not cancel a delayed request; keep the same UUID and input for an explicit retry. receipt preserves the accepted open request, while current can reflect later staff completion. A removed request returns current:null with request_not_found and retains its receipt. A different payload under the same UUID is refused with 409.

The list defaults to open requests, newest first. Use status=done or all as needed, and follow nextCursor until null. Results can change between pages: this is a current directory, not a stable snapshot or synchronization feed. Historical rows may contain empty or repeated languages; display them without treating the response as a new valid submission.

Save the booking result before checking delivery

A confirmed receipt establishes the appointment. WhatsApp disconnection, a paused sender or a message failure does not undo it. Show the booking details and a management reference even when a message cannot be sent. Pausing WhatsApp does not itself pause website intake; use bookingEnabled and authoritative booking responses for intake.

GET notifications uses current customer proof for the known booking. It reports preferences and messages for that booking, not a business-wide admin delivery feed. A read-only integration key does not provide customer notification authority.

Present the versioned appointment-update choice

The implemented booking notice version is website-transactional-whatsapp-v1. Read communicationNoticeVersion from current capabilities and submit that supported version with the customer’s explicit choice. This is optional operational appointment messaging, not marketing permission or a delivery promise.

The current CRAD booking screen uses the following label and explanation. Registration, imported contact data, phone proof and booking success do not independently provide messaging consent.

LanguageChoice labelExplanation
EnglishI would like appointment updates on WhatsApp when available.Optional. Delivery depends on the business connection. Save your booking details here.
עבריתאשמח לקבל עדכוני תור ב־WhatsApp כשהשירות זמין.לא חובה. השליחה תלויה בחיבור של העסק. כדאי לשמור כאן את פרטי התור.
العربيةأرغب بتلقي تحديثات الموعد عبر WhatsApp عند توفر الخدمة.اختياري. الإرسال يعتمد على اتصال النشاط. احفظ تفاصيل الموعد هنا.

Translate message state into a useful UI

Treat reason as diagnostic data, with a safe fallback for an unfamiliar value. The message status is authoritative; an empty array is not proof of delivery. This public contract has no manual resend endpoint.

StateMeaning for the customerApplication behavior
not_requestedUpdates were not requested for this message.Keep the booking details available; do not label the message failed.
scheduled / queuedThe message is scheduled or waiting to send.Show waiting, not sent or delivered.
unavailableSending prerequisites are not ready.Show that the booking remains saved. Examples include connection_unavailable, template_unavailable and policy_disabled.
acceptedThe messaging service accepted the request.Do not describe provider acceptance as delivery.
deliveredDelivery was reported.Show delivered; this does not establish that the customer read it.
failedSending or delivery failed, or prerequisite retries were exhausted.Keep booking success separate. Offer the business contact route, not automatic booking or message resubmission.
unknownA possible provider attempt has no certain outcome.Do not automatically resend. Later authoritative status may resolve it.
suppressedSending was stopped, for example by withdrawal or a superseded booking version.Do not resume it by replaying the booking.
expiredThe allowed sending window passed.Do not promise a delayed catch-up message.

Read each configured reminder separately

Configurable reminders require the new scheduler to be installed and explicitly enabled for the business. Until that transition, the existing website reminder remains two hours before the appointment, with its existing sending window. Documentation availability does not activate the scheduler.

The default remains one reminder two hours before the appointment. A super-admin can authorize up to three reminders per appointment; the business owner selects their lead times in CRAD settings, for example 24 hours, eight hours and one hour. Raising the allowance does not add messages automatically. Customers and integration booking requests cannot set that allowance or the business schedule.

Read every reminder entry in notifications. Configurable reminder entries add offsetMinutes and scheduledAt; scheduledAt represents the same instant as dueAt. Older projections may omit these fields. Keep confirmation, change and cancellation entries separate: they do not consume the reminder allowance. A zero reminder allowance does not itself disable those other notices or booking intake.

Changing the appointment to a genuinely new UTC start gives that start a separate reminder allowance, subject to the current policy, consent and eligibility. Returning to a previously used start preserves its attempted-message evidence. Template fallback or a transport retry does not create another logical reminder. An unknown attempt remains protected from automatic replay.

A lead time of one day means 24 elapsed hours, which may differ from the same local clock time on the previous day across daylight-saving changes. The reminder lead time is unrelated to WhatsApp’s customer-service messaging window. Use approved templates and server scheduling; do not build a second reminder sender in the website.

When WhatsApp is disconnected

A missing or unavailable connection can produce unavailable with connection_unavailable. Sending checks the current sender and consent again; a changed sender is not permission to route an older message through another number. There is no automatic SMS fallback.

When delivery processing is enabled, failures before a provider send may be retried with bounded backoff while the message remains eligible. Reconnection is not a promise of catch-up: a deadline, withdrawal, changed booking, sender change or exhausted retries can prevent dispatch. Ambiguous provider attempts are not automatically resent.

The legacy website scheduler sends the two-hour reminder within its ten-minute window. Creating or moving a booking after its target time does not create a late reminder. Configurable additional reminder times use their own bounded recovery window; that window recovers an already eligible message and does not authorize a new late reminder. Confirmation/change/cancellation messages retain their ten-minute sending window. Refresh message status rather than starting a local resend timer.

Change permission with the current preference version

Appointments remain saved after withdrawal. A message already accepted by the provider may still arrive. Consent changes stop eligible future sending; they do not recall an in-flight provider request.

  1. Read current preferences

    GET notifications and retain its strong preference ETag, for example "n1". This is separate from the appointment version.

    Retrieve notification status
  2. Choose the scope explicitly

    Use scope: booking for this appointment, or a separately confirmed all_whatsapp action for this phone at this business. Global withdrawal affects messages sent through CRAD, not messages sent separately from the business’s WhatsApp app.

  3. Persist and submit the change

    Save one UUID, the body and If-Match. Enabling requires the current noticeVersion. Re-enabling all_whatsapp additionally requires the displayed preferences.globalVersion as expectedGlobalVersion. A later booking preference does not silently remove a global withdrawal.

    Change booking or business-wide WhatsApp permission
  4. Resolve the returned current state

    On 412 VERSION_CONFLICT, read current preferences and require a fresh confirmation. On timeout/503, retry the exact saved command. Successful replay can return the original receipt alongside a later blocked current state; do not treat the old receipt as current permission.