Aller au contenu

Événements et webhooks

S’abonner aux événements du réseau (OHN-24), les recevoir par webhook signé ou les récupérer, et vérifier chaque envoi.

Lorsqu’un autre système doit être informé d’un fait (un résultat est disponible, une référence est acceptée, une demande de remboursement est tranchée), le service qui en est responsable publie un événement. OHN-24 (infrastructure d’événements et d’abonnements) le transmet aux abonnés par webhook (envoi) ou les laisse le récupérer (pull).

L’enveloppe

Tous les événements partagent la même enveloppe ; le payload varie selon le type d’événement.

ChampSignification
event_idIdentifiant unique. Servez-vous-en pour éliminer les doublons.
event_typeNom pointé, par exemple diagnostic-result.available (motif ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$).
schema_versionVersion du schéma du payload (voir Gestion des versions).
occurred_atDate de l’événement (ISO 8601, UTC).
jurisdiction_id, organization_idOù il s’est produit.
aggregate_id, aggregate_versionL’enregistrement modifié et sa version.
correlation_id, causation_idPour remonter une chaîne d’événements jusqu’à la demande d’origine.
data_classificationClasse de sensibilité ; elle détermine quels abonnés peuvent recevoir l’événement.
payloadIdentifiants, codes et états, tels que les définit chaque schéma d’événement. Les payloads restent minimaux (par exemple, les événements de résultat d’OHN-11 ne contiennent aucune valeur de résultat) : récupérez l’enregistrement par l’API, où l’accès est vérifié.

S’abonner

Les abonnements se gèrent par OHN-24 (/api/ohn/v1/subscriptions, /api/ohn/v1/endpoints, /api/ohn/v1/event-schemas ; voir le contrat OHN-24). Règles toujours applicables :

  • Un abonnement ne reçoit que les événements de sa propre organisation.
  • La diffusion est refusée par défaut selon la classification des données ; le plafond des abonnements est internal.
  • Les redirections ne sont jamais suivies lors de l’envoi d’un webhook.

Livraison

  • Au moins une fois. Un même événement peut arriver plusieurs fois : éliminez les doublons grâce à event_id.
  • L’ordre n’est garanti que par aggregate_id.
  • Nouvelles tentatives. Un délai dépassé, une erreur réseau, 408, 425, 429 ou tout 5xx est réessayé avec un délai exponentiel (par défaut : base 30 s, plafond 1 heure, au plus 8 tentatives en 72 heures). Tout autre 4xx ou un 3xx est définitif.
  • Après la dernière tentative, l’envoi passe en file des lettres mortes et un événement delivery.failed est publié. Les opérateurs peuvent rejouer des événements (/api/ohn/v1/events/{id}/replay).
  • Mode pull : au lieu d’un webhook, prenez les événements avec /api/ohn/v1/subscriptions/{id}/pull (avec bail) et accusez réception de chacun avec /api/ohn/v1/deliveries/{id}/acknowledge.

Répondez à un webhook par un 2xx dès que l’événement est enregistré ; faites le traitement ensuite.

Vérifier un webhook

Chaque envoi est un POST avec content-type: application/json et ces en-têtes :

En-têteValeur
x-ohn-event-idL’event_id de l’événement. Vérifiez qu’il correspond au corps.
x-ohn-signaturesha256=<HMAC-SHA256 hexadécimal du corps brut>
x-ohn-signature-notehmac, ou local-unsigned sur un déploiement de développement local. Refusez local-unsigned dans tout environnement réel.

Vérifiez la signature sur les octets bruts, avant d’analyser le JSON, avec une comparaison en temps constant. Pendant un renouvellement de secret, acceptez chacun des secrets en cours. Actuellement, un déploiement signe tous les envois avec un unique secret de webhook que l’opérateur du réseau vous communique ; conservez-le dans votre gestionnaire de secrets.

// Node.js 18+
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyOhnWebhook(rawBody, headers, secrets) {
  if (headers['x-ohn-signature-note'] !== 'hmac') return false;
  const got = Buffer.from(String(headers['x-ohn-signature'] ?? ''));
  const ok = secrets.some((s) => {
    const want = Buffer.from('sha256=' + createHmac('sha256', s).update(rawBody).digest('hex'));
    return want.length === got.length && timingSafeEqual(want, got);
  });
  if (!ok) return false;
  return JSON.parse(rawBody.toString('utf8')).event_id === headers['x-ohn-event-id'];
}
// Java 17+
static boolean verify(byte[] rawBody, String signature, List<String> secrets) throws Exception {
  for (String s : secrets) {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(s.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String want = "sha256=" + HexFormat.of().formatHex(mac.doFinal(rawBody));
    if (MessageDigest.isEqual(want.getBytes(StandardCharsets.US_ASCII), signature.getBytes(StandardCharsets.US_ASCII))) return true;
  }
  return false;
}

Les SDK incluent cette vérification (verifyWebhook, verify_webhook, Webhooks.verify) et un utilitaire SeenEvents pour éliminer les doublons.

Catalogue des événements

192 types d’événements publiés par 49 services, lus dans les schémas d’événements du dépôt (modules/OHN-XX/events/).

ServiceTypes d’événementsSchémas
OHN-04identifier.mapping.changed, patient.merged, patient.unmerged1
OHN-05facility.branding.changed, facility.logo.approved, facility.logo.rejected, facility.logo.uploaded, facility.logo.withdrawn, facility.registered, facility.suspended, facility.verified1
OHN-06affiliation.changed, practitioner.license.expired, practitioner.suspended, practitioner.suspension.lifted, practitioner.verified1
OHN-08clinical-summary.updated, health-chart.projection.refreshed1
OHN-09encounter.corrected, encounter.timeline.updated1
OHN-10clinical-summary.observations-recorded, clinical-summary.published, reconciliation.requested1
OHN-11critical-result.acknowledged, critical-result.detected, critical-result.escalated, diagnostic-result.amended, diagnostic-result.available1
OHN-12birth.event.linked, child-health.age-transition.completed, immunization.record.updated1
OHN-13document.registered, document.revoked, document.versioned3
OHN-14emergency-summary.accessed, ips.generated1
OHN-15consent.expired, consent.granted, consent.revoked1
OHN-16access.denied, access.policy-version.changed, document_mark.issued, policy.published4
OHN-17emergency-access.ended, emergency-access.reviewed, emergency-access.started1
OHN-18audit.export.generated, audit.integrity.failure2
OHN-19delegation.revoked, dependent.age-transition, representation.verified1
OHN-20privacy.assessment.approved, privacy.policy.changed, transfer.authorized3
OHN-21fhir.transaction.accepted, fhir.transaction.rejected2
OHN-22legacy.message.accepted, legacy.message.quarantined1
OHN-23terminology.mapping.disputed, terminology.version.published1
OHN-25connector.connected, connector.degraded, connector.upgraded1
OHN-26edge.conflict.detected, edge.lease.expired, edge.sync.completed3
OHN-27referral.accepted, referral.completed, referral.declined, referral.sent1
OHN-28clinical-notification.acknowledged, clinical-notification.escalated, clinical-notification.needs-supervisor, clinical-notification.sent1
OHN-29aggregate.approved, aggregate.rejected, aggregate.submitted1
OHN-30coverage.eligibility.received, coverage.eligibility.requested1
OHN-31patient.portal-accessed, patient.request.submitted1
OHN-32clinician.emergency-requested, clinician.patient-accessed1
OHN-33developer.application.approved, developer.credential.rotated1
OHN-34quality.issue.detected, stewardship.case.resolved2
OHN-35ops.incident.closed, ops.incident.opened, ops.slo.breached1
OHN-36federation.request.denied, federation.transfer.approved2
OHN-37assurance.changed, proofing.completed, proofing.failed3
OHN-38auth.risk.detected, auth.session.revoked, client.credential.rotated3
OHN-39trust.enrollment.approved, trust.status.revoked2
OHN-40record-location.expired, record-location.registered2
OHN-41fhir.profile.published, fhir.resource.versioned2
OHN-42resource.classified, resource.reclassified1
OHN-43record.correction.proposed, rights.request.closed, rights.requested3
OHN-44clinical.hazard.detected, clinical.release.approved, clinical.release.blocked1
OHN-45crypto.key.revoked, crypto.key.rotated, crypto.signature.failed3
OHN-46partner.conformance.failed, partner.conformance.passed1
OHN-47backup.failed, failover.initiated, restore.drill.passed3
OHN-48disposal.completed, legal-hold.placed, retention.policy.changed3
OHN-49order.accepted, order.amended, order.cancelled, order.in_progress, order.performed, order.placed, order.protocoled, order.rejected, order.resulted, order.reviewed, order.scheduled, order.specimen_collected, orders.config.changed1
OHN-50medication.dispensed, prescription.signed2
OHN-52digitisation.item.written, digitisation.job.completed, digitisation.job.ready_for_review, digitisation.job.rejected, digitisation.job.uploaded, digitisation.page.sent_to_external_engine1
OHN-54appointments.appointment.booked, appointments.appointment.cancelled, appointments.appointment.checked_in, appointments.appointment.completed, appointments.appointment.in_consultation, appointments.appointment.no_show, appointments.appointment.rescheduled, appointments.booking_settings.changed, appointments.encounter.linked, appointments.followup.booked, appointments.followup.cancelled, appointments.followup.created, appointments.reminder.requested, appointments.request.accepted, appointments.request.confirmed, appointments.request.created, appointments.request.declined, appointments.request.expired, appointments.request.proposal_rejected, appointments.request.proposed, appointments.request.withdrawn, appointments.schedule.published, appointments.schedule.retired, appointments.waitlist.added, appointments.waitlist.slot_offered, teleconsult.call.ended, teleconsult.call.started, teleconsult.consent.recorded1
OHN-56public_health.adr.reviewed, public_health.adr.submitted, public_health.alert.raised, public_health.alert.triaged, public_health.alert.updated, public_health.civil_notice.registered, public_health.civil_notice.rejected, public_health.civil_notice.sent, public_health.config.changed, public_health.registry.enrolled, public_health.registry.status_changed1
OHN-57insurance.fraud_flag.raised, insurance.fraud_flag.resolved, research.access_request.decided, research.access_request.submitted, research.contact.outcome_recorded, research.extract.released, research.study.registered, research.study.state_changed, research.trial.contacts_routed1