Load the authenticated clinic settings
Resolve the clinic from the authenticated staff session on your server before looking up a patient or loading its API key. Use https://api.crad.ai/v1/management for the relative paths in this guide. Send the clinic's existing CRAD_API_KEY as a backend-only Bearer credential. Existing booking code can keep its current CRAD URL.
Retain the existing calendar permissions and current owner-approved appointment grant: appointments:read and appointments:status for approval, and appointments:create for staff creation. The document and sending examples need template-requests:read, template-requests:write, campaigns:read and campaigns:send, with resources.campaigns.wholeBusiness:true for the contacts audience. These are separately granted permissions.
For a key with appointments:read, GET /v1/management preserves the calendar scope vocabulary and omits whatsapp-templates:read, whatsapp-templates:write, whatsapp-profile:read and whatsapp-profile:write. Discover those permissions through GET /v1/management/messaging-capabilities and its feature granted fields. installed, providerSupported, granted and ready answer different questions; ready:null is unknown. The document example below uses staff template requests and campaigns, so it does not require direct template/profile editing.
| Source | Values to use |
|---|---|
| Clinic server settings | Its existing API key, public display name, calendar time zone and HTTPS patient portal sign-in URL. Keep credentials on the server. |
| This clinic’s campaign-templates catalogue | Actual template name, exact approved language code, status:APPROVED, supported:true, and body parameter count/order. Configure the mapping per clinic. |
| Saved booking or document | The patient’s CRAD profile UUID in this clinic, appointment/document ID, public service label, canonical appointment time and the applicable messaging permission. |
Approve an existing patient request
Read the current approval-required PENDING appointment and its allowedActions. Submit the status action with that appointment's current quoted ETag and a saved approval UUID. Do not use a list replica's stale version for the final action.
CRAD queues the customer confirmation for this approval transition, subject to booking consent, opt-outs and current sender/template checks. End the website approval handler after displaying the returned result. Never call the campaign helper from a status change, operation replay or delayed-delivery handler. An accepted approval does not prove message delivery.
POST /appointments/{appointmentId}/actions
Authorization: Bearer <clinic CRAD_API_KEY>
If-Match: <current appointment ETag, including quotes>
Idempotency-Key: <saved UUID for this approval>
Content-Type: application/json
{"action":"status","status":"CONFIRMED"} Create a staff appointment and send its confirmation
Keep the existing staff booking flow, using POST appointments with bookingIntent:appointment or its default. For a Book and send confirmation action, show the patient and rendered message before staff confirm. Use the authenticated creation receipt for the guard below; PENDING is not a final confirmation.
enqueueOnce is your application outbox helper, not a CRAD endpoint. Atomically insert or recover one event keyed by clinic, purpose and appointment. Creation retries and receipt replay must recover the same event. They must not start a second send. Keep a saved appointment even if its notification fails.
For a clinic using crad_website_confirmation_v1 with four approved body fields, use the order shown below. Another template can have another order. Format the canonical receipt.startAt in clinic.timeZone; do not slice a UTC ISO string. Verify that the saved patient, service and time still match the reviewed preview. Use a generic public service label and the appropriate messaging permission. Management statuses are uppercase; Customer API statuses are lowercase.
const { receipt } = createResult;
if (receipt.action === "create" && receipt.status === "CONFIRMED" &&
receipt.notification?.state === "not_requested") {
// Application helper: atomically insert or recover the same unique event.
await enqueueOnce(clinic.id, "staff-booking-confirmation", receipt.appointmentId);
}
// For a clinic using the approved four-field confirmation template:
const parameters = [clinic.displayName, publicServiceLabel, localDate, localTime];
// Derive localDate/localTime from receipt.startAt in clinic.timeZone. Notify one patient that a document is ready
First verify that the document is ready, belongs to this patient at this clinic, and that the patient has agreed to document-ready notices. Appointment messaging consent is not blanket document permission. Honor current opt-outs.
Use an existing approved supported document-ready template in the patient's language, or request one for this clinic. The Arabic request below asks CRAD staff for assistance; it neither submits to Meta nor sends a message. Track receipt.request.requestId with GET template-requests/{requestId}. done means staff handling is complete, not Meta approval. Recover a lost submission with template-request-operations/{originalUuid}.
Before sending, read campaign-templates and use the actual APPROVED, supported:true variant and exact language code. Pass [clinic.portalSignInUrl] as one BODY text parameter for this example. This is a text link, not a document attachment or a dynamic URL button. The portal must authenticate the patient and authorize access to their document; the messaging API does not provide that protection. Keep diagnoses, patient identifiers and sign-in/access tokens out of the message and URL.
POST /template-requests
Authorization: Bearer <clinic CRAD_API_KEY>
Idempotency-Key: <saved UUID for this template request>
Content-Type: application/json
{
"purpose": "Let a patient know that a document is ready in the clinic portal",
"languages": ["ar"],
"exampleText": "مستندك جاهز. رابط بوابة العيادة: {{1}}. سجّل الدخول إلى حسابك للاطلاع على المستند."
} Preview, confirm and recover the same send
Use the clinic's authenticated backend JSON client. In this example post returns parsed data and the raw response ETag. Resolve profileId within the same clinic; approvedName and approvedLanguage come from its catalogue. parameters is the reviewed booking array or [clinic.portalSignInUrl]. matchLanguage:false sends the explicitly chosen approved language.
This contacts draft selects exactly one profile. Require one matching recipient and no skipped recipients, then show the rendered message before staff confirm. The preview reserves no sending capacity. Submit only after the booking/document gate is satisfied and the saved details match; changed details or a changed preview require another review.
| Situation | Required handling |
|---|---|
| Concurrent clicks or reloads | Use one durable intent and UUID for the same action. An initial staff-booking confirmation is unique on (clinic ID, purpose, appointment ID); a document send is unique on (clinic ID, purpose, document ID, sendIntentId). Persist the exact draft and quoted preview ETag. Creation and template requests use separate UUIDs. |
| Deliberate document resend | After the previous outcome is known, staff may explicitly Send again. Review the saved report version and recipient, then create a new sendIntentId and UUID. sendIntentId is your outbox identifier, not an API field. This is a new action, not a retry. Queued, timeout, not_found or unknown are not reasons to create a new intent. |
| Timeout, not_found or unknown | Read campaign-operations/{savedSendUuid}. not_found can race an in-flight request; unknown requires review. Do not create a new UUID or resend automatically. Any safe exact retry uses the original body, UUID and If-Match. |
| Suppression or stale preview | Show that the notice was not sent and retain the saved booking/document. Refresh and review before a new action; do not recreate the appointment to retry its notice. |
| Parameters and message status | Each trimmed nonblank parameter, including the URL, is limited to 200 UTF-16 units; the filled body to 1,024. A recipient state of sent means provider acceptance. Show delivered/read only with corresponding evidence. |
// post() is your authenticated backend client; it returns { data, etag }.
// profileId is the intended patient CRAD profile UUID for this clinic.
// Use the approved template name, language and parameter order from this clinic’s catalogue.
const draft = {
providerId: null,
audience: { kind: "contacts" },
recipientProfileIds: [profileId],
template: { name: approvedName, language: approvedLanguage },
parameters, // Booking values, or [clinic.portalSignInUrl] for the document.
matchLanguage: false
};
const preview = await post("/campaign-previews", draft);
const { recipientCount, recipients, skipped } = preview.data;
if (recipientCount !== 1 || recipients.length !== 1 || skipped.length !== 0 ||
recipients[0].profileId.toLowerCase() !== profileId.toLowerCase() ||
!/^"cp[0-9a-f]{64}"$/.test(preview.etag ?? "")) {
throw new Error("Review the intended recipient and message");
}
// Display the recipient and rendered message; await staff confirmation.
// Persist this exact draft, quoted ETag and savedSendUuid in the unique event.
// Submit after the saved booking/document is ready and still matches the preview.
const send = await post("/campaigns", { draft, confirm: true }, {
"If-Match": preview.etag,
"Idempotency-Key": savedSendUuid
});
// Track send.data.receipt.campaignId with GET /campaigns/{campaignId}/recipients.