# License services (/docs/basic-concepts/license-services)

A license service hands a license key to the buyer of a product after they pay. The key is saved on the order item and shown on the receipt page and in the order email. This page shows how to set one up, how to build your own license server and how to deal with failed requests.

## Two kinds of license service [#two-kinds-of-license-service]

| `type` | Where keys come from | Use it when |
| --- | --- | --- |
| `list` | A list of keys you upload. Comecero hands them out one at a time. | You have keys made in advance. |
| `remote_url` | Your own license server. Comecero calls it after each sale and saves what it answers. | Each key is made for the buyer, for example from their name or email. |

One license service can serve many products.

## Set up a license service [#set-up-a-license-service]

<Steps>
<Step>

### Create the service [#create-the-service]

In the dashboard, go to **Store > License Services** and click to add one, or call [Create a license service](/api/license-services/create-license-service). A list service with two keys:

```bash title="Request"
curl -X POST "https://api.comecero.com/api/v1/license_services" \
  -H "Authorization: Bearer $COMECERO_TEST_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Widget Pro keys",
    "label": "License Code",
    "type": "list",
    "instructions": "Open Widget Pro, choose Help, then Enter License, and paste the code.",
    "configuration": {
      "licenses": ["AAAA-BBBB-CCCC-0001", "AAAA-BBBB-CCCC-0002"]
    }
  }'
```

`label` is what the buyer sees the key called, such as `License Code` or `Registration Code`. `instructions` are shown to the buyer with the key.

</Step>
<Step>

### Link it to a product [#link-it-to-a-product]

Set the product's `license_service_id` to the new service's `license_service_id` with [Update a product](/api/products/update-product), or add the license service on the product's page in the dashboard.

</Step>
<Step>

### Test it [#test-it]

Buy the product in test mode. The order item gets its key, and the [order licenses assigned](/api/webhooks/order-licenses-assigned) webhook fires once every item that needs a key has one.

</Step>
</Steps>

### List services [#list-services]

A list service hands out the keys in order. With `remove_after_use` a key is removed once used (new services start with it on). With `per_quantity`, a buyer of 3 units gets 3 keys; otherwise they get one per order item. When the keys left fall to `notify_at_count` (100 by default), the [low licenses](/api/webhooks/license-service-low-licenses) webhook fires so you can upload more. Updating `licenses` replaces the whole list.

## Build a license server [#build-a-license-server]

For a `remote_url` service, Comecero sends an HTTP `POST` to your server after each sale and saves the response body as the key.

```bash title="Request"
curl -X POST "https://api.comecero.com/api/v1/license_services" \
  -H "Authorization: Bearer $COMECERO_TEST_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Widget Pro key server",
    "label": "License Code",
    "type": "remote_url",
    "configuration": {
      "url": "https://licenses.example.com/issue",
      "format": "json"
    }
  }'
```

The `url` must be a public address, not `localhost` or a private network. `format` is `json` or `xml` and sets the format of the request body.

### What Comecero sends [#what-comecero-sends]

The body is a [license request](/api/license-requests) object. It holds the `product_id` the key is for and the whole `order`, with the customer expanded. Trimmed:

```json
{
  "object": "license_request",
  "license_request_id": "0142130710483Lruow24Z6",
  "test": true,
  "product_id": "widget-pro.test",
  "order": {
    "object": "order",
    "order_id": "6622-NXKHE-858",
    "items": [
      { "item_id": "widget-pro.test", "product_id": "widget-pro.test", "name": "Widget Pro", "quantity": 1 }
    ],
    "customer": {
      "object": "customer",
      "name": "John Doe",
      "email": "john@example.com"
    }
  }
}
```

The request has these headers:

| Header | Value |
| --- | --- |
| `Content-Type` | `application/json` or `application/xml` |
| `User-Agent` | `Comecero-LicenseRequest (+http://www.comecero.com)` |
| `X-Comecero-Signature` | The HMAC-SHA256 of the raw body, keyed with your account's signature key |
| `Authorization` | HTTP basic authentication, when you set `http_authorization_username` and `http_authorization_password` |
| Your own header | When you set `custom_header_name` and `custom_header_value` |

To send less of the order, set `show` or `hide` on the service; to add child objects, set its `expand`. They work like the [query parameters](/docs/basic-concepts/customizing-output) of the same name.

### What your server answers [#what-your-server-answers]

Answer with a status from 200 to 299 and the key as the body, as plain text:

```text
Name: John Doe
License Code: IUB2-PQYU-HAZM-UJE4
```

- Line breaks are kept. You can use a few HTML tags: `<br>`, `<b>`, `<strong>`, `<i>`, `<em>` and `<a href>`. Other HTML is removed.
- Only the first 4,096 characters are kept.
- An empty body counts as a failure.

A small server in Node.js:

```js
import http from 'node:http';
import crypto from 'node:crypto';

const signatureKey = process.env.COMECERO_SIGNATURE_KEY;

http.createServer((req, res) => {
  const chunks = [];
  req.on('data', (chunk) => chunks.push(chunk));
  req.on('end', () => {
    const raw = Buffer.concat(chunks); // the raw bytes, before parsing
    const expected = Buffer.from(crypto.createHmac('sha256', signatureKey).update(raw).digest('hex'), 'utf8');
    const received = Buffer.from(req.headers['x-comecero-signature'] ?? '', 'utf8');
    const valid = received.length === expected.length && crypto.timingSafeEqual(received, expected);
    if (!valid) {
      res.writeHead(401).end();
      return;
    }

    const request = JSON.parse(raw.toString('utf8'));
    const key = makeKey(request.product_id, request.order.customer.email); // your own key logic
    res.writeHead(200, { 'Content-Type': 'text/plain' }).end(`License Code: ${key}`);
  });
}).listen(3000);
```

### Secure your server [#secure-your-server]

- **Check the signature.** Compute the HMAC-SHA256 of the raw body, before you parse it, with your account's signature key from **Settings > Technical** (`signature_key`), and compare it with `X-Comecero-Signature` in constant time.
- **Use basic authentication or a custom header** as a second check, if you like.
- **Do not trust IP addresses.** Requests come from many addresses that change.
- **Make the same key for the same request.** A request can be sent more than once (see below), so the same `license_request_id` should give the same key, not a new one.

## When a request fails [#when-a-request-fails]

A request fails when your server cannot be reached, answers with a status outside 200 to 299, or answers with an empty body. Comecero then tries again on its own: every 2 minutes at first, then less often (up to every 8 hours), 22 more times over about 56 hours. After that the request is `failed`.

While a key is missing, the order confirmation email waits. It goes out as soon as every key on the order has been issued. So fix a failing license server quickly, or buyers do not get their order email.

To see and fix failed requests:

- In the dashboard, go to **Developer > License Requests**.
- With the API, call [List license requests](/api/license-requests/list-license-requests). Add `debug=true` to [Get a license request](/api/license-requests/get-license-request) to see `last_failure_meta`, with the first 500 characters of your server's answer.
- To try one again now, call [Retry a license request](/api/license-requests/retry-license-request). It answers `200` even when the attempt fails, so check `status` in the response. A success stops the automatic retries.

## Next steps [#next-steps]

<Cards>
  <Card title="Webhooks" href="/docs/guides/webhooks" />
  <Card title="License services in the API reference" href="/api/license-services" />
</Cards>
