Docs
Checking Raims account
IntegrationsWebhooks

Receive and validate webhooks

Validate webhook signatures and process notifications safely, including redeliveries.

Prepare an HTTPS endpoint that accepts POST with Content-Type: application/json. Use the default port 443 and a domain whose DNS resolves to a public IPv4 address. It must receive calls between systems without interactive login, CAPTCHA, or redirects. Configure the destination and events in Webhooks, and allow the five official IPs when sources are restricted.

Event body

Each request identifies the event, environment, and changed resource.

JSON
{
  "id": "d377b4c5-5678-4c42-8ea3-8f823156948e",
  "type": "charge.paid",
  "created_at": "2026-10-15T12:30:00.000Z",
  "environment": "sandbox",
  "data": {
    "object": "charge",
    "id": "ch_4ZxYp8Q2mV7nR6sT5uW3aB",
    "payment_method": "pix",
    "paid_amount_cents": 10000,
    "currency": "BRL",
    "statement_id": "st_4ZxYp8Q2mV7nR6sT5uW3aB"
  }
}
FieldMeaning
idEvent UUID, preserved in redeliveries and across destinations receiving the same event.
typeEvent name, such as charge.paid, refund.completed, or webhook.test.
created_atEvent date in UTC, in ISO 8601 format. It does not represent the time of each attempt.
environmentsandbox or production, according to the resource's environment.
data.objectType of resource associated with the event.
data.idPublic identifier of that resource.
data.payment_methodPayment method associated with the event, such as pix or boleto, when known.
data.charge_idPublic identifier of the charge linked to a refund or dispute.

Retries and manual resends preserve the original body bytes. If you need the current state, query the resource with a credential for the same company and environment.

To validate the body for each event type, use the webhooks section of the OpenAPI contract.

data.objectdata.id prefixWhere to query
chargech_Charges
refundrf_Refunds
withdrawalwd_Withdrawals
disputemed_Disputes
statementst_Statements
payment_linkpl_Payment links
customercus_Customers
accountco_Account Ā· Balances
webhookwhk_Webhooks

Payment instructions events identify the charge in data.id and always include data.payment_method. In dispute.*, data.id identifies the dispute. If a charge is linked, use data.charge_id to retrieve it.

The customer.deleted event identifies the deleted customer, whose retrieval returns 404. For hold and release events, the balances query shows the account’s current amounts.

withdrawal.destination_changed and withdrawal.automatic_settings_changed identify the account. The data.object field is account and data.id starts with co_. Depending on the event type, query the withdrawal destinations or automatic withdrawal settings.

created_at uses ISO 8601 in the event. Delivery and attempt queries return dates in Unix seconds in UTC.

Event amounts and references

These fields are optional. When present, they record the amounts and links from the original event. Amounts are integers in cents, with data.currency set to BRL.

EventFields in dataReconciliation use
charge.paidpaid_amount_cents, statement_idTotal confirmed when the charge became paid and the statement entry for the associated credit.
refund.*charge_id, amount_centsLinked charge and individual refund amount. Use the event type to identify the request, bank acceptance, reconciliation, or final outcome.
refund.failedfailure_reason_codePublic failure code.
refund.completedstatement_idStatement entry for the debit from this refund.
statement.createdstatement_type, amount_cents, reference_type, reference_idEntry type and amount. The sign indicates a credit or debit. The reference appears when a public link is confirmed.
dispute.funds_debiteddebited_amount_cents, statement_idPositive amount of the confirmed debit for that movement and the statement entry ID.
boleto.overpayment_receivedcredit_delta_cents, statement_idDifference between the total confirmed in this settlement and the previous confirmed total, with the statement entry ID.

When present, data.statement_id matches data.id on the statement.created event for the same movement. Use this ID to reconcile the events, including partial refunds of equal amounts on the same charge. To retrieve the statement entry through the API, use a credential with permission to read statements. A first boleto settlement above the nominal amount can produce charge.paid and boleto.overpayment_received with the same statement_id. Count that credit once.

statement_type and reference_type use the codes from the statements API.

Signature headers

HeaderMeaning
webhook-idDelivery UUID for that destination. It remains the same in retries.
webhook-timestampAttempt time in Unix seconds in UTC.
webhook-signatureOne or more v1= signatures, each with 64 hexadecimal characters, separated by commas.

The webhook-id differs from the body's id: an event may be delivered to more than one destination or manually resent. Each delivery has its own webhook-id. Retries of the same delivery preserve that ID and the original body but may have a different timestamp and signature.

During a transition period chosen through the API, the same header contains the new secret's signature first, followed by the previous secret's: v1=<assinatura nova>,v1=<assinatura anterior>. The receiver must accept the request when any v1 signature matches the configured secret. When the deadline passes or an immediate rotation ends the transition, new sends include only the current secret's signature.

Validate the signature

  1. Capture the HTTP body as bytes before parsing the JSON.
  2. Read the three signature headers.
  3. Remove the whsec_ prefix from the registration's secret and decode the remaining part as Base62, in this order: digits from 0 to 9, letters from A to Z, and letters from a to z. Represent the number in 32 little-endian bytes, padding with zeros on the right when needed. These bytes are the HMAC key.
  4. Build the message from the UTF-8 bytes of webhook-id + "." + webhook-timestamp + ".", followed by the exact bytes of the received body.
  5. Split the header's signatures by comma and select the v1 values. Calculate HMAC-SHA256 and compare the result with each signature using a constant-time comparison. Accept the request if one matches.

Do not use the whsec_... text directly as the HMAC key. Do not serialize the JSON again: spaces, line breaks, and property order are part of the signature.

Configure the framework to preserve the original body on this route. An object already converted from JSON to the application's language cannot be used to check the signature. Reject the request without applying its effects if the signature or timestamp is invalid.

We recommend accepting timestamps within five minutes of the receiver's clock and keeping that clock synchronized. This check reduces the reuse of old requests. Delivery deduplication remains necessary within that window.

The tolerance applies to the attempt's webhook-timestamp, not to the body's created_at. Retries and resends receive a current timestamp and signature, while the original event date remains in the body.

Node.js example

Use the Node.js SDK to authenticate before decoding JSON. This module defines an HTTP handler for your existing Node.js server. Expose /webhooks/raims through the final HTTPS address and keep its request body untouched by JSON parsers or text encoding middleware.

The handler only acknowledges after acceptEvent confirms durable acceptance. Supply that adapter from your application; signature verification alone does not persist, deduplicate, or process the event. The 1 MiB body cap is a choice of this example, not an additional Raims API limit.

raims-webhook-handler.mjs
JavaScript
import { SignatureVerificationError, Webhook } from '@raimshq/raims';

const signingHeaders = ['webhook-id', 'webhook-timestamp', 'webhook-signature'];
const maxBodyBytes = 1024 * 1024;
class BodyLimitError extends Error {}

function readOriginalBody(request) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    let exceeded = false;
    request.on('data', (chunk) => {
      if (exceeded) return;
      size += chunk.length;
      if (size > maxBodyBytes) {
        exceeded = true;
        chunks.length = 0;
        reject(new BodyLimitError());
        return;
      }
      chunks.push(chunk);
    });
    request.once('end', () => {
      if (!exceeded) resolve(Buffer.concat(chunks));
    });
    request.once('aborted', () => reject(new Error('Request aborted.')));
    request.once('error', reject);
  });
}

export function createRaimsWebhookHandler({
  secret,
  environment,
  acceptEvent,
}) {
  if (
    typeof secret !== 'string' ||
    !secret ||
    !['sandbox', 'production'].includes(environment) ||
    typeof acceptEvent !== 'function'
  ) {
    throw new Error(
      'Configure the signing secret, environment, and durable adapter.',
    );
  }

  return async (request, response) => {
    if (request.url?.split('?')[0] !== '/webhooks/raims') {
      response.writeHead(404).end();
      return;
    }
    if (request.method !== 'POST') {
      response.writeHead(405, { Allow: 'POST' }).end();
      return;
    }
    if (
      !/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')
    ) {
      response.writeHead(415).end();
      return;
    }

    const names = request.rawHeaders
      .filter((_, index) => index % 2 === 0)
      .map((name) => name.toLowerCase());
    if (
      signingHeaders.some(
        (name) => names.filter((item) => item === name).length !== 1,
      )
    ) {
      response.writeHead(400).end();
      return;
    }

    try {
      const rawBody = await readOriginalBody(request);
      const event = Webhook.constructEvent(rawBody, request.headers, secret);
      if (
        event.environment !== environment ||
        typeof event.id !== 'string' ||
        !event.id ||
        typeof event.type !== 'string' ||
        typeof event.data?.id !== 'string'
      ) {
        response.writeHead(400).end();
        return;
      }

      const result = await acceptEvent({
        event,
        deliveryId: request.headers['webhook-id'],
      });
      if (result !== 'accepted' && result !== 'duplicate') {
        throw new Error('The durable adapter did not confirm acceptance.');
      }
      response.writeHead(204).end();
    } catch (error) {
      const status =
        error instanceof SignatureVerificationError
          ? 400
          : error instanceof BodyLimitError
            ? 413
            : 503;
      if (!response.headersSent) response.writeHead(status).end();
    }
  };
}

Connect the handler with the secret from your server configuration, the expected environment, and your durable inbox adapter:

Connect to your server
JavaScript
const handler = createRaimsWebhookHandler({
  secret: process.env.RAIMS_WEBHOOK_SECRET,
  environment: 'sandbox',
  acceptEvent: (entry) => inbox.acceptOnce(entry),
});

inbox represents your application's durable storage, not a component provided by the SDK. Its acceptOnce function must implement this contract:

Adapter resultRequired guarantee before resolving
acceptedThe event identity and pending work were saved atomically.
duplicateThe same event was already durably accepted; no new work was created.
Rejected promiseAcceptance was not confirmed. The handler returns a failure to allow redelivery.

Scope the identity to the authorized account, environment, and event id. Concurrent deliveries must not create two jobs. Store webhook-id only as delivery metadata. Recover accepted work after failures and make its effects idempotent; do not rely on another webhook after returning success.

Input to the handlerHTTP resultBusiness work
Valid signature, expected environment, durable acceptance204Saved once for later processing.
A previously accepted event204No additional job.
Invalid signature, ambiguous signing headers, or wrong environment400Not accepted.
Body above this example's cap413Not accepted.
The adapter fails503No acceptance is claimed.

After a valid signature, parse the JSON, check the environment, and record the delivery before responding. Store the secret on the integration server with restricted access. Never include it in URLs, browser code, screenshots, or support messages.

Acknowledge receipt

Respond with an HTTP 2xx status only after accepting the event into durable storage in your system. Send lengthy processing to a queue and run it asynchronously. A successful response confirms that the receiver accepted the delivery; it does not confirm a new financial transaction.

The receiver must follow this sequence:

  1. Validate the signature using the original body and check the event environment.
  2. Durably record the event id and the work to be processed. Ensure this acceptance prevents duplicates even when two requests arrive at the same time.
  3. If the event has already been accepted, return 2xx without recording the same work again. Otherwise, acknowledge receipt after saving.
  4. Process the accepted work and track its completion separately. If that processing fails after the response, your system must recover it: Raims has already received the delivery acknowledgement.

If you cannot store the event, do not acknowledge it with 2xx. Subsequent processing must also tolerate repetitions without duplicating their effects.

The timeout for each webhook HTTP send is 5 seconds in total. Validate the signature, record the event safely, and return 2xx within that time, without waiting for lengthy processing to finish. The up to 72 hours in Production is the retry window; a request does not stay open for that period.

Raims does not follow redirects; register the final HTTPS URL directly, including a trailing slash when it is part of the receiver's path. The registration preserves that slash. Configure the certificate with a valid public chain.

To investigate a response, check the HTTP status, duration, and error in the attempt details. By default, use your receiver logs to read the response text.

Handle redeliveries and ordering

A delivery may arrive more than once, including when the receiver already accepted the event but the response was lost. Record webhook-id to recognize retries of the same delivery and use the body's id to prevent a manual resend of the same event from repeating its effect. Acknowledge previously accepted duplicates with 2xx as well.

The same resource can generate separate events of the same type, such as two updates to a dispute. Each event has its own id.

Do not depend on arrival order. Events for different resources or retries may arrive in another sequence. Query the resource through the API when you need to decide based on its current state. If different destinations feed the same routine, the body's id identifies the same event across them.

SituationEvent idwebhook-idTimestamp and signatureWork to create
First deliveryEvent identityDelivery identityFrom this attemptOne durable job.
Retry of the same deliveryUnchangedUnchangedCan changeNone if already accepted.
Manual resendUnchangedNew delivery identityCurrentNone if that event was already accepted.

Manually resend events

The Dashboard allows you to request a resend for up to 15 days after the event was created, when the payload is available, the webhook is active, and the event type remains selected in the registration. The action requires Webhooks, View event logs, and Resend webhook events.

To recover multiple events, use Resend selected in the Dashboard logs. Each item remains subject to the individual resend conditions. Check the accepted and rejected results before repeating the request. Technical webhook.test events cannot be resent; request another test.

A resend creates a delivery with a new webhook-id and preserves the original body bytes, including id and created_at. It uses the webhook's current URL and secret. If a secret transition is active, the same signature rules as other sends apply.

The request does not cancel automatic retries for the previous delivery. When the queue is paused, the new delivery also waits for it to resume, and its own deadline continues counting down. Prepare the receiver to recognize the same body id across different deliveries. Requesting a resend does not repeat the financial action that generated the event or confirm receipt by the endpoint.

The retry window for this delivery starts when the resend request is accepted: up to 72 hours in Production or up to four hours in Sandbox, with a maximum of three retries after the initial attempt in Sandbox. In Production, intervals increase exponentially and vary between attempts, without a fixed count within the deadline. The limit for requesting another resend remains fifteen days after the original event was created; resending does not renew that limit or change the body's created_at.

Pause and resume the queue

Before maintenance, pause the webhook queue. Pending deliveries and newly selected events wait for the queue to resume within their original deadlines. Pausing does not interrupt an already authorized HTTP call or freeze the 72-hour Production or four-hour Sandbox window.

You can request a technical test while the queue is paused. After checking the receiver, resume the queue to allow sends that remain valid. Resuming does not recover expired deliveries.

Webhook failures and retries

An HTTP 2xx response completes the delivery. Connection failures, timeouts, and other HTTP codes allow retries within the environment's limits. This includes 3xx, 400, 401, 403, 404, 429, and 5xx. Raims does not follow redirects: configure the final HTTPS URL directly.

The technical webhook.test event has one HTTP attempt and a deadline of up to five minutes. Subscribed events follow the environment's retry policy.

In Production, Raims retries delivery for up to 72 hours from the event. Calculated intervals increase exponentially and vary between attempts, up to a one-hour limit. There is no fixed number of attempts within that deadline.

In Sandbox, there are up to three retries after the first attempt, spread over a few hours, within a window of up to four hours from the event. Use this environment to check how your receiver handles duplicates and failures.

Retry-After may specify a minimum wait in seconds or an HTTP date. A valid value may increase the interval beyond one hour. If that wait places the next attempt at or after the end of the delivery window, Raims does not schedule another attempt. The header does not extend the window or increase the number of Sandbox attempts. Check the address, signature, and firewall rules when investigating a failure; do not depend on an exact time for the next attempt.

Failure alerts

Failures do not automatically pause the queue or disable the webhook. Each delivery continues following its retry policy and deadline. After a delivery exhausts its limits, new events continue generating their own deliveries while the registration is active.

Raims notifies you in the Dashboard when the fifth and tenth failures of the same episode are confirmed. Each alert is sent once per episode. An HTTP 2xx response ends that episode; new failures may start another. Alerts do not stop retries or extend their deadlines.

Sending these alerts by email depends on the Webhook failure preference. Recipients are verified email addresses belonging to the account. Alerts may be grouped into email summaries, with a link to view the notices in the Dashboard.

Individual notices remain available in the Dashboard. Check the current registration state and logs to investigate a failure; an email summary may include alerts from before the endpoint recovered.

Fix the receiver and follow subsequent attempts. If you disabled the webhook manually, re-enable it to allow new sends. Re-enabling starts a new failure episode and preserves the registration, secret, and selected events. Rotating the secret does not reset the count or re-enable a disabled webhook. Editing the URL or events also preserves the registration state, failure count, and retry deadlines.

Disabling the registration prevents new sends. If a pending delivery's next attempt finds the webhook disabled, that delivery is closed. Re-enabling it before that attempt allows it to continue within the original limits. Re-enabling does not resend earlier events or automatically recover closed deliveries. When eligible, an event can receive a new delivery through manual resend. Requests in progress may still finish.

Test receipt through the API

After preparing the receiver, use Send a test event for the active webhook. When sent, the event uses the same URL and follows the same signature rules as other deliveries, with type: webhook.test, data.object: webhook, and the registration identifier in data.id.

The test checks connectivity and signature validation. It does not change charges, payments, refunds, balance, or the webhook's failure count. Check the result in the receiver records.

The up-to-five-minute deadline includes waiting until the test can be sent. The HTTP call to the receiver remains limited to five seconds. A 2xx response to the test does not prove that your application handles financial events; check that flow with Sandbox simulations.

A new request creates another test. If you need to retry the same request, keep the original Idempotency-Key to retrieve the same event_id and delivery_id. After a failed HTTP attempt, fix the integration before requesting a new test. The test allows one attempt.

A request accepted with HTTP 202 returns the event and delivery identifiers:

HTTP 202 response examplePOST /v1/webhooks/{webhook_id}/test

Send a test event

JSON
{
  "event_id": "d36ffb51-e0c6-8a8f-904d-e426cc0b76bb",
  "delivery_id": "46be4604-31fc-876a-bbb7-69e204ff9c14"
}
What proves receipt

Find the returned delivery ID as webhook-id at the receiver. Check the signature and durable acceptance there. The API's 202 confirms only that the test was requested; it does not prove that the receiver accepted it.

TestWhat it checksWhat it does not confirm
webhook.testConnectivity and signature at the registered receiver.Processing of charge or refund events.
Financial simulation in SandboxThe selected event and your isolated business handling.A real payment in Production.

Test webhooks in Sandbox

Register a destination in Sandbox and select the events you want. Create a charge and use Simulation to confirm a payment or test failures and refunds. Confirmed changes generate the corresponding Sandbox events for that destination without moving real money.

Webhook requests are real and use the same official IPs as Production. The body reports environment: sandbox. Keep the receiver and effects of this test separate from your system's Production data.