# Webhooks

Instead of polling the sales endpoint, register an HTTPS URL and we POST a signed JSON event to it the moment something happens. Manage endpoints in your workspace under **Settings → API Key → Webhooks** (up to 5, each with its own signing secret shown once at creation).

| Event | Sent when |
|---|---|
| `sale.created` | One of your items, bundles or courses is sold |
| `sale.refunded` | One of your sales is refunded or cancelled — revoke the licence on your side |
| `ticket.created` | A buyer opens a support ticket about one of your items |
| `ticket.replied` | A buyer or an administrator replies on a support ticket of your items (never your own replies) |
| `license.activated` | A site activates a licence of one of your items (also a paused site coming back) |
| `license.deactivated` | A site pauses itself, or you revoke it |
| `license.blocked` | You or an administrator block a licence or one of its sites |
| `license.unblocked` | You or an administrator lift such a block |
| `item.update_approved` | An update of one of your items passed review and is live |
| `item.update_rejected` | An update of one of your items was rejected, or expired unreviewed after 30 days |

## Delivery

Each delivery is an HTTP POST with a JSON body. Respond with any 2xx status within 10 seconds; do heavy work asynchronously. Failed deliveries are retried 3 times (after 1 minute, 15 minutes and 1 hour). After 10 consecutive failures — or a 410 Gone response — the endpoint is disabled automatically and you are notified.

| Header | Description |
|---|---|
| `X-SMC-Event` | The event name, e.g. sale.created |
| `X-SMC-Delivery` | Unique delivery ID (UUID) — deduplicate retries with it |
| `X-SMC-Signature` | `t=<unix>,v1=<hex>` — HMAC-SHA256 signature (see below) |

```json
{
  "id": "1c2f6a7e-9d31-4c3e-8f5b-2d9f8f4f1a10",
  "event": "sale.created",
  "created_at": "2026-07-18T10:30:00+00:00",
  "data": {
    "sale_id": 981,
    "purchase_code": "8f14e45f-ce95-41d8-a2b6-72e5f13d81a7",
    "type": "item",
    "item": { "id": 123, "name": "My Theme" },
    "buyer": "johndoe",
    "license_type": "Regular",
    "price": 29.0,
    "earning": 23.2,
    "currency": "USD",
    "date": "2026-07-18T10:30:00+00:00"
  }
}
```

Support ticket events carry the ticket and the new message — see [Support tickets](https://sellmycode.net/api-docs/support-tickets.md):

```json
{
  "id": "6b1d…",
  "event": "ticket.replied",
  "created_at": "2026-10-24T08:12:00+00:00",
  "data": {
    "ticket_id": 812,
    "subject": "Webhook not firing after update",
    "item": { "id": 22314, "name": "Perfex Connect" },
    "buyer": "johndoe",
    "status": "open",
    "escalated": false,
    "message": { "id": 5011, "from": "buyer", "body": "Since 1.1.0 the Zapier hook…", "created_at": "2026-10-24T08:12:00Z" },
    "url": "https://sellmycode.net/workspace/support/…",
    "api_url": "https://sellmycode.net/api/tickets/812"
  }
}
```

## Licence events

The `license.*` events let a self-hosted update server react at once instead of waiting for an [entitlement token](https://sellmycode.net/api-docs/licence-entitlement.md) to expire. New endpoints must tick them; existing endpoints keep the events they chose.

```json
{
  "id": "0e4c…",
  "event": "license.blocked",
  "created_at": "2026-10-27T04:02:42+00:00",
  "data": {
    "purchase_code_hash": "3c9d…e1f2",
    "purchase_code_hint": "…81a7",
    "item": { "id": 123, "name": "My Script" },
    "license_type": "Regular",
    "buyer": "johndoe",
    "scope": "site",
    "domain": "customer-site.com",
    "by": "author",
    "reason": "Running on a reseller's demo server",
    "activation_limit": 2,
    "activations_used": 1,
    "date": "2026-10-27T04:02:42+00:00"
  }
}
```

| Field | Description |
|---|---|
| `scope` | `site` — one domain; `licence` — the whole purchase code (then `domain` is null) |
| `domain` | the site, lower case, without `www.` |
| `by` | `site` (the installation, through the licence API), `author` or `admin` |
| `state` | `license.activated`: `activated` or `reactivated` · `license.deactivated`: `paused` (the site keeps its slot) or `revoked` (slot freed) |
| `reason` | `license.blocked` only: the reason given when blocking |
| `purchase_code_hash` | SHA-256 of the purchase code, lowercase hex — match it against `hash('sha256', $code)` on your side; `license.*` events never carry the code itself, because the code is what activates licences |
| `purchase_code_hint` | the last four characters of the code, for logs and support screens |
| `activation_limit` / `activations_used` | the licence's slots after the change; limit null = unlimited |

## Verifying the signature

Compute HMAC-SHA256 over the string `timestamp.rawBody` with your signing secret and compare it (constant-time) to the v1 value. Reject deliveries whose timestamp is older than about 5 minutes to prevent replays.
```php
$secret  = 'whsec_...'; // from Settings → API Key → Webhooks
$body    = file_get_contents('php://input');
$header  = $_SERVER['HTTP_X_SMC_SIGNATURE'] ?? '';

parse_str(str_replace(',', '&', $header), $sig); // ['t' => ..., 'v1' => ...]

$expected = hash_hmac('sha256', $sig['t'] . '.' . $body, $secret);

if (!hash_equals($expected, $sig['v1'] ?? '') || abs(time() - (int) $sig['t']) > 300) {
    http_response_code(400); exit;
}

http_response_code(200); // ack fast, process async
```
```node
// Express: use express.raw() so the RAW body is available for the HMAC
const crypto = require('crypto');
const SECRET = 'whsec_...'; // from Settings → API Key → Webhooks

app.post('/webhooks/sellmycode', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('X-SMC-Signature') || '';
  const sig = Object.fromEntries(header.split(',').map(p => p.split('=')));

  const expected = crypto.createHmac('sha256', SECRET)
    .update(sig.t + '.' + req.body.toString('utf8')).digest('hex');

  const fresh = Math.abs(Date.now() / 1000 - Number(sig.t)) < 300;
  const valid = sig.v1 &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig.v1));

  if (!valid || !fresh) return res.sendStatus(400);

  const event = JSON.parse(req.body); // { id, event, created_at, data }
  res.sendStatus(200); // ack fast, process async
});
```
```python
# Flask — request.get_data() is the RAW body needed for the HMAC
import hmac, hashlib, time
from flask import Flask, request

SECRET = 'whsec_...'  # from Settings → API Key → Webhooks

@app.route('/webhooks/sellmycode', methods=['POST'])
def webhook():
    header = request.headers.get('X-SMC-Signature', '')
    sig = dict(p.split('=', 1) for p in header.split(',') if '=' in p)

    body = request.get_data()  # bytes, unparsed
    expected = hmac.new(
        SECRET.encode(), (sig.get('t', '') + '.').encode() + body, hashlib.sha256
    ).hexdigest()

    fresh = abs(time.time() - float(sig.get('t', 0))) < 300
    if not (hmac.compare_digest(expected, sig.get('v1', '')) and fresh):
        return '', 400

    event = request.get_json()  # { id, event, created_at, data }
    return '', 200  # ack fast, process async
```
```ruby
# Rails / Rack — request.body.read is the RAW body needed for the HMAC
SECRET = 'whsec_...' # from Settings → API Key → Webhooks

def webhook
  header = request.headers['X-SMC-Signature'].to_s
  sig = header.split(',').to_h { |p| p.split('=', 2) }

  body = request.body.read
  expected = OpenSSL::HMAC.hexdigest('SHA256', SECRET, "#{sig['t']}.#{body}")

  fresh = (Time.now.to_i - sig['t'].to_i).abs < 300
  valid = sig['v1'] &&
    ActiveSupport::SecurityUtils.secure_compare(expected, sig['v1'])

  return head :bad_request unless valid && fresh

  event = JSON.parse(body) # { id, event, created_at, data }
  head :ok # ack fast, process async
end
```
## Missed deliveries

Every event is tried 4 times in about 75 minutes (once, then after 1 minute, 15 minutes and 1 hour). After that it is dropped — there is no replay. Treat webhooks as a fast signal and reconcile now and then with the API:

| Events | Reconcile with |
|---|---|
| `sale.created`, `sale.refunded` | [`GET /api/sales?from=…`](https://sellmycode.net/api-docs/sales.md) — the `sale_status` of each sale |
| `ticket.created`, `ticket.replied` | [`GET /api/tickets?status=needs_reply`](https://sellmycode.net/api-docs/support-tickets.md) |
| `item.update_approved`, `item.update_rejected` | [`GET /api/items/{id}/versions`](https://sellmycode.net/api-docs/review-state.md) |
| `license.*` | refuse what verify refuses — an [entitlement token](https://sellmycode.net/api-docs/licence-entitlement.md) expires within 24 hours anyway |

## Review events

`item.update_approved` and `item.update_rejected` tell a release pipeline the review result of an update — one sent through the [upload API](https://sellmycode.net/api-docs/upload.md), [`PATCH`](https://sellmycode.net/api-docs/update-item.md) or the Workspace form — so it no longer has to poll. Updates that trusted authors publish at once fire nothing: the API answer already says `mode: "published"`.

```json
{
  "id": "5a0e…",
  "event": "item.update_rejected",
  "created_at": "2026-10-27T09:00:00+00:00",
  "data": {
    "item": { "id": 123, "name": "My Script" },
    "update_id": 846,
    "version": "2.5.0",
    "package_changed": true,
    "by": "reviewer",
    "reason": "The demo link is broken.",
    "submitted_at": "2026-10-26T08:00:00+00:00",
    "date": "2026-10-27T09:00:00+00:00",
    "api_url": "https://sellmycode.net/api/items/123/versions"
  }
}
```

| Field | Description |
|---|---|
| `update_id` | the `update_id` you got from the upload or `PATCH` answer |
| `version` | approved: the version now live · rejected: the version the update carried, when it set one |
| `package_changed` | the update replaced a file |
| `by` | `admin`, `reviewer`, or `auto` — rejected because nobody reviewed it within 30 days |
| `reason` | rejected only: why |

> **Note:** Endpoints must be public HTTPS URLs. Deliveries never follow redirects. Use the `X-SMC-Delivery` ID to deduplicate — a retry after a timeout can arrive even though you already processed the original.

---
Source: https://sellmycode.net/api-docs/webhooks
