# Financial event integration examples

These are source examples, not a published marketplace app. Deploy the matching services and browser SDK before using the new routes. Keep private credentials on your server. For an installable WooCommerce integration with classic and Checkout Blocks support, use the reviewed [WooCommerce 1.1.2 plugin source](../../integrations/woocommerce/readme.txt) and the web installer at `/downloads/neutarget-woocommerce-1.1.2.zip` (checksum at the same URL with `.sha256` appended). The complete [installation pack source](../../integrations/installation-kit/START-HERE.md) adds placement examples, PDF guides and a feature activation checklist.

## Shared API contract

`POST https://api.neutarget.com/api/v1/financial-events` uses `X-Api-Secret` and JSON:

```json
{
  "websiteId": "YOUR_WEBSITE_UUID",
  "idempotencyKey": "capture:booking-42",
  "orderId": "booking-42",
  "kind": "capture",
  "amountMinor": "12345",
  "currency": "USD",
  "occurredAt": "2026-11-02T00:00:00Z",
  "sessionHash": null,
  "customerStatus": "unknown"
}
```

Amounts are positive integer **minor units**, sent as decimal strings to preserve values above JavaScript's safe-integer range. `kind` is `capture`, `refund` or `chargeback`; adjustments reference the original `orderId`. USD123.45 is12345, JPY123 is123, and KWD1.001 is1001. Use `currency-exponents.json`, generated by the same Java currency catalog as the services. Unsupported/unknown currencies cannot be guessed.

Use a stable capture key derived from the order and a stable refund/loss key derived from the actual provider adjustment ID. Retries must keep the same amount, currency, occurrence time and key. A409 means the event requires review; changing the key must not be used to create a second capture. Record the capture before its adjustments. A200 response acknowledges a PostgreSQL receipt; `delivery: pending` means downstream projection is pending. A204 means website collection is closed. Missing attribution never prevents recording an otherwise eligible confirmed payment.

The generic API classifies a private-key holder's report as `server_reported`. It cannot independently verify that your provider collected money. Verify signatures and fetch the canonical provider payment/order on your server before calling it. Native Shopify's authenticated receiver records `provider_verified` events. A hash is a pseudonymous identifier, not proof of a person or of consent. Do not hash raw email addresses into a globally shared identifier. An optional `userHash` must be a site-scoped64-character digest; set `customerStatus: new` only when your own customer history establishes it.

Remove private-key attributes from any existing browser integration. Any credential previously placed in public HTML must be replaced before relying on its secrecy; update backend configuration through a controlled credential cutover. Existing keys are not silently rotated by this change.

## Node.js server

`client.mjs` exports exact `decimalToMinor` and bounded `reportFinancialEvent` functions. A booking, SaaS invoice, donation or commerce server can use the same contract. Read amount, currency and occurrence time from the verified provider record, and pass only optional session context from the browser.

The helper retries transient transport errors with the same payload. Your webhook receiver must persist its authenticated receipt/job **before acknowledging the provider**; retain failed jobs for retry or review. Three HTTP attempts in a helper are not a durable job queue. Never accept the browser's amount or `eventSource` as payment evidence.

## Browser handoff

```js
const context = await window.neutarget?.whenReady?.({ timeoutMs: 2000 });
// Include this optional field in your existing authenticated checkout request.
const sessionHash = context?.ready ? context.sessionHash : null;
```

`whenReady` has a bounded deadline and resolves without a session when tracking is disabled/unavailable. The SDK uses a random session nonce with30-minute inactivity expiry, plus approximate weekly network groups for anonymous visitor reporting. Its `revenue()` method cannot confirm a payment. No browser script needs the private API secret.

## Shopify theme

Connect the native integration, then configure `orders/paid`, `refunds/create` and `order_transactions/create` at the dashboard's Shopify webhook URL. Refund creation alone does not establish money movement; only successful refund transactions reduce recorded revenue. Provider occurrence times and ISO currency scales are preserved.

Load `shopify-storefront.js` after your tracking script. It exports `neutargetPrepareShopifyCheckout`; loading it alone does not modify checkout. Await it inside your theme's existing checkout handler, and always continue checkout when it returns false. It updates the same-origin, locale-aware cart's `nt_session` and `nt_consent` attributes and clears obsolete values if attribution is unavailable.

For a standard native cart form with a `name="checkout"` submit button, this hook preserves native submission:

```js
if (HTMLFormElement.prototype.requestSubmit) {
  const resumed = new WeakSet();
  document.querySelectorAll('form[action$="/cart"]').forEach(form => {
    form.addEventListener('submit', async event => {
      if (resumed.has(form) || event.submitter?.name !== 'checkout') return;
      event.preventDefault();
      try { await window.neutargetPrepareShopifyCheckout(); } catch (_) {}
      resumed.add(form);
      try { form.requestSubmit(event.submitter); } finally { resumed.delete(form); }
    });
  });
}
```

Validate the hook against your actual theme. Cart drawers, Checkout Extensibility, Shop Pay and other accelerated checkouts require their own supported metadata handoff. Financial webhooks still record eligible payments without that context; attribution is then unavailable rather than invented.

## WooCommerce

The source files below are the earlier classic-checkout reference example. The installable 1.1.0 plugin in `integrations/woocommerce/` is the current path for stores; it also supports Checkout Blocks, encrypted server credentials, operator review and bounded repair of stranded receipt jobs. See [the integration guide](../../docs/woocommerce-integration.md) for its install and live validation steps.

Copy `woocommerce-neutarget.php`, `woocommerce-checkout.js` and `currency-exponents.json` into one site-specific plugin directory. Configure `NEUTARGET_WEBSITE_ID` and `NEUTARGET_API_SECRET` in server configuration, and keep your existing secretless tracking tag. This example requires WooCommerce Action Scheduler and a functioning WordPress/system cron runner.

The PHP adapter initializes the order before reading it, queues work from payment-completion/paid-order and refund hooks, preserves occurrence times and exact amounts, and uses durable Action Scheduler retries. It records returned receipt IDs in order metadata. Unpaid orders and thank-you page views cannot assert payment. Manual WooCommerce refunds remain merchant assertions; this adapter does not independently authenticate the payment gateway.

The JavaScript adapter supports **classic checkout**. Checkout Blocks require a Store API extension; this source example does not claim that support. Guest email hashes are not generated. Registered customer IDs use a site-scoped HMAC. Review lawful processing/consent requirements for your deployment.

Inspect failed actions in WooCommerce → Status → Scheduled Actions. Invalid credentials or conflicting amounts require repair; do not generate a new event key to bypass a conflict. Financial receipts follow the website's analytics retention and erasure policy, separately from NeuTarget's own subscription invoices.

## Executable validation

```sh
node --test examples/financial-events/client.test.mjs examples/financial-events/storefront.test.mjs
docker run --rm --network none --read-only \
  -v "$PWD/examples/financial-events:/examples:ro" php:8.3-cli \
  php /examples/woocommerce.test.php
```

The tests exercise actual Node/PHP code with mocked network/WordPress boundaries. They do not certify compatibility with every Shopify theme, WooCommerce version or payment gateway. Regenerate the currency catalog with Java21 using `java tools/ExportCurrencyCatalog.java > examples/financial-events/currency-exponents.json`.

Canonical `/financial-events` requests require the original provider occurrence time in
`occurredAt`; retain it with the durable job and never replace it on retry. The Node helper
rejects missing/invalid times before network I/O. Legacy `/revenue` retains its optional
server-time compatibility; its replay proof is bounded by retained source history.
