# PHP SDK & WordPress

Two ready-made files that do the licence work for you: activate a site, check the licence, and install updates — with every answer's signature, nonce and package checksum verified.

> **Note:** The SDK only calls the public licence endpoints ([activation](https://sellmycode.net/api-docs/licence-activation.md) and [updates](https://sellmycode.net/api-docs/licence-updates.md)). Your buyers need nothing but their purchase code; you need no API token.

## Download

| File | What it is |
|---|---|
| [sellmycode-license-sdk.zip](https://sellmycode.net/api-docs/sdk/bundle) | both files below, in a `sellmycode/` folder |
| [SellMyCodeLicense.php](https://sellmycode.net/api-docs/sdk/php) | the PHP client — any PHP product |
| [class-sellmycode-wp-updater.php](https://sellmycode.net/api-docs/sdk/wordpress) | WordPress plugins and themes; needs `SellMyCodeLicense.php` next to it |

The files you download from this page already contain the current public key (`k1`), so answers are verified out of the box.

**Requirements:** PHP 7.4 or newer, `ext-sodium` (bundled with PHP since 7.2) or `paragonie/sodium_compat` (shipped with WordPress), and `ext-curl` or `allow_url_fopen`. `SellMyCodeLicense::requirements()` lists whatever is missing.

## What it does for you

- Sends a fresh `nonce` with every call and rejects answers whose signature, key id or nonce do not check out.
- Keeps the `activation_token` from [activate](https://sellmycode.net/api-docs/licence-activation.md) — updates and deactivation need it.
- Remembers the last signed answer and keeps the site licensed until `grace_until` when SellMyCode cannot be reached.
- Downloads update packages and compares them with the signed `sha256` and `size` before handing them to you.
- Refuses packages without a checksum (`integrity` other than `sha256`) unless you set `allow_unverified`.

## PHP quick start
1. Copy `SellMyCodeLicense.php` into your product and `require` it.
2. Create the client with your item ID and a storage file outside the web root.
3. Activate once, when the buyer enters their purchase code.
4. Call `isLicensed()` wherever you gate features, and `checkUpdate()` when you look for updates.
```php
require __DIR__ . '/vendor/sellmycode/SellMyCodeLicense.php';

$smc = new SellMyCodeLicense([
    'item_id' => 12345678,                       // YOUR item's ID on SellMyCode
    'purchase_code' => $settings['purchase_code'],
    'storage' => __DIR__ . '/storage/smc-license.json',
]);

// once, from your licence screen
$answer = $smc->activate();
if (!$answer->success) {
    echo $answer->message;                        // e.g. "This licence has used all of its site slots"
}

// anywhere
if (!$smc->isLicensed()) {
    exit('Please activate your licence.');
}
```

> **Warning:** The storage file holds the site's activation token. Keep it outside the public web folder, or deny access to it.

## Checking the licence

`isLicensed(int $maxAge = 43200): bool`

- Reuses the last verified answer for up to `$maxAge` seconds (12 hours by default) without a network call.
- After that it calls `verify`. A refused licence (blocked, refunded, paused, revoked) returns `false` at once.
- If SellMyCode cannot be reached, or the answer cannot be trusted, the site keeps running on the last good answer until its `grace_until`.

`verify()`, `activate()` and `deactivate()` return the full [answer](#the-answer-object) when you need the details.

## Installing updates

```php
$update = $smc->checkUpdate(MY_PRODUCT_VERSION);

if ($update->updateAvailable) {
    try {
        $zip = $smc->downloadUpdate($update);    // path of the verified .zip
        // unpack and install it your way, then delete $zip
    } catch (SellMyCodeLicenseException $e) {
        error_log('Update failed: ' . $e->reason . ' — ' . $e->getMessage());
    }
} elseif ($update->code === 'update_window_expired') {
    echo 'Renew your update period: ' . $update->renewUrl;
}
```

Unpacking and installing stay with you: every product installs differently. Make a backup first.

## The answer object

Every call returns a `SellMyCodeLicenseAnswer`.

| Property | Type | Description |
|---|---|---|
| `success` | bool | the server answered "success" |
| `code` | string | the answer code (`valid`, `activated`, `update_available`, `invalid_code`, …) or a client-side one, see below |
| `message` | string \| null | the error message |
| `offline` | bool | no trustworthy answer: the server was not reached, or the answer failed verification |
| `status` | int | HTTP status; `0` when the server was not reached |
| `data` | array | the decoded, verified payload — see [Signatures & fields](https://sellmycode.net/api-docs/licence-signatures.md) |
| `get($key)` | mixed | one payload field, dots for nested keys: `get('updates.until')` |
| `updateAvailable` | bool | `checkUpdate()`: a newer package can be downloaded |
| `latestVersion` | string \| null | latest published version |
| `package` | array \| null | `download_url`, `expires_at`, `max_uses`, `sha256`, `size`, `integrity` |
| `changelog` | array \| null | `version`, `body`, `released_at` |
| `renewUrl` | string \| null | where the buyer renews once the update period has ended |
| `entitlement` | string \| null | activate / verify: the [entitlement token](https://sellmycode.net/api-docs/licence-entitlement.md) |

Client-side codes: `offline`, `untrusted_answer` (bad signature, unknown key id or wrong nonce), `no_activation_token` (activate first), `not_configured` (no purchase code or domain), `sodium_missing`.

## Options

| Option | Default | Description |
|---|---|---|
| `item_id` *required* | — | your item's ID |
| `storage` *required* | — | a JSON file path, or `['get' => fn(): ?array, 'set' => fn(?array $state)]` to keep the state in your database |
| `purchase_code` | `''` | the buyer's purchase code |
| `domain` | current host | the domain to activate; `www.` is dropped |
| `allow_unverified` | `false` | let `downloadUpdate()` return packages that have no checksum |
| `public_keys` | keys in the file | `['kid' => 'base64 key']`, for [key rotation](https://sellmycode.net/api-docs/key-rotation.md) |
| `timeout` | `15` | seconds per licence call (downloads allow 300) |
| `api` | `https://sellmycode.net/api` | the API base URL |
| `transport` | curl / streams | your own HTTP function: `fn($method, $url, ?string $json, ?string $sinkPath): array{status, body}` |

## Download errors

`downloadUpdate()` throws `SellMyCodeLicenseException`. `$e->reason` is one of:

| Reason | Meaning |
|---|---|
| `unverified_package` | the package has no checksum and `allow_unverified` is off |
| `checksum_mismatch` | the file does not match the signed `sha256` or `size` — it was deleted |
| `no_package` | the answer carries nothing to download |
| `bad_package_url` | the link does not point at the licence API |
| `not_writable` | the download folder is not writable |
| `download_failed` | no signed answer came back |
| a server code | `invalid_ticket`, `ticket_used`, `package_changed`, `not_allowed`, `update_window_expired`, `item_removed`, `rate_limited` — see [Licence updates](https://sellmycode.net/api-docs/licence-updates.md) |

`$e->answer` holds the signed answer when the server sent one.

## WordPress plugins and themes

Put both files in a folder of your plugin or theme and create the updater once.

**Plugin** — in the plugin main file:

```php
require_once __DIR__ . '/sellmycode/class-sellmycode-wp-updater.php';

new SellMyCodeWpUpdater([
    'item_id' => 12345678,
    'file' => __FILE__,
    'settings_page' => true,                     // Settings → My Plugin licence
]);
```

**Theme** — in `functions.php`:

```php
require_once get_template_directory() . '/sellmycode/class-sellmycode-wp-updater.php';

new SellMyCodeWpUpdater([
    'item_id' => 12345678,
    'theme' => get_template(),
    'settings_page' => true,
]);
```

What the buyer gets:

- **A licence screen** (with `settings_page`): they paste the purchase code and click Activate. The code is shown masked afterwards, with the update period and a Deactivate button.
- **Updates in WP admin**: a new version appears under Dashboard → Updates and on the Plugins / Themes screen like any other. "Update now" and WordPress auto-updates both work.
- **A verified install**: the package is fetched through the licence API at the moment of the update and checked against the signed `sha256` before WordPress unpacks it.
- **Clear reasons** when an update cannot be installed: a renew link once the update period has ended, or a pointer to their SellMyCode library when the package has no checksum.

Checks are cached for 6 hours; "Check again" on Dashboard → Updates refreshes them.

| Option | Description |
|---|---|
| `item_id` *required* | your item's ID |
| `file` / `theme` | the plugin main file (`__FILE__`), or the theme folder name |
| `settings_page` | `true` for a screen under Settings, or a parent menu slug of your own |
| `purchase_code` | a string or callable, when your own settings screen stores the code |
| `name` | shown on the licence screen; defaults to the plugin or theme name |
| `allow_unverified` | install packages that have no checksum |
| `public_keys`, `transport` | as in the PHP client; requests use the WordPress HTTP API by default |

Using your own settings screen? Pass `purchase_code`, then call `$updater->license()->activate()` when the buyer saves. `$updater->license()` is the same PHP client, so `$updater->license()->isLicensed()` gates premium features.

## Your own update server

If your files live on your own server, send it an [entitlement token](https://sellmycode.net/api-docs/licence-entitlement.md) instead of the purchase code:

```php
// in the product
$token = $smc->entitlement();            // reused for up to 23 hours, then refreshed through verify
$zip = my_http_get('https://updates.example.com/latest.zip', ['Authorization: Bearer ' . $token]);

// on updates.example.com
$claims = SellMyCodeLicense::verifyEntitlement($bearer, ['item_id' => 12345678]);
if (!$claims || !$claims['updates']['active']) {
    http_response_code(403);
    exit;
}
```

## Lost activation token

The token is issued once. A site that lost it (database restored, storage deleted) still verifies, but can neither update nor deactivate. Revoke that site under Workspace → Licenses; the buyer activates again and gets a new token.

---
Source: https://sellmycode.net/api-docs/licence-sdk
