Integrate Awin with EMRG Booking and Webhooks
Connect the standard EMRG booking widget or Partner Booking API to Awin through a clinic-owned adapter, with event mappings, attribution, webhooks and a launch checklist.
Integrate Awin with EMRG Booking and Webhooks
You can integrate Awin while keeping the standard EMRG booking widget on your website. Your team adds a widget callback and a backend adapter that connects EMRG events to your Awin program. You do not need to rebuild booking or switch to Partner Booking API v1.
This guide is for clinic developers and integration partners. It also covers custom booking experiences built with the Partner Booking API.
What EMRG provides and what you build
| EMRG provides | Your team owns |
|---|---|
Seven browser milestones through onBookingEvent | Host consent, Awin MasterTag and click capture |
| A flow ID and a server-side patient link | Attribution storage and first/last-click rules |
| Appointment outcome and paid-order webhooks | Signature verification, durable ingestion and Awin delivery |
| Economic-clinic ownership, voucher codes and prior paid-order count | Advertiser selection, commission groups, payout rates, voucher mappings and reconciliation |
The data flow is:
Your website + EMRG widget ── browser milestones ──┐ ▼ EMRG backend ── signed webhooks ──> Your integration backend ──> Awin
A callback alone does not complete the integration. Your backend must store attribution, process webhooks, retry failed Awin submissions and prevent duplicate conversions.
Before you start
- Confirm your EMRG environment has the booking callback,
booking.patient_linkedandorder.paidfeatures deployed. If Paid-order events is missing from your webhook settings, contact EMRG before proceeding. - Identify the clinic brand that owns the booking relationship and sale. For a referred booking, this can differ from the treating provider clinic.
- Prepare a publicly reachable HTTPS receiver and a durable queue or database for incoming events and outgoing Awin jobs.
- Obtain your Awin advertiser configuration and account access. Agree on commission groups, payout rates, attribution window, currency and the validation process with your Awin contact.
- Keep Awin credentials and EMRG webhook signing secrets on your server.
1. Capture attribution on your website
Capture the visitor's Awin click and click time on your host, subject to your consent policy. Preserve attribution through redirects. Associate it with the visitor's own session and later with (clinicId, bookingFlowId) when the widget callback arrives. The flow ID is an opaque UUID, not the Awin click itself.
Install the advertiser's MasterTag on eligible host pages. Awin excludes pages displaying or processing payment or personal information; do not inject its scripts into EMRG's patient/payment iframe. Preserve awc when redirecting visitors.
For server-readable click cookies, Awin's direct S2S guidance specifies HTTP-response cookies with HttpOnly and Secure flags. Your receiver reads that cookie; widget JavaScript cannot read an HttpOnly cookie.
Marketing email and SMS preferences in EMRG are not a substitute for your host's advertising consent. Store the applicable consent context with attribution.
2. Add the widget callback
Add onBookingEvent to the configuration in your existing widget installation. Keep your other configuration fields and initialize the widget once, after its script loads. Replace the placeholder clinic ID below with your numeric clinic ID.
const config = { clinicId: YOUR_CLINIC_ID, async onBookingEvent(event) { // Apply your website's consent policy before sending. // This endpoint belongs to YOUR backend, not EMRG or Awin. const response = await fetch('/integrations/emrg/booking-events', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(event), keepalive: true, }); if (!response.ok) throw new Error('Booking event was not accepted'); }, }; // Run inside your existing widget script's onload handler: window.emrgWidget.init(config);
The callback receives a frozen payload like this:
{ "schemaVersion": 1, "eventId": "22222222-2222-4222-8222-222222222222:email_verified", "eventName": "email_verified", "clinicId": 101, "bookingFlowId": "22222222-2222-4222-8222-222222222222", "occurredAt": "2026-11-03T16:00:00.000Z" }
These browser fields use camelCase. EMRG server webhook fields use snake_case.
Each milestone fires at most once per widget opening. Reopening creates a fresh flow. Resends, repeated selections and back navigation do not repeat a milestone within that flow. A callback configured for one clinic is not inherited when launching another clinic.
The callback contains no patient IDs, contact details, service names or appointment times. EMRG isolates callback failures from booking and does not retry browser events. The example shows transport only: implement consent gating, buffering, retries and deduplication on your side. Validate the host session, allowed origin, event shape and clinic at your receiver; browser events are untrusted signals, never proof of a paid sale. Resolve the advertiser from your server configuration, not a browser-supplied value.
3. Enable signed Partner Webhooks
In Clinic Management → Settings → Partner Webhook, select the correct clinic, configure your receiver and enable Paid-order events. That opt-in enables both order.paid and booking.patient_linked. Use the Partner Webhooks guide for setup, raw-body signature verification and delivery-log replay.
The destination must be your receiver, not an Awin endpoint. Verify the signature, persist the event durably, then acknowledge with 2xx. Forward conversions to Awin asynchronously through a separate queue. EMRG retries delivery, and your receiver must deduplicate event_id.
Capture starts prospectively. Payments completed while disabled are not backfilled; re-enabling resets the paid-order capture floor. Earlier identity links are not backfilled either. Terminal deliveries already in the log can be replayed with their original IDs and payloads. Delivery order is not guaranteed, so retain unmatched events while waiting for correlation.
4. Connect the flow to the patient
For the standard widget, EMRG forwards the flow ID during verification, patient creation and appointment creation. With the opt-in enabled, your receiver gets this minimal link after an existing patient verifies, or after a new verified patient record is created:
{ "schema_version": 1, "event_id": "66666666-6666-4666-8666-666666666666", "event": "booking.patient_linked", "occurred_at": "2026-11-03T16:00:00Z", "clinic_id": 101, "data": { "patient_id": "55555555-5555-4555-8555-555555555555", "booking_flow_id": "22222222-2222-4222-8222-222222222222" } }
Store (clinic_id, booking_flow_id) -> patient_id alongside your host attribution. EMRG validates the selected clinic's booking relationship and sends the link only to that clinic. It does not fan out to other brands sharing the provider.
An existing patient can verify, abandon booking and purchase later; you already have the link. A new visitor who leaves before their first patient record exists cannot yet be linked to an EMRG patient. Do not reuse a flow after switching identities.
Appointment webhooks also include data.booking_flow_id and data.economic_clinic_id; patient.id provides a fallback mapping at booking. Only the economic clinic's copy contains the flow; other entitled CRM recipients receive null. Historical or staff-created bookings can have no flow.
Maintain attribution history rather than blindly overwriting the latest click when a delayed event arrives. Select an eligible click at conversion time using your agreed policy and window. Do not infer that every purchase belongs to the most recent appointment or referral. A flow ID is correlation, not authorization or commission entitlement.
If you use Partner Booking API v1
Your custom frontend emits its own milestones. Your backend maps its flow to the patientId returned by connection-scoped patient creation/reconciliation, before an appointment is required. For a previously established patient association, use your stored mapping; do not claim another connection's patient by matching demographics.
Supply your own UUID bookingFlowId when creating the appointment; an analytics session is not required for this correlation. The same appointment and paid-order webhooks then apply. Partner patient creation does not verify email—emit an email-verified milestone only when your own verification succeeds. The standard widget performs that verification itself.
5. Map events to your Awin program
This is an example eleven-group mapping. Confirm the actual group codes in your advertiser account; EMRG does not create them or set commission rates.
| EMRG signal | Example Awin group | Logical conversion key |
|---|---|---|
widget_opened | WIDGET_OPENED | Flow + milestone |
appointment_type_selected | APPOINTMENT_TYPE_SELECTED | Flow + milestone |
provider_selected | APPOINTMENT_PROVIDER_SELECTED | Flow + milestone |
time_selected | APPOINTMENT_TIME_SELECTED | Flow + milestone |
email_sent | EMAIL_SENT | Flow + milestone |
email_verified | EMAIL_VERIFIED | Flow + milestone |
appointment_booked | APPOINTMENT_BOOKED | Flow + milestone |
appointment.completed | APPOINTMENT_DONE | Appointment + completed |
appointment.no_show | NO_SHOW | Appointment + no-show |
order.paid with no prior paid orders | NEW_CUSTOMER | Order |
order.paid with prior paid orders | RETURNING_CUSTOMER | Order |
booking.patient_linked is correlation, not another conversion. Use appointment.created for correlation/reconciliation without counting APPOINTMENT_BOOKED twice. appointment.cancelled has no conversion in this mapping. Do not use payment.received as the paid-order trigger; it can represent a partial payment.
Track lead quantity as 1 and purchase value as subtotal_cents / 100. Payout rates are separate account settings. Group codes are case-sensitive and their amounts must sum to the tracked total. See Awin commission groups.
Paid-order payload
{ "schema_version": 1, "event_id": "33333333-3333-4333-8333-333333333333", "event": "order.paid", "occurred_at": "2026-11-03T16:30:00Z", "clinic_id": 101, "data": { "order_id": "44444444-4444-4444-8444-444444444444", "patient_id": "55555555-5555-4555-8555-555555555555", "subtotal_cents": 10000, "currency": "USD", "applied_voucher_codes": ["WELCOME"], "prior_paid_order_count": 0 } }
EMRG emits one logical event per positive, fully funded order and economic clinic. The subtotal is discounted and excludes convenience fees. Partial payments, write-offs, services-rendered and account-credit entries do not qualify as funding. The worker reads the same durable orders/transactions for API, bulk and membership billing.
prior_paid_order_count covers earlier fully funded orders for the same patient record and economic clinic, including subsequently refunded purchases. Equal-time payments are not arbitrarily ordered. The example NEW/RETURNING mapping is an adapter policy to confirm with your business team; this is not a cross-clinic or cross-chart identity merge.
occurred_at records when qualifying payments first covered the total. A later refund does not erase that historical paid event. Refund reversal events are not included: define reconciliation before final commission approval. Amounts and voucher/history facts are snapshotted at capture, not a complete immutable billing journal.
6. Send reliable conversions to Awin
Prefer Awin's authenticated Conversion API. Its server-side x-api-key must never reach widget configuration. Submit the configured advertiser, reference, amount, currency, attribution and commission groups. Use aw for an Awin-attributed channel. A valid click or eligible voucher is needed; never fabricate a missing click.
Awin truncates references at 50 characters. Some widget eventId values exceed that limit. Generate and persist a bounded reference from the logical conversion, and reuse it across retries and matching browser/server sends:
import { createHash } from 'node:crypto'; function awinReference(clinicId, kind, objectId, stage = '') { const key = JSON.stringify([clinicId, kind, objectId, stage]); return 'e-' + createHash('sha256').update(key).digest('hex').slice(0, 40); } // 42 URL-safe characters; keep this algorithm stable after launch. // Browser: awinReference(clinicId, 'flow', bookingFlowId, eventName) // Visit: awinReference(clinicId, 'appointment', appointmentId, 'completed') // Sale: awinReference(clinicId, 'order', orderId)
Keep the purchase reference unchanged if its acquisition classification is corrected. Deduplicate incoming deliveries by event_id and outgoing conversions by the logical reference.
For delayed reporting, ask Awin to activate transactionTime, derived from occurred_at in Unix seconds. Aim for near-real-time forwarding and monitor queue age. Awin's three-minute rule concerns prioritization against a matching browser request, not universal rejection of delayed events. isTest: true does not create tracked transactions; HTTP 202 is not proof of attribution. See Conversion API timing and parameters.
If your plan also sends browser conversions, follow the asynchronous Conversion Tag pattern, preserving the parent AWIN object and applying host consent. Coordinate the transport plan and shared references with Awin to avoid duplicate counting.
Voucher-only attribution
Map the voucher to a publisher in Awin and confirm the account's channel rules. Forward the actual applied code using the destination's encoding requirements. A voucher applied in EMRG does not automatically establish an Awin publisher mapping. Define a policy for multiple applied codes, and test attribution without a click. See Awin voucher attribution.
Multiple brands and privacy
Resolve program settings from the economic clinic. For appointment outcomes, process only the recipient copy whose economic_clinic_id matches your configured clinic. For paid orders, use clinic_id. Never select an advertiser from a browser field or current patient referral.
Store each outgoing job's original advertiser, configuration version and reference. Changing settings must not reroute queued work, and disabling one program must not stop another. Shared advertisers must be an explicit configuration choice.
Your EMRG receiver still receives CRM events with patient/contact data. Translate only allowlisted fields; never forward the whole envelope to Awin. Patient IDs stay internal for correlation. Exclude contact information, service names and clinical/product details from advertising payloads.
Launch checklist
- Callback and webhook features are deployed; the correct clinic destination and Paid-order events are enabled.
- Account access, advertiser, currency, exact groups, payout rates, attribution window and test/live settings are confirmed.
- MasterTag and consent work on the intended host; redirects and server-readable click fallbacks preserve attribution.
- All seven browser milestones work; repeated selections do not duplicate them, and reopening creates a fresh flow.
- A verified existing patient abandons booking and purchases later; the correct clinic and eligible click are selected.
- New patient creation followed by a failed booking retains its link. Invalid verification and unrelated-clinic attempts create no link.
- Completed/no-show appointments and new/returning purchases map correctly. Partial payments, fees, noncash entries and refunds behave as documented.
- Bulk and membership billing purchases reach the same receiver. If using the Partner Booking API, test that path separately.
- Duplicate delivery, ambiguous Awin responses, older clicks arriving late and out-of-order links do not create duplicate or misattributed conversions.
- Two brands sharing a provider remain isolated, including voucher-only sales and queued work during reconfiguration.
- Failed-job recovery, delayed reporting and refund reconciliation have owners and procedures.
- Confirm the final deployed flow in the Awin account with your Awin contact, then coordinate live activation. Prior validation of another implementation is not acceptance of this adapter.
Troubleshooting
| Symptom | Check |
|---|---|
| No browser callbacks | Updated widget loaded, callback supplied at initialization, and configured clinic matches the launch. |
| Callback arrives but no patient link | Paid-order opt-in, completed verification/chart creation, valid booking relationship, and matching flow ID. No link exists before a first patient record. |
| Purchases cannot be attributed | Match clinic + patient to stored flow history; buffer events that arrive before correlation. Check click eligibility and voucher mapping. |
| Duplicate conversions | Reuse stable logical references across retry and browser/server sends; do not count both booked callback and appointment-created webhook. |
| Webhook is marked failed | Inspect the Events tab, fix receiver/signature/timeout issues, and replay the stored delivery. |
| Awin request succeeds but no attributed sale appears | Check test mode, advertiser, group codes, attribution window, voucher eligibility and account-side results. |