CRADالمطوّرون
العربية

Sync customers and bookings

Maintain permitted CRAD data in your backend with separate customer and booking streams, durable checkpoints and explicit sharing.

قبل الاستخدام الفعلي — افحص القدرات المنشورة والصلاحيات وجاهزية ربطك.

تحقّق من القدرات المنشورة وصلاحيات المفتاح وجاهزية النشاط في بيئتك. أمثلة HTTP مسجّلة من اختبارات معزولة؛ وصفها local-unreleased لا يعني أن API غير عامل ولا يُثبت جاهزية ربطك. في مسار العميل يُتحقق من الهاتف بقالب واتساب أعدّه النشاط؛ SMS غير مدعوم. التسجيل بواسطة مسؤول مخوّل عملية منفصلة دون رمز.

Choose what belongs in each database

CRAD owns canonical business contacts and appointments. Your website owns its accounts and private notes. Keep those local fields separate from the CRAD projection so a tombstone, permission change or replacement snapshot cannot erase them. An embedded booking screen does not require a second customer database.

The default projection covers this integration’s mappings and accepted booking lineages. A verified registration or accepted booking can establish a mapping. Existing canonical name/language is not silently overwritten by registration; explicit updates can change CRAD and propagate to other linked integrations.

NeedPublic operation and scopeBoundary
Customer replicationCustomer snapshot → customer changes → customer checkpoint; customer-changes:readIntegration-scoped mappings, including detach tombstones.
Business directory replicationManagement customer snapshot → changes → checkpoint; contacts:read and contacts:syncCanonical business contacts, including unmapped and blocked contacts; separately approved fields are optional.
Booking replicationBooking snapshot → booking changes → booking checkpoint; bookings:read:integrationAll dates for this integration’s accepted lineages, including later moves and cancellations.
Account booking historyMapped customer bookings; customers:read and bookings:read:integrationCurrent states in a maximum 31-day query range; this is not an incremental sync cursor.
Private notes and account authenticationYour own backendNever copy account credentials or local notes into CRAD request bodies or treat a public mapping ID as account authorization.

Record a contact from your existing admin

Use this path when an authorized staff member enters a contact in your website’s admin. Your backend authenticates that administrator and uses the same owner-issued API key with explicit management permissions with contacts:record. Keep it on the server. A public customer form must use the customer verification flow instead.

Send a stable externalCustomerId, E.164 phone, displayName and language. A new contact is saved in CRAD and linked to this integration. An unambiguous existing contact is linked without silently replacing its name, language or blocked state. Ambiguous phones, blocked contacts and conflicting account links are refused.

Save businessCustomerId as the canonical CRAD contact ID and mappingId as the integration customer ID. They are different identifiers. The integration customer APIs use mappingId as customerId, with their own integration credential and scopes. A newly created owner_reviewed mapping does not gain the customer-verified shared-field or cross-channel-history permissions.

Phone verification, public booking intake, bot state and the WhatsApp connection are not prerequisites for this administrative record command. Recording does not send an OTP, book an appointment or change consent. Existing verified mappings retain their assurance when unchanged.

  1. Check management access

    GET /v1/management using the server-held management bearer. Confirm the expected integration and contacts:record scope. A contact-only key may have no schedule resources. This read does not grant broader authority or prove message delivery.

    Check management access
  2. Persist the command

    Save the exact request body and an operation UUID before POST. Use that UUID as Idempotency-Key. Keep your local account and private notes separate from the CRAD projection.

    Record a business contact
  3. Store the accepted result

    Store the immutable receipt and both returned IDs. The current projection is a fresh authorized view; it may differ from the original receipt after later changes. Do not silently replay a changed name as a new recording command.

    Record a business contact
  4. Recover uncertainty

    Read the original contact operation, or retry the same body and key. If current is null, honor currentUnavailableReason. A not_found result does not prove an in-flight request cannot commit; retain the original command for reconciliation.

    Recover a contact operation

Manage canonical customers from your admin

Use a server-held Management key and authorize the signed-in administrator in your backend. contacts:read exposes the basic business directory, including contacts created by CRAD or the bot and contacts with no website account. This permission does not make every contact a user of your website. Existing keys do not gain the new permissions automatically.

Use businessCustomerId for these routes. List/filter customers with GET, search names through POST /customers/search, and look up an exact E.164 phone through POST /customers/lookup. Names and phone numbers belong in request bodies, not URL parameters. Lookup does not create or merge a contact. A directory cursor belongs to the original filters/order and expires after 30 minutes; this browsing list is not a synchronization snapshot.

Read the current customer and retain its quoted ETag, for example "c4". Basic PATCH accepts only displayName and language and requires contacts:write. The separate block command requires contacts:block and an explicit boolean. Both use If-Match and a persisted operation UUID. A 412 requires refetch and review; do not overwrite a newer edit automatically. Blocking does not cancel appointments or change messaging consent.

On a timeout, recover the original customer operation or retry its exact request. A not_found result is not proof that a pending request cannot still commit. A receipt establishes the accepted action; current is a fresh view and can be null after deletion or movement to another business. Keep field edits, contact recording and basic-edit operation ledgers distinct.

Phone correction has a separate command and permission described below. Appointment administration uses the separate Business calendar contract. Customer merging and archival/deletion are not supported here. Management access does not create customer phone proof, an authenticated website account or WhatsApp consent.

Filter customers and show accurate segment counts

Use POST /v1/management/customer-segments/query with contacts:read and explicitly approved contacts:segments:read. It covers all business contacts, including blocked customers. The additional permission reveals visit-derived membership and email-search matches. It does not return email values, appointment rows or private notes, and never grants permission to send messages.

Search, the selected languages and status form the base list; selected languages combine with OR. Segment criteria combine with AND. For filter-option badges, supply up to 32 distinct countQueries IDs; each proposal replaces the entire segments object while keeping the same base search/languages/status. total and language counts describe all contacts, including blocked contacts; base describes the unsegmented filtered list; matched describes the selected segment. Never use the returned page length as a total.

Search normalizes Unicode compatibility forms, case, combining marks and the supported Hebrew/Arabic spelling variants. A query containing letters requires every word to match the name or email, in any order; it is not a phone query. Numeric queries also match stored phone digits or the Israeli local-phone form. Email affects membership only and is never returned. Search accepts up to 200 Unicode characters.

Name sorting compares the first 128 Unicode characters of the lowercase saved name using server C collation, then customer UUID. This bounds pagination tokens even for legacy names with thousands of characters and can differ from browser locale sorting. joined lists newest signups first, then UUID. lastAppointment lists the latest appointment start first across every status, including future and cancelled appointments, with missing dates last; it uses the same name/UUID tie-break and is not the last completed visit.

Each page reports observedAt and the business timezone. Pagination is a live read, so concurrent edits can change later pages. Keep the query unchanged with nextCursor. An invalid, expired or rotated-credential cursor returns INVALID_CURSOR: start the query again. Complete counts are capped at 20,000 contacts; CUSTOMER_SEGMENT_LIMIT_EXCEEDED returns an error instead of misleading partial totals.

SegmentMeaning
visits: none / oneNo completed appointments / exactly one business calendar day with completed appointments. Several appointments on that day still count as one visit day. Contacts with no history match none.
visits: recentRegularAt least three completed-visit days in the current 120-day business-calendar window.
away: 3w / 1m / 2m / 3mAt least one completed visit, no current/upcoming appointment, and more than 21 / 30 / 60 / 90 business calendar days since the last completed visit.
visitedFrom + visitedToBoth dates are required, ordered and no later than business today. Match at least one completed visit in the inclusive business-date range.
providerIdAt least one non-cancelled appointment with that same-business provider. An inactive retained provider can still match; missing or foreign IDs are refused.
backToBack: once / repeatedBack-to-back non-cancelled appointments on at least one / two business days, with the next beginning within 30 minutes after the previous end.
lateRegularA recent regular with no current/upcoming appointment and more than 30 business days since the last completed visit.
noUpcomingNo appointment in progress (NOW) or future PENDING/CONFIRMED appointment.
recentMissed / newCustomersAt least one missed appointment in the current 90-day business-calendar window / joined within 30 elapsed days.
Retained lastVisit choiceswithin30 means at most 30 elapsed days since a completed visit; notSince60 / notSince90 mean at least 60 / 90. Missing history never matches.
Retained visits: regular / missed / overdueregular: at least five completed appointments; missed: any historical missed appointment. overdue: at least three visit days, no upcoming appointment, later than 1.5 times the average return gap and less than 180 elapsed days away.
Example query shape — use your own filters
{
  "search": "",
  "languages": [
    "ar"
  ],
  "status": "active",
  "segments": {
    "noUpcoming": true
  },
  "countQueries": [
    {
      "id": "away-one-month",
      "segments": {
        "noUpcoming": true,
        "away": "1m"
      }
    }
  ],
  "limit": 50
}

Correct the same customer’s phone number

Use contacts:read and separately owner-issued contacts:phone:write. Read the canonical customer, display the old and proposed number for review, and retain the quoted ETag. POST /v1/management/customers/{businessCustomerId}/phone-corrections accepts only newPhone in E.164 format, that If-Match value and a persisted Idempotency-Key UUID. Basic PATCH cannot change a phone.

A material correction keeps the canonical businessCustomerId, accepted appointments, notes and profile-level restrictions. It does not merge contacts, create a verified identity, move historical booking ownership or grant WhatsApp consent. Supplying the same canonical number is a no-op. Authorized directory synchronization publishes material corrections; keep website-owned notes and account identity separate from the CRAD projection.

Existing bot or inbound-chat identity, verified customer links, booking lineage, ambiguous or occupied phone numbers and phone-only messaging restrictions can require a separate reviewed process. Do not detach records or remove STOP preferences to bypass PHONE_IDENTITY_REVIEW_REQUIRED or another conflict. PHONE_SEND_IN_PROGRESS means a retained send attempt or pending notification must be reconciled before trying a new reviewed correction; a locally elapsed deadline is not evidence that nothing was sent.

After uncertainty, recover the original customer operation with its original UUID and current contacts:read plus contacts:phone:write authority. Retain the original body and preconditions for an exact retry. The receipt describes the accepted action; current is freshly authorized and may have changed or become null. OPERATION_CONFLICT can follow an already committed original request: recover that original operation before preparing anything new.

For a customer-driven change to a website integration mapping, use the separate verified phone-change workflow. Its fresh phone proof and historical ownership rules are different from this administrative correction.

Approve and edit business notes and fields separately

The owner selects which standard notes and eligible custom fields this Management integration may read or edit. These approvals are separate from the customer-verified Integration field-sharing policy. The credential also needs contacts:read and contacts:fields:read; writes additionally need contacts:fields:write and readwrite approval for every changed selector.

Read the fields endpoint for current definitions, permitted options, grantRevision and each field’s exists/value. Identify custom fields by fieldId; a reused textual key is not a replacement definition. Missing and explicit null differ. If a stored value is unavailable, repair it in CRAD before preparing a new comparison.

PATCH uses grantRevision and per-key expectedExists/expectedValue, with a stable operation UUID. Do not send If-Match or copy the entire field projection. All changes apply together. Resolve FIELD_CONFLICT by re-reading the current values, and SHARING_GRANT_CHANGED by re-reading current approval. Neither refusal permits a blind overwrite.

Field-operation recovery checks current scopes and current readwrite approval for the original selectors. Receipts identify accepted selectors without preserving old sensitive values. Removal of a grant or field definition can refuse recovery; retained data must not be shown merely because an old response once allowed it.

Synchronize the whole business directory

Local candidate correction, 16 October: Management customer, appointment, service and provider checkpoints may return unchanged:true for an identical already applied cursor/sequence under a new UUID. That response creates no stored receipt and does not reserve that UUID. Previously accepted UUIDs retain conflict/replay handling. Keep the original pending ACK; never substitute a new UUID after uncertainty. Accepted checkpoint receipts are retained at least 30 days and until their original cursor expires; booking-command receipts are separate. Verify the deployed contract before relying on this additive response.

Use the separate Management customer stream with contacts:read and contacts:sync. Keep its cursor, staging state and pending acknowledgement separate from Integration customer and booking streams. Optional contacts:fields:read adds only the fields currently approved by the owner. A capability flag alone grants no access.

Start a snapshot with an empty JSON object. It captures fixed membership IDs and a publication watermark, not historical field values. Pages hydrate currently permitted values; a newer edit may appear in the snapshot and repeat in later changes. Complete all snapshot pages before activating the staged projection or acknowledging its delta cursor. The maximum is 10,000 contacts, ten active snapshots and ten starts per integration/hour.

Read pages of up to 100 records under one backend worker lease. Persist each complete page and its nextCursor atomically. Changes contain ordered metadata signals and a current projection; current can be newer than signalVersion. Apply the returned current projection idempotently and preserve its opaque version for later edits. signalVersion is not the current resource version. A new projection epoch requires rebuilding permitted fields even when a customer version is unchanged.

Use the hydrated current projection for present state: null means remove the CRAD customer projection, while a non-null current is authoritative even if an older signal has type: removed. Snapshot rows instead carry their explicit removed marker. Preserve unrelated website accounts, private notes and fields. Hidden-only events may advance the cursor without a visible event. hasMore:false means caught up to that read, not that future native edits cannot arrive. Use bounded polling or an approved wake-up worker, retaining periodic reconciliation and backoff.

Snapshots expire after 30 minutes; delta history/cursors have a 30-day horizon and idle reads do not renew expiry. Changes to effective scopes, field grants or eligible definitions require a new projection epoch and bootstrap. Restrict revoked CRAD fields immediately; stage a new permitted projection while preserving website-owned data. Equivalent key rotation may resume the same permitted stream.

Persist the acknowledgement UUID and issued nextCursor with the durable page application. Retry that exact acknowledgement after uncertainty. An accepted old acknowledgement can be recovered after its cursor expires, but bootstrapRequired/currentProjectionEpoch can require a new snapshot; its receipt never advances a newer epoch. Reconcile 410 by bootstrapping, and stop on revoked authority.

Signed Management wake-ups are capability-gated; current availability is an explicitly approved HALA pilot with a fixed callback. Require capabilities.syncWakeups === true plus separate enabled subscription state. Missing/false is unavailable, and other integrations retain bounded polling. A callback schedules feed reads; it does not carry customer values, grant authority or replace ACK/reconciliation. The efficient integration guide and downloaded pilot reference give the exact restrictions.

Consume the Integration customer and booking streams

This section applies only to the Integration customer and booking streams linked here. The separate Management directory workflow above uses current-value hydration and projection epochs; do not apply the Integration customer-version filtering rule to its signalVersion.

The returned watermark describes the server position; it does not prove you applied every event while hasMore is true. An acknowledgement is your consumer’s report, not server verification of your database. Neither stream is an external webhook or an independent booking authority.

Every snapshot page must have the same watermark as that snapshot’s start, including its final page. Validate that invariant before applying the page. On mismatch, retain the old active projection, stop acknowledgement and discard only the incomplete staged snapshot before starting a fresh one; repeated mismatches need support review. After snapshot completion, changes pages have their own advancing watermark.

  1. Recover pending work first

    Use a durable backend store and a shared worker lease. If a page acknowledgement is pending, retry its saved UUID and exact cursor before reading the next page. Keep the customer and booking stream state independent.

    Acknowledge customer changesAcknowledge booking changes
  2. Start a snapshot

    POST an empty JSON object to the appropriate snapshot endpoint. Persist its issued cursor and starting watermark together with the new staging snapshot. A snapshot is a consistent current-state projection, not a reconstructed historical event journal.

    Start customer snapshotStart booking snapshot
  3. Stage complete pages

    Read pages of up to 100 records. Store each whole page and nextCursor atomically. Stage partial snapshots while keeping the old projection readable. Finish the snapshot before switching to its change cursor.

    Read customer changesRead booking changes
  4. Activate and acknowledge

    When the complete snapshot or changes page has been applied durably, persist its nextCursor and a pending acknowledgement UUID in that same transaction. POST that cursor with the saved Idempotency-Key. Do not acknowledge an initial or partial snapshot cursor, or a caller-invented watermark.

    Acknowledge customer changesAcknowledge booking changes
  5. Poll with bounded work

    Apply changes in integration sequence order and retain tombstones. For customers, ignore equal/older record versions. For bookings, process sequence even when booking versions match: an external-reference link can be a separate event at the same version. Bound pages, retries and elapsed time; use backoff and honor Retry-After.

    Read customer changesRead booking changes

Recover a gap without losing local data

ConditionMeaningConsumer action
Snapshot cursor: 30 minutes; changes cursor: 30 daysCursors are opaque, integration-bound and expiring. Idle customer polling does not extend the hard expiry.Keep cursors server-side and finish snapshots promptly.
410 CURSOR_EXPIREDThe cursor expired or its retained event prefix is unavailable.Start a new scoped snapshot. Stage it, then reconcile the old CRAD projection against the completed snapshot; preserve unrelated website accounts/notes.
410 on a pending checkpointAn exact accepted acknowledgement is recovered before expiry checks, after current authorization. A definitive 410 means this acknowledgement was not accepted.Bootstrap again. A timeout or 503 is different: retain and retry the pending acknowledgement.
409 SNAPSHOT_TOO_LARGEThe snapshot exceeds the supported 10,000-record bound.Stop automatic snapshot retries and request capacity review.
429 RATE_LIMITED or SNAPSHOT_LIMITA request or snapshot limit was reached.Honor Retry-After. Snapshot work is bounded to ten active snapshots and ten starts per integration/hour.
401/403, or 409 SYNC_CURSOR_NOT_ISSUED / SYNC_CHECKPOINT_STALEAuthority or checkpoint state needs repair.Retain pending state; stop for review instead of discarding the cursor or inventing a watermark.

Map accounts and edit customers explicitly

Use the integration customerId returned by CRAD, together with the backend-authorized externalCustomerId mapping. Never select a mapping solely because a browser submitted its ID or phone.

Name/language updates require the current strong customer ETag, for example "1", and a stable operation UUID. On 412 VERSION_CONFLICT or CUSTOMER_CHANGED, refetch and let the user resolve the newer state. Do not copy an entire GET response into PATCH.

Phone change is a separate operation with fresh proof for the new phone. It preserves prior appointment ownership and does not merge accounts. If proof expires during recovery, verify that same intended new phone again and replace only newSessionToken; retain the original operation UUID, customerId and If-Match. A different target phone is a different command. Detach removes the integration mapping and emits a tombstone; it does not delete profiles or appointments, and another booking does not silently reconnect it.

A null displayName with displayNameUnavailableReason means the source value could not be projected. Preserve the source and local account fields; do not echo that null as a deletion. owner_reviewed identity records historical owner approval, not customer phone authentication.

Treat additional sharing as a separate permission

Shared fields and all-channel history require an active customer_verified mapping in the same integration, current matching identity and separate owner approval. A supported capability flag or ordinary customer scope alone does not grant them. Internal notes and raw custom data are not exposed.

Read shared fields on demand. They are not copied into the customer change feed. Reconcile current grants before showing a cached projection, and remove or restrict revoked CRAD values in your store. CRAD can stop future access but cannot erase a copy already held by your website.

For shared-field writes, use grantRevision plus expectedExists/expectedValue for each changed key and a saved operation UUID. Missing and explicit JSON null differ. The GET projection ETag/hash is not a PATCH If-Match token. An unavailable stored value needs repair in CRAD before you can construct a new comparison.

All-channel history returns display-only historyId references and current states, up to 100 per page within a maximum 31-day query. Those IDs do not authorize booking reads, intents, changes or cancellations. There is no all-channel change feed, and this feature is not a full business calendar.

Shared-field refusalNext action
409 FIELD_CONFLICTRead the current field, show the conflict, and prepare a new comparison only after resolving any unknown earlier operation.
412 SHARING_GRANT_CHANGEDReload current grants and values; require a fresh review.
403 FIELD_ACCESS_DENIED / HISTORY_ACCESS_DENIEDStop access and reconcile cached projections with the current authorization.
422 invalid field or valueCorrect the request using current field definitions and allowed options.
Timeout or 503Retain the exact UUID/body and retry it. Replay rechecks current grants and does not return revoked historical values.