# Welcome

{% hint style="warning" %}
We've moved to our new documentation site with improved guides and AI-powered support! Visit us at <https://go.sundevs.net/sl-doc>
{% endhint %}

{% embed url="<https://youtu.be/kgDKtpxXg8A>" %}
What is SunLicense ?&#x20;
{% endembed %}

Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Getting Started</strong></td><td>Step by setup guide to setup SunLicense on Pterodactyl panel</td><td><a href="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2FLVIzPlOyBf8OGF4PcvNV%2Fpurple-diamond.png?alt=media&amp;token=1dd4e06a-d64a-423e-a427-c5112d47e04e">purple-diamond.png</a></td><td></td><td><a href="/getting-started/quickstart">Getting Started</a></td></tr><tr><td><strong>API Docs</strong></td><td>SunLicense Open-API Documentation</td><td><a href="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2F432AYgd6NpuXnv83YYzD%2FSUN.png?alt=media&amp;token=e513f970-d396-4ded-b5e7-a7ae0880bdce">SUN.png</a></td><td></td><td><a href="/api-documentation/license-api">API Documentation</a></td></tr><tr><td>A<strong>utomations</strong></td><td>Automate the license issual process</td><td><a href="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2FpVQdyWFdkuaYyhRd1g1b%2Fpurple-torus.png?alt=media&amp;token=55ea4a4e-bc7b-4ebb-9812-1ff1cb620e5b">purple-torus.png</a></td><td></td><td><a href="/automations/builtbybit-automation">Automations</a></td></tr></tbody></table>

{% hint style="info" %}
This documentation includes AI-generated content such as videos, images, and text. If you need further assistance, please join our Discord community at <https://dsc.gg/sundevs> to contact the developer. We are always happy to help.
{% endhint %}


# Quickstart

Step by setup guide to setup SunLicense on Pterodactyl panel

{% hint style="warning" icon="burst-new" %}
We've moved to our new documentation site with improved guides and AI-powered support! Visit us at <https://go.sundevs.net/sl-doc>
{% endhint %}

{% embed url="<https://www.youtube.com/watch?t=91s&v=objpAGzFlgM>" fullWidth="true" %}
SunLicense Server Setup Guide
{% endembed %}

### Step 1: Purchase and Download `server.jar`

{% embed url="<https://builtbybit.com/resources/sunlicense-license-management-system.58359/>" fullWidth="false" %}
SunLicense resource page
{% endembed %}

{% stepper %}
{% step %}
**Visit the SunLicense Resource Page**

Navigate to the SunLicense resource page to purchase your license.
{% endstep %}

{% step %}
**Choose a Payment Method**

You can use the following secure payment options:

* **PayPal**
* **Credit/Debit Card**
* **Cryptocurrency**\
  *(All payments are processed securely through Tebex.)*
  {% endstep %}

{% step %}
**Download the `server.jar` File**

Once your purchase is complete, you will gain access to download the `server.jar` file
{% endstep %}
{% endstepper %}

{% hint style="success" %}
While purchasing the license, you can also choose to purchase the **Managed Hosting** addo&#x6E;**.**\
With this add-on:

* We will manage and host your server.
* You won’t need to handle anything beyond this step.
  {% endhint %}

### Step 2: Join Our Discord Server to Request a License Key

{% embed url="<https://dsc.gg/sundevs>" %}
Sundevs Support Discord Server
{% endembed %}

{% stepper %}
{% step %}
**Join the SunLicense Discord Server**

Use the following link to join our Discord server: Join Discord.
{% endstep %}

{% step %}
**Go to the License Channel**

Navigate to the **#premium** channel within the server.
{% endstep %}

{% step %}
**Request Your License Key**

* Click the **Request License** button in the embedded message.
* A developer will provide your license key shortly.
  {% endstep %}

{% step %}
**Save Your License Key**

Keep this license key safe, as you will need it later.
{% endstep %}
{% endstepper %}

### Step 3: Download SunLicenseEggShell (Generic Java Egg) and Import it to Pterodactyl Panel

{% file src="/files/UX9QJ2ithg58VVZx3dOj" %}
SunLinceseEggShell is a modified generic java egg that can be used to SunLicense on Pterodactyl Panel\
Generic Java Egg was created by [parkervcp](https://github.com/parkervcp).
{% endfile %}

{% stepper %}
{% step %}
**Download the SunLicenseEggShell**

Download the `SunLicenseEggShell (Generic Java Egg)` file from the above provided link
{% endstep %}

{% step %}
**Go to Your Pterodactyl Admin Dashboard**

Log in to your Pterodactyl admin panel.
{% endstep %}

{% step %}
**Navigate to Nests**

In the **Service Management** section, locate and select **Nests**.
{% endstep %}

{% step %}
**Import the Egg**

* Click the **Import Egg** button (green button).
* Upload the `SunLicenseEggShell` file you downloaded earlier.
  {% endstep %}
  {% endstepper %}

<figure><img src="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2F1Ru5U137M40eXsNwbzJt%2Fimage.png?alt=media&amp;token=0d083baf-14f9-4a29-bdec-f931f619fb23" alt=""><figcaption></figcaption></figure>

### Step 4: Create and Start a Server with SunLicenseEggShell

{% stepper %}
{% step %}
**Go to the Servers Section**

Navigate to the **Servers** section in your Pterodactyl panel.
{% endstep %}

{% step %}
**Click the Create Server Button**

Select the **Create Server** button to start setting up a new server.
{% endstep %}

{% step %}
**Configure Server Resources**

SunLicense typically requires the following minimum resources:

* **CPU Cores**: 1 Core
* **RAM**: 1 GB
* **Storage**: 2 GB

Adjust these settings based on your requirements.
{% endstep %}

{% step %}
**Select the Egg File**

Choose the **Egg File** that you uploaded in the previous step.
{% endstep %}

{% step %}
**Upload `server.jar` to newly created server**

Goto file tab of newly created server and upload server.jar
{% endstep %}

{% step %}
**Create  `license.txt`**

* Create file called `license.txt` next to the `server.jar`&#x20;
* Open `license.txt` and paste license key that you obtained from step 02
* Save the license key and start the server
  {% endstep %}
  {% endstepper %}

<figure><img src="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2FWZfHpOEU6oqW9eHEVsch%2Fimage.png?alt=media&amp;token=569cbecd-5c14-410a-8fae-b9402ecb97cf" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
On the first start, the SunLicense server will automatically download the required dependencies.

* This process may take several minutes.
* During this time, a folder named `.m2` will be created.
* Please wait until the process is complete.
  {% endhint %}

### Step 5: Access the SunLicense Dashboard

{% stepper %}
{% step %}
**Visit Your Server Address**

Open your browser and navigate to:\
`http://{serverip}:{port}`\
*(Replace `{serverip}` and `{port}` with your server's actual IP address and port number.)*
{% endstep %}

{% step %}
**Log In to the Dashboard**

Use the following default credentials to log in:

* **Username**: `admin`
* **Password**: `admin`
  {% endstep %}

{% step %}
**Update Your Credentials**

After logging in, navigate to the **Settings** page to change the default credentials for security purposes.
{% endstep %}
{% endstepper %}

## Congratulations 🎉✨

You have successfully set up the SunLicense server.


# VPS Setup

{% embed url="<https://youtu.be/objpAGzFlgM?t=219>" fullWidth="true" %}
SunLicense Server Setup VPS Guide (Without Pterodactyl)
{% endembed %}

## SunLicense VPS Setup Guide (Without Pterodactyl)

This guide will walk you through setting up SunLicense on a VPS without using Pterodactyl.

### Prerequisites

Before starting, ensure your VPS meets the following requirements:

* **Java 21+ installed**
* **A valid SunLicense license key**

### Installation Steps

#### 1. Upload Required Files

Transfer the following files to your VPS:

* `server.jar` (SunLicense server file)
* `license.txt` (Contains your license key)

You can use `scp` or an FTP client like FileZilla to upload these files to your VPS.

Example using `scp`:

```sh
scp server.jar license.txt user@your-vps-ip:/home/user/
```

#### 2. Start SunLicense Server

Navigate to the directory containing `server.jar` and `license.txt`, then execute the following command:

```sh
SERVER_PORT=25595 java -Dterminal.jline=false -Dterminal.ansi=true -jar server.jar
```

* Replace `25595` with the desired port number.
* Ensure the port is open in your firewall settings.

If Java 21+ is not installed, you can install it using:

```sh
sudo apt update
sudo apt install openjdk-21-jdk -y
```

#### 3. Verify Local Access

Once the server starts, you can access SunLicense from the VPS itself:

```sh
curl http://localhost:25595
```

Replace `25595` with your chosen port.

#### 4. Expose to the Internet (Optional)

If you want to access SunLicense from an external network, you need to configure a reverse proxy using Nginx.

**Install Nginx**

```sh
sudo apt install nginx -y
```

**Configure Nginx Proxy**

Create a new Nginx configuration file:

```sh
sudo nano /etc/nginx/sites-available/sunlicense
```

Add the following content:

```nginx
server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://localhost:25595;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
```

Save and exit (`CTRL + X`, then `Y`, then `Enter`).

**Enable the Configuration**

```sh
sudo ln -s /etc/nginx/sites-available/sunlicense /etc/nginx/sites-enabled/
```

Restart Nginx:

```sh
sudo systemctl restart nginx
```

Now, you can access SunLicense from `http://yourdomain.com`.

#### 5. Running on Port 80 (Alternative)

If you don't want to use Nginx, you can run SunLicense directly on port 80:

```sh
SERVER_PORT=80 java -Dterminal.jline=false -Dterminal.ansi=true -jar server.jar
```

> **Note:** This works only if no other services (like Nginx or Apache) are using port 80.

#### 6. Configure Firewall (If Required)

To allow external access, open the required ports:

```sh
sudo ufw allow 80/tcp
sudo ufw allow 25595/tcp
sudo ufw reload
```

#### 7. Keeping SunLicense Running

To keep SunLicense running even after closing the terminal, use `screen` or `tmux`:

**Using `screen`**

```sh
sudo apt install screen -y
screen -S sunlicense
SERVER_PORT=25595 java -Dterminal.jline=false -Dterminal.ansi=true -jar server.jar
```

Press `CTRL + A`, then `D` to detach. To resume, use:

```sh
screen -r sunlicense
```

**Using `tmux`**

```sh
sudo apt install tmux -y
tmux new -s sunlicense
SERVER_PORT=25595 java -Dterminal.jline=false -Dterminal.ansi=true -jar server.jar
```

Detach with `CTRL + B`, then `D`. Resume with:

```sh
tmux attach -t sunlicense
```

### Conclusion

SunLicense is now set up on your VPS without Pterodactyl. You can manage it manually or configure a systemd service for automatic startup. If you need a managed setup, consider [SunLicense Managed Hosting](https://docs.sunlicense.hapangama.com/services/managed-hosting).

For purchasing, visit: [SunLicense on BuiltByBit](https://builtbybit.com/resources/sunlicense-license-management-system.58359/).


# Dashboard

This guide provides detailed instructions for navigating and utilizing the core administrative functionalities within the SunLicense Web Dashboard, focusing on managing Products, Licenses, Blacklists,

{% embed url="<https://youtu.be/3JVEtzH3et4?si=p-s-Rn_cUD9HlLCt>" fullWidth="true" %}

## SunLicense Web Dashboard Administrator Guide

The **Web Dashboard** is the central interface for managing your license system.\
You can access it via your server address (e.g., `http://{serverip}:{port}`).\
Authentication is required, and access is restricted to users with the `ROLE_ADMIN` permission.

***

### 1. Product Management

The **Products** view allows you to define the software or resources that your license keys will validate against.

#### 1.1. Creating a Product

In the **"Create Products"** tab, you must define the foundational settings for all future licenses associated with this product:

| **Field**                    | **Description & Detail**                                                                                                                                              |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Name & Description**       | Standard identifier fields. Name is required and must be unique.                                                                                                      |
| **Product Type**             | Choose from: `MINECRAFT_JAVA_PLUGIN`, `WEB_APPLICATION`, `DISCORD_BOTS`, or `OTHER`. If `OTHER` is selected, an **Other Product Type** text field appears (required). |
| **Default Max IPs**          | Max number of unique IPs per license. `-1` = unlimited, `0` = none. Default: **5**.                                                                                   |
| **Default Max HWIDs**        | Max number of Hardware IDs per license. `-1` = unlimited, `0` = none. Default: **5**.                                                                                 |
| **Product Role Id**          | Discord Role ID assigned when a user redeems a license.                                                                                                               |
| **Product Purchase Role Id** | Discord Role ID marking a user as a purchaser (required for `/get-license` in Discord).                                                                               |
| **Product URL / Image URL**  | Used for display in the Customer Dashboard.                                                                                                                           |

***

#### 1.2. Managing and Updating Products

The **"Manage Products"** tab displays products in a grid:

* **Updating**: Edit properties such as default limits, roles, and names.
* **Deletion**:
  * Products with active licenses **cannot** be deleted.
  * Attempting deletion shows error:

    > `"Product has licenses, cannot delete"`

***

### 2. License Management

The **Licenses** view lets you generate, modify, and track license keys.

#### 2.1. Creating a License

The **"Create License"** tab handles key generation and assignment.

| **Field**                 | **Description & Detail**                                                                   |
| ------------------------- | ------------------------------------------------------------------------------------------ |
| **License Key**           | Auto-generated (masked `XXXX-XXXX-...`). Hover to view, click to copy.                     |
| **Product**               | Select a product; defaults for Max IPs/HWIDs auto-populate.                                |
| **License Type & Expiry** | Choose `PERMANENT` or `TEMPORARY`. Temporary requires duration or custom date.             |
| **Platform Details**      | Select platform (`SPIGOT`, `BUILT_BY_BIT`, `DISCORD`, `OTHER`) and enter Platform User ID. |
| **Owner Details**         | Provide User Discord ID & Username. If bot is active, a dropdown may be available.         |
| **Initial Data/Status**   | Set comma-separated IPs/HWIDs. Status defaults to `ACTIVE`.                                |
| **Discord DM Prompt**     | If Discord ID provided, you’ll be prompted to send key via DM.                             |

***

#### 2.2. Managing and Updating Licenses

In the **"Manage Licenses"** tab:

* **Search & Filter**: Search by keywords, product, user, etc.
* **Editing**:
  * Clicking a license opens an **Edit License Dialog**.
  * Update fields like owner info, platform, limits, or status.
* **Manual Data Management**:
  * Edit IP/HWID lists directly (comma-separated).
* **Status Updates**:
  * Set to `ACTIVE`, `EXPIRED`, `DEACTIVATED`, or `DELETED`.
* **Deletion**:
  * Available via Delete button in the Edit Dialog.
  * Prompts confirmation before permanent deletion via `licenseService.deleteLicense(id)`.

***

### 3. Blacklist Management

Blacklist Management prevents specific devices or IPs from validating licenses.

#### 3.1. Creating a Blacklist Entry

Use the **"Create Blacklist"** tab:

1. **Type**: Select `IP` or `HWID`.
2. **Data**: Input the IP or Hardware ID.
3. **Scope**:
   * `All Products`
   * `Specific Product` (dropdown required).
4. **Reason**: Required field explaining why the entry is added.

***

#### 3.2. Managing Blacklists

The **"Manage Blacklists"** tab displays all active blacklist entries:

* **Viewing**: See details including blocked data, scope, product ID, and reason.
* **Deleting**: Use Delete button → removes entry via `blacklistService.removeBlackList(id)`.

***

### 4. Viewing License Requests

The **Requests** view provides analytics and history for all license validation attempts.

#### 4.1. Filtering and Overview

* **Filters**: Search term, Product, User, and Date Range.
* **Status Badges**:
  * ✅ Successful (green)
  * ❌ Invalid License
  * 🚫 Spam / Rate Limited
  * 🔴 Blocked (shows `BlockReason`)

***

#### 4.2. Viewing Detailed Request Information

Clicking a request row opens a dialog with detailed request data:

* **License/Product Details**: Masked License Key, Product Version.
* **Device Identifiers**: IP, HWID, MAC Address.
* **System Environment**: OS Name/Version/Architecture, Java Version.
* **Result Data**: Request Date, Type, and Response Type.


# License API

## License Validation Request V1

<mark style="color:green;">`POST`</mark> `/api/v1/validate`

Api request that can be used to validate product license

**Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

| Name                          | Type   | Description                                | Type                                       |
| ----------------------------- | ------ | ------------------------------------------ | ------------------------------------------ |
| `licenseKey`                  | string | License Key of the User                    | <mark style="color:red;">Required</mark>   |
| `productId`                   | number | Product Id of the license                  | <mark style="color:red;">Required</mark>   |
| `hwid`                        | string | Hardware id of the device                  | <mark style="color:red;">Required</mark>   |
| `productVersion`              | string | Product Version                            | <mark style="color:green;">Optional</mark> |
| `ip`                          | string | Client-Provided IP Address                 | <mark style="color:green;">Optional</mark> |
| `macAddress`                  | string | MAC Address                                | <mark style="color:green;">Optional</mark> |
| `operatingSystem`             | string | Operating System of the device             | <mark style="color:green;">Optional</mark> |
| `operatingSystemVersion`      | string | OS Version of the device                   | <mark style="color:green;">Optional</mark> |
| `operatingSystemArchitecture` | string | CPU Architecture of the device (ARM / x86) | <mark style="color:green;">Optional</mark> |
| `javaVersion`                 | string | Java Version installed in the device       | <mark style="color:green;">Optional</mark> |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "message": "License validated",
    "status": 200,
    "timestamp": "2025-01-27T19:01:25.710+00:00"
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "message": "Max IPs reached",
    "status": 400,
    "timestamp": "2025-01-27T20:01:34.140+00:00"
}
```

{% endtab %}
{% endtabs %}

{% file src="/files/HI6MoXljT5OdsR0MMDOf" %}
Postman Collection
{% endfile %}


# Java API

SunLicenseAPI Integration Guide

### Prerequisites

* Java 8 or higher
* SunLicense Server API URL
* Product ID

### Project Setup

#### 1. Configure Maven Repository

Add the Sundevs repository to your `pom.xml`:

```xml
<repositories>
    <repository>
        <id>sundevs</id>
        <name>Sundevs Repository</name>
        <url>https://repo.hapangama.com/releases</url>
    </repository>
</repositories>
```

#### 2. Add Dependency

Include the SunLicenseAPI dependency in your `pom.xml`:

```xml
<dependencies>
    <dependency>
        <groupId>com.hapangama</groupId>
        <artifactId>SunLicenseAPI</artifactId>
        <version>1.0.3</version>
    </dependency>
</dependencies>
```

### Basic Integration

#### 1. Initialize the API

Create an instance of SunLicenseAPI with your license details:

```java
SunLicenseAPI api = SunLicenseAPI.getLicense(
    "YOUR-LICENSE-KEY",    // License key
    YOUR_PRODUCT_ID,       // Product ID (integer)
    "YOUR_VERSION",        // Product version
    "YOUR_API_URL"         // API endpoint
);
```

{% hint style="warning" %}
License Key cannot be hardcoded its different from license to license and **you have to write a logic to take license key from a config file** and pass as a parameter.
{% endhint %}

#### 2. Implement License Validation

Add basic license validation to your application:

```java
try {
    api.validate();
    System.out.println("License is valid");
} catch (IOException e) {
    System.out.println("License validation failed: " + e.getMessage());
    System.exit(1);
}
```

### Advanced Configuration

#### Custom IP Address Configuration

You can manually set the IP address for validation:

```java
// Option 1: Get public IP automatically
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.ipify.org"))
    .GET()
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String publicIP = response.body();
api.setIp(publicIP);

// Option 2: Set IP manually
api.setIp("YOUR.IP.ADDRESS");
```

#### Loading License from File

For production environments, load the license key from a file:

```java
SunLicenseAPI api = SunLicenseAPI.getLicenseFromFile(
    "path/to/license.txt",
    YOUR_PRODUCT_ID,
    "YOUR_VERSION",
    "YOUR_API_URL"
);
```

\
**Custom HWID**\
\
You can write your own implementation for HWID and pass it with the request.

```java
api.setHwid("YOUR-CUSTOM-HWID");
```

### Troubleshooting

Common issues and solutions:

1. **Connection Issues**
   * Verify API endpoint URL
   * Check network connectivity
   * Confirm firewall settings
2. **Validation Failures**
   * Verify license key format
   * Check product ID is correct
   * Confirm IP address restrictions
3. **Configuration Problems**
   * Ensure Java version compatibility
   * Check dependency versions

Remember to replace placeholder values (`YOUR-LICENSE-KEY`, `YOUR_PRODUCT_ID`, `YOUR_API_URL`) with your actual values from your SunLicense account.


# API V2

SunLicense API V2 provides a secure, RESTful interface for managing products, licenses, blacklists, license requests, and customers.

### Authentication & Intents

* **API Token:** All endpoints (except `/healthy`) require an API token in the request header:
  * `TOKEN: <your-api-token>`
* **Intents:** Each endpoint requires specific intents. If your token lacks the required intent, you will receive an error response with a list of accepted intents.

***

### Error Handling

All error responses follow this structure:

```json
{
  "message": "invalid token or missing required intent",
  "accepted_intents": ["PRODUCTS_READ", "PRODUCTS_READ_WRITE", ...]
}
```

* Always check the `message` and `accepted_intents` fields to understand why a request failed.

***

### Update (PUT) Operations Warning

**Important:**

> For every update (PUT) call, always perform a GET first and pass all fields (including unchanged ones) in your PUT request. Fields not included in the PUT body may be lost.

***

### Endpoints

#### 1. Health & Ping

**`GET /api/v2/healthy`**

* **Description:** Health check endpoint. No authentication required.
* **Response:**
  * `200 OK` — `"healthy"`

**`GET /api/v2/ping`**

* **Description:** Ping endpoint to test authentication.
* **Headers:**
  * `TOKEN: <api-token>`
* **Response:**
  * `200 OK` — `"pong"`
  * `401 Unauthorized` — Error response

***

#### 2. Product API

**`GET /api/v2/products`**

* **Intents:** `PRODUCTS_READ`, `PRODUCTS_READ_WRITE`, `ALL_READ`, `ALL_READ_WRITE`
* **Response:** List of products

**`GET /api/v2/products/{id}`**

* **Intents:** Same as above
* **Response:** Product object

**`POST /api/v2/products`**

* **Intents:** `PRODUCTS_READ_WRITE`, `ALL_READ_WRITE`
* **Body:**

```json
{
  "name": "Test Product",
  "description": "1",
  "productType": "OTHER",
  "productTypeOther": "Test Type",
  "defaultMaxIPs": 4,
  "defaultMaxHWIDs": 3
}
```

* **Note:** Do not include `id`, `createdDate`, or `updatedDate`.

**`PUT /api/v2/products/{id}`**

* **Intents:** Same as POST
* **Body:** All product fields (see GET response)
* **Warning:** See update warning above.

**`DELETE /api/v2/products/{id}`**

* **Intents:** Same as POST

**Sample Product Response:**

```json
{
  "id": 602,
  "name": "Test Product",
  "description": "1",
  "productType": "OTHER",
  "productTypeOther": "Test Type",
  "createdDate": "2024-11-16T09:54:23.048+00:00",
  "updatedDate": "2024-11-16T09:54:23.048+00:00",
  "defaultMaxIPs": 4,
  "defaultMaxHWIDs": 3,
  "roleId": null,
  "purchaseRoleId": null,
  "url": null,
  "imageUrl": null
}
```

***

#### 3. License API

**`GET /api/v2/licenses`**

* **Intents:** `LICENSES_READ`, `LICENSES_READ_WRITE`, `ALL_READ`, `ALL_READ_WRITE`

**`GET /api/v2/licenses/{id}`**

* **Intents:** Same as above

**`POST /api/v2/licenses`**

* **Intents:** `LICENSES_READ_WRITE`, `ALL_READ_WRITE`
* **Body:**

```json
{
  "productId": 1552,
  "licenseType": "TEMPORARY",
  "licensePlatform": null,
  "licensePlatformOther": "",
  "ownerPlatformId": "",
  "expiryDate": "2025-05-31T18:30:00.000+00:00",
  "maxIPs": 5,
  "maxHWIDs": 5,
  "ownerDiscordId": "754054589690544250",
  "ownerDiscordUsername": "kaxun",
  "notes": ""
}
```

* **Note:** Do not include `id`, `createdDate`, `updatedDate`, `customer`, or `licenseKey` (license key is generated automatically).

**`GET /api/v2/licenses/by-license-key/{licenseKey}`**

* **Intents:** Same as above
* **Description:** Get a single license by its license key
* **Response:** License object or 404 if not found

**`GET /api/v2/licenses/by-customer-email/{email}`**

* **Intents:** Same as above
* **Description:** Get all licenses associated with a customer email address
* **Response:** Array of license objects

**`GET /api/v2/licenses/by-platform/{platform}/{platformId}`**

* **Intents:** Same as above
* **Description:** Get all licenses for a specific platform and platform ID
* **Query Parameters:**
  * `productId` (optional): Filter by product ID
* **Path Parameters:**
  * `platform`: One of SPIGOT, FORGE, BUKKIT, BUILT\_BY\_BIT, SOURCE\_EXCHANGE, DISCORD, OTHER
  * `platformId`: The platform-specific user ID
* **Response:** Array of license objects

**`GET /api/v2/licenses/by-customer-id/{customerId}`**

* **Intents:** Same as above
* **Description:** Get all licenses for a specific customer ID
* **Response:** Array of license objects

**`GET /api/v2/licenses/by-product-id/{productId}`**

* **Intents:** Same as above
* **Description:** Get all licenses for a specific product
* **Response:** Array of license objects

**`GET /api/v2/licenses/by-discord-id/{discordId}`**

* **Intents:** Same as above
* **Description:** Get all licenses associated with a Discord user ID
* **Response:** Array of license objects

**`PUT /api/v2/licenses/{id}`**

* **Intents:** Same as POST
* **Body:** All license fields (see GET response)
* **Warning:** See update warning above.

**`DELETE /api/v2/licenses/{id}`**

* **Intents:** Same as POST

**Sample License Response:**

```json
{
  "id": 4353,
  "licenseKey": "U12BPHB1VO1CB73N773B",
  "productId": 1552,
  "licenseType": "TEMPORARY",
  "licensePlatform": null,
  "licensePlatformOther": "",
  "ownerPlatformId": "",
  "createdDate": "2025-06-15T15:00:37.243+00:00",
  "updatedDate": "2025-06-23T05:31:36.707+00:00",
  "expiryDate": "2025-05-31T18:30:00.000+00:00",
  "maxIPs": 5,
  "maxHWIDs": 5,
  "totalRequests": null,
  "ownerDiscordId": "754054589690544250",
  "ownerDiscordUsername": "kaxun",
  "licenseStatus": "EXPIRED",
  "hwids": [],
  "ips": [],
  "notes": "",
  "customer": { ... },
  "productIdString": "1552"
}
```

***

#### 4. Blacklist API

**`GET /api/v2/blacklists`**

* **Intents:** `BLACKLISTS_READ`, `BLACKLISTS_READ_WRITE`, `ALL_READ`, `ALL_READ_WRITE`

**`GET /api/v2/blacklists/{id}`**

* **Intents:** Same as above

**`POST /api/v2/blacklists`**

* **Intents:** `BLACKLISTS_READ_WRITE`, `ALL_READ_WRITE`
* **Body:**

```json
{
  "licenseDataType": "HWID",
  "data": "unique-hardware-id3",
  "isForAllProducts": true,
  "reason": "x"
}
```

* **Note:** Do not include `id`, `createdAt`, or `updatedAt`.

**`PUT /api/v2/blacklists/{id}`**

* **Intents:** Same as POST
* **Body:** All blacklist fields (see GET response)
* **Warning:** See update warning above.

**`DELETE /api/v2/blacklists/{id}`**

* **Intents:** Same as POST

**Sample Blacklist Response:**

```json
{
  "id": 1,
  "licenseDataType": "HWID",
  "data": "unique-hardware-id3",
  "isForAllProducts": true,
  "productId": null,
  "reason": "x",
  "createdAt": "2025-02-13T07:41:53.226+00:00",
  "updatedAt": "2025-02-13T07:41:53.226+00:00"
}
```

***

#### 5. License Request API

**`GET /api/v2/requests`**

* **Intents:** `REQUESTS_READ`, `ALL_READ`, `ALL_READ_WRITE`

**`GET /api/v2/requests/{id}`**

* **Intents:** Same as above

**Sample License Request Response:**

```json
{
  "id": 802,
  "licenseId": null,
  "licenseKey": "FE72URFX4RKWM38T0ARO",
  "productId": 602,
  "productVersion": "1.0.0",
  "ip": "0:0:0:0:0:0:0:1",
  "hwid": "unique-hardware-id7",
  "macAddress": "00:1A:2B:3C:4D:5E",
  "operatingSystem": "Windows",
  "operatingSystemVersion": "10",
  "operatingSystemArchitecture": "x64",
  "javaVersion": "17",
  "requestDate": "2025-01-27T17:28:13.173+00:00",
  "requestType": "Valid",
  "responseType": "Success",
  "blockReason": null,
  "notes": null,
  "remarks": null,
  "valid": true,
  "successful": true,
  "rateLimited": false,
  "blocked": false,
  "spam": false
}
```

***

#### 6. Customer API

**`GET /api/v2/customers`**

* **Intents:** `CUSTOMERS_READ`, `ALL_READ`, `ALL_READ_WRITE`

**`GET /api/v2/customers/{id}`**

* **Intents:** Same as above

**Sample Customer Response:**

```json
{
  "id": 503,
  "firstName": null,
  "lastName": null,
  "username": "chinezu_1221",
  "email": null,
  "phoneNumber": null,
  "profilePictureUrl": "https://cdn.discordapp.com/avatars/1203762369625464832/a_7a39928788f5ee51dd60b53a8f04ed4a.gif",
  "passwordHash": null,
  "role": null,
  "status": null,
  "createdAt": null,
  "lastLoginAt": null,
  "discordId": 1203762369625464832,
  "discordUsername": "chinezu_1221",
  "discordAvatarUrl": null,
  "discordAccessToken": null,
  "discordRefreshToken": null,
  "discordTokenExpiry": null,
  "spigotId": null,
  "spigotUsername": null,
  "forgeId": null,
  "forgeUsername": null,
  "bukkitId": null,
  "bukkitUsername": null,
  "builtByBitId": "477048",
  "builtByBitUsername": null,
  "sourceExchangeId": null,
  "sourceExchangeUsername": null,
  "ploymartId": null,
  "ploymartUsername": null,
  "modrinthId": null,
  "modrinthUsername": null,
  "curseforgeId": null,
  "curseforgeUsername": null,
  "notes": null
}
```

***

#### 7. License Validation API

**`POST /api/v2/validate`**

* **Intents:** `LICENSE_VALIDATE`, `ALL_READ_WRITE`
* **Body:** See v1 LicenseRequestController for request structure.
* **Response:** Same as v1 LicenseRequestController.

***

### Enum Values Used in API Models

#### ProductType (Product)

* `MINECRAFT_JAVA_PLUGIN`
* `MINECRAFT_JAVA_MOD`
* `MINECRAFT_BEDROCK_PLUGIN`
* `MINECRAFT_BEDROCK_MOD`
* `MINECRAFT_SERVER_SETUP`
* `WEB_APPLICATION`
* `DESKTOP_APPLICATION`
* `MOBILE_APPLICATION`
* `OTHER`

#### LicenseType (License)

* `TEMPORARY`
* `PERMANENT`

#### LicenseStatus (License)

* `ACTIVE`
* `EXPIRED`
* `DEACTIVATED`
* `DELETED`

#### LicensePlatform (License)

* `SPIGOT`
* `FORGE`
* `BUKKIT`
* `BUILT_BY_BIT`
* `SOURCE_EXCHANGE`
* `DISCORD`
* `OTHER`

#### LicenseDataType (Blacklist)

* `IP`
* `HWID`

#### ApiIntent (Token/Permissions)

* `PRODUCTS_READ`
* `PRODUCTS_READ_WRITE`
* `LICENSE_VALIDATE`
* `LICENSES_READ`
* `LICENSES_READ_WRITE`
* `BLACKLISTS_READ`
* `BLACKLISTS_READ_WRITE`
* `REQUESTS_READ`
* `CUSTOMERS_READ`
* `ALL_READ`
* `ALL_READ_WRITE`

***

### General Notes

* Always include the `TOKEN` header for all endpoints except `/healthy`.
* For all update (PUT) operations, always fetch the current object first and send all fields in your update request.
* Error responses will always include a `message` and a list of `accepted_intents`.
* Do not send fields like `id`, `createdDate`, `updatedDate`, or system-generated fields when creating new objects.
* For creating licenses, do not send the license key or customer object; these are handled by the system.

***

For further details or questions, contact the SunLicense [support team](https://dsc.gg/sundevs).


# BuiltByBit Automation

BuiltByBit SunLicense Integration Guide

### Step 1: Get the Webhook URL

1. Go to the **Integrations** page on SunLicense.
2. Select your product.
3. Copy the **Webhook URL**.
4. The webhook URL should be in the following format:

   ```
   {yourdomain}/api/v1/bbb/{productId}
   ```

### Step 2: Create a Placeholder in BuiltByBit

1. Navigate to the **Placeholders** page in BuiltByBit: [BuiltByBit Placeholders](https://builtbybit.com/resources/dashboard/placeholders)
2. Click on **Create New Placeholder**.
3. Set the placeholder name to something like:

   ```
   %%__MyProduct_License__%%
   ```
4. Set **Type** as `External License Key`.
5. Paste the copied **Webhook URL** in the URL field.
6. Copy the **Secret Key** from the SunLicense **Integrations** page.
7. Paste the secret key in BuiltByBit.
8. Save the placeholder in BuiltByBit.

### Step 3: Use the Placeholder in Your Product

1. When using SunLicense API with your product, assign the placeholder string to the license key variable.
2. Example usage in Java:

   ```java
   String key = "%%__MyProduct_License__%%";

   SunLicenseAPI api = SunLicenseAPI.getLicense(
       key,     // License key
       1,       // Product ID (integer)
       "1.0.0", // Product version
       "http://yourdomain.com/" // API endpoint
   );

   api.validate();
   ```

### Step 4: Automatic License Assignment

* When users download your product, BuiltByBit will automatically create a new license in SunLicense.
* The placeholder `%%__MyProduct_License__%%` will be replaced with the user's actual license key.
* The user's downloaded product will be validated automatically without requiring manual input of the license key.

Now your BuiltByBit product is successfully integrated with SunLicense for seamless license management!


# Discord Automation

Automate License Issuance with Discord Bot

### Overview

This guide explains how to automate license issuance in SunLicense using the Discord bot. Once a user receives the designated product-purchased role, they can claim a license key for that product without direct contact with you.

### Step 1: Assigning a Product Purchased Role in SunLicense

When creating a product in SunLicense, you can specify a **Product Purchased Discord Role ID**. This role should be given to users upon purchasing the product through your system or any other sales system.

#### If You Are Creating a New Product:

1. Go to the **Products** page in the SunLicense dashboard.
2. Click **Create Product**.
3. Enter all necessary product details.
4. Find the **Product Purchased Role ID** field.
5. Enter the **Discord Role ID** that represents users who have purchased this product.
6. Save the product.

#### If You Already Have an Existing Product:

1. Go to the **Products** page.
2. Click **Manage Products**.
3. Select the product you want to update.
4. Locate the **Product Purchased Role ID** field.
5. Enter or update the **Discord Role ID**.
6. Save the changes.

### Step 2: Assigning the Role to Users

* Ensure that your system (or any other sales platform) grants the **Product Purchased Role** to a user when they buy the product.
* This role acts as proof that the user has purchased the product.

### Step 3: License Claiming with `/get-license` Command

Once a user receives the **Product Purchased Role**, SunLicense will recognize them as a valid purchaser.

#### How Users Can Claim a License:

1. Join your Discord server.
2. Ensure they have the required **Product Purchased Role**.
3. Execute the `/get-license` command in the designated Discord channel.
4. SunLicense will automatically issue a license key for the product.
5. The user will receive their license key immediately.

### Notes

* The **Product Purchased Role** should be granted when a user buys the product.
* Users must have the correct role before executing `/get-license`.
* This automation removes the need for manual license distribution.

### Conclusion

By following this guide, you can streamline the license issuance process, allowing users to claim their licenses effortlessly via Discord. 🚀


# Minecraft Plugins

SunLicense Integration Guide for Minecraft Plugins

### Prerequisites

* Spigot/Paper development environment
* Maven or Gradle build system
* SunLicense API credentials
* Your product ID and license key

### Integration Steps

#### 1. Add Repository and Dependency

**For Maven (plugin.xml):**

```xml
<repositories>
    <repository>
        <id>sundevs</id>
        <name>Sundevs Repository</name>
        <url>https://repo.hapangama.com/releases</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.hapangama</groupId>
        <artifactId>SunLicenseAPI</artifactId>
        <version>1.0.3</version>
    </dependency>
</dependencies>
```

#### 2. Create License Manager Class

```java
public class LicenseManager {
    private final JavaPlugin plugin;
    private SunLicenseAPI licenseApi;

    public LicenseManager(JavaPlugin plugin) {
        this.plugin = plugin;
        setupLicense();
    }

    private void setupLicense() {
        // Save default config if it doesn't exist
        plugin.saveDefaultConfig();
        
        // Initialize license API
        licenseApi = SunLicenseAPI.getLicense(
            plugin.getConfig().getString("license.key"),
            602, // Your Product Id
            "1.1.0", // Your Product Version (Plugin Version)
            "YOUR_API_URL"
        );

    }

    public void validateLicense() {
        try {
            licenseApi.validate();
            plugin.getLogger().info("License validated successfully!");
        } catch (IOException e) {
            plugin.getLogger().severe("License validation failed: " + e.getMessage());
            Bukkit.getPluginManager().disablePlugin(plugin);
        }
    }
}
```

#### 3. Implement in Main Plugin Class

```java
public class YourPlugin extends JavaPlugin {
    private LicenseManager licenseManager;

    @Override
    public void onEnable() {
        // Initialize license manager
        licenseManager = new LicenseManager(this);
        
        // Validate license
        licenseManager.validateLicense();
        
        // Continue with plugin initialization if license is valid
        if (isEnabled()) {
            // Your plugin initialization code
        }
    }
}
```

#### 4. Create Default Config

Create `config.yml` in your plugin's resources folder:

```yaml
license:
  key: "YOUR-LICENSE-KEY"
```

#### 5. License Command Implementation (Optional)

```java
public class LicenseCommand implements CommandExecutor {
    private final LicenseManager licenseManager;

    public LicenseCommand(LicenseManager licenseManager) {
        this.licenseManager = licenseManager;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!sender.hasPermission("yourplugin.license")) {
            sender.sendMessage("§cNo permission!");
            return true;
        }

        if (args.length != 1) {
            sender.sendMessage("§cUsage: /license <key>");
            return true;
        }

        // Update license logic here
        return true;
    }
}
```

### Common Issues and Solutions

1. **Plugin Won't Enable**
   * Check if license key is properly configured
   * Verify product ID matches
   * Check server connectivity to license API
2. **License Validation Fails**
   * Confirm license key hasn't expired
   * Check if HWID matches
   * Verify IP restrictions
3. **Configuration Issues**
   * Ensure config.yml is properly formatted
   * Check if all required fields are present
   * Verify encoding is UTF-8

Need additional help? Contact support or check the [Java API Documentation](/api-documentation/java-api) for more details.


# Server Software

SunLicense Integration Guide for Minecraft Server Software

### Prerequisites

* Java Development Environment
* Maven/Gradle
* Your Minecraft server project
* SunLicense API credentials

### Integration Steps

#### 1. Add Dependencies

Add this to your `pom.xml`:

```xml
<repositories>
    <repository>
        <id>sundevs</id>
        <name>Sundevs Repository</name>
        <url>https://repo.hapangama.com/releases</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.hapangama</groupId>
        <artifactId>SunLicenseAPI</artifactId>
        <version>1.0.3</version>
    </dependency>
</dependencies>
```

#### 2. Create License Validator

```java
public class ServerLicenseManager {
    private final SunLicenseAPI licenseApi;
    private final Server server;

    public ServerLicenseManager(Server server, String licenseKey, int productId) {
        this.server = server;
        this.licenseApi = SunLicenseAPI.getLicense(
            licenseKey,
            productId,
            "1.0.0",
            "YOUR_API_URL"
        );
    }

    public boolean validateLicense() {
        try {
            licenseApi.validate();
            return true;
        } catch (IOException e) {
            server.getLogger().severe("License validation failed: " + e.getMessage());
            return false;
        }
    }
}
```

#### 3. Implement in Server Startup

```java
public class CustomServer {
    private ServerLicenseManager licenseManager;

    public void startServer() {
        // Initialize license manager
        licenseManager = new ServerLicenseManager(
            this,
            "YOUR-LICENSE-KEY",
            YOUR_PRODUCT_ID
        );

        // Validate license before server starts
        if (!licenseManager.validateLicense()) {
            System.err.println("Invalid license - Server startup aborted");
            System.exit(1);
        }

        // Continue with server startup
        initializeServer();
    }
}
```

### Best Practices

1. **Startup Validation**
   * Validate license before server initialization
   * Implement graceful shutdown on validation failure
   * Log validation status
2. **Regular Validation**
   * Implement periodic checks
   * Handle network issues gracefully
   * Cache validation results
3. **Error Handling**
   * Clear error messages
   * Proper logging
   * Graceful shutdown procedures

### Troubleshooting

1. **Startup Failures**
   * Check license key validity
   * Verify network connectivity
   * Confirm product ID
2. **Runtime Issues**
   * Monitor validation logs
   * Check for network problems
   * Verify license hasn't expired


# Minecraft Mods

SunLicense Integration Guide for Minecraft Mods

### Prerequisites

* Forge/Fabric mod development environment
* Gradle
* SunLicense API credentials

### Integration Steps

#### 1. Add Repository and Dependency

In your `build.gradle`:

```gradle
repositories {
    maven {
        url "https://repo.hapangama.com/releases"
    }
}

dependencies {
    implementation 'com.hapangama:SunLicenseAPI:1.0.3'
}
```

#### 2. Create License Manager

```java
public class ModLicenseManager {
    private final SunLicenseAPI licenseApi;
    private static final Logger LOGGER = LogManager.getLogger();

    public ModLicenseManager() {
        this.licenseApi = SunLicenseAPI.getLicense(
            "YOUR-LICENSE-KEY",
            YOUR_PRODUCT_ID,
            "1.0.0",
            "YOUR_API_URL"
        );
    }

    public boolean validateLicense() {
        try {
            licenseApi.validate();
            return true;
        } catch (IOException e) {
            LOGGER.error("License validation failed: " + e.getMessage());
            return false;
        }
    }
}
```

#### 3. Implement in Mod Main Class

```java
public class YourMod {
    private ModLicenseManager licenseManager;

    public void onInitialize() { // For Fabric
    // OR
    public void init(FMLCommonSetupEvent event) { // For Forge
        licenseManager = new ModLicenseManager();
        
        if (!licenseManager.validateLicense()) {
            LOGGER.error("Invalid license - Mod will not function!");
            // Disable mod functionality
            return;
        }
        
        // Continue with mod initialization
    }
}
```

### Best Practices

1. **Mod Loading**
   * Validate before initializing features
   * Provide clear feedback to users
   * Handle offline mode gracefully
2. **Feature Management**
   * Graceful feature disabling
   * Clear user communication
   * Cache validation results

### Common Issues

1. **Mod Loading Failures**
   * Verify license key
   * Check network connectivity
   * Confirm dependency inclusion
2. **Runtime Problems**
   * Monitor mod logs
   * Check for network issues
   * Verify license status


# Discord Bots

SunLicense Integration Guide for Discord Bots

### Prerequisites

* Node.js environment (for Discord.js)
* Your Discord bot project
* SunLicense API credentials

### Integration Steps

#### 1. Install Required Packages

```bash
npm install axios
```

#### 2. Create License Validator

```javascript
const axios = require('axios');

class LicenseValidator {
    constructor(licenseKey, productId) {
        this.licenseKey = licenseKey;
        this.productId = productId;
        this.apiUrl = 'YOUR_API_URL/api/v1/validate';
    }

    async validateLicense() {
        try {
            const response = await axios.post(this.apiUrl, {
                licenseKey: this.licenseKey,
                productId: this.productId,
                hwid: 'YOUR-HWID', // Optional
                productVersion: '1.0.0'
            });

            return response.status === 200;
        } catch (error) {
            console.error('License validation failed:', error.message);
            return false;
        }
    }
}
```

#### 3. Implement in Bot

```javascript
const { Client, GatewayIntentBits } = require('discord.js');
const LicenseValidator = require('./LicenseValidator');

const client = new Client({ 
    intents: [GatewayIntentBits.Guilds] 
});

const licenseValidator = new LicenseValidator('YOUR-LICENSE-KEY', YOUR_PRODUCT_ID);

client.once('ready', async () => {
    const isValid = await licenseValidator.validateLicense();
    if (!isValid) {
        console.error('Invalid license - Bot shutting down');
        client.destroy();
        process.exit(1);
    }
    console.log('Bot is ready!');
});

// Add periodic validation
setInterval(async () => {
    const isValid = await licenseValidator.validateLicense();
    if (!isValid) {
        console.error('License validation failed - Bot shutting down');
        client.destroy();
        process.exit(1);
    }
}, 24 * 60 * 60 * 1000); // Check every 24 hours

client.login('YOUR_BOT_TOKEN');
```

### Best Practices

1. **Startup Validation**
   * Validate before bot initialization
   * Implement graceful shutdown
   * Clear error logging
2. **Periodic Validation**
   * Regular license checks
   * Handle network issues
   * Graceful error handling
3. **Security**
   * Secure storage of license key
   * Environment variable usage
   * Proper error handling

### Common Issues

1. **Validation Failures**
   * Check license key validity
   * Verify network connectivity
   * Confirm product ID
2. **Runtime Issues**
   * Monitor bot logs
   * Check for API rate limits
   * Verify license status


# FiveM Projects

This guide walks through the process of implementing SunLicense license management in a FiveM resource.

### Prerequisites

* A FiveM server
* SunLicense API credentials
* Your product ID and license key

### Step 1: Set Up Basic Structure

Create a new file called `license_check.lua` in your resource's server folder:

```lua
-- license_check.lua
local SunLicenseValidator = {}
SunLicenseValidator.__index = SunLicenseValidator

-- Configuration
local CONFIG = {
    API_URL = "http://localhost:8080/api/v1/validate",
    LICENSE_KEY = GetConvar("sunlicense_key", "YOUR-LICENSE-KEY"),
    PRODUCT_ID = 602,  -- Replace with your product ID
    VERSION = "1.0.0"
}
```

### Step 2: Implement the Validator Class

Add the core validation functionality:

```lua
function SunLicenseValidator.new()
    local self = setmetatable({}, SunLicenseValidator)
    self.authenticated = false
    return self
end

function SunLicenseValidator:validate()
    -- Construct the payload according to SunLicense specifications
    local payload = json.encode({
        licenseKey = CONFIG.LICENSE_KEY,
        productId = CONFIG.PRODUCT_ID,
        productVersion = CONFIG.VERSION,
        hwid = self:getHWID(),
        macAddress = "",  -- Optional field
        operatingSystem = "",  -- Optional field
        operatingSystemVersion = "",  -- Optional field
        operatingSystemArchitecture = "",  -- Optional field
        javaVersion = ""  -- Optional field
    })

    PerformHttpRequest(CONFIG.API_URL, function(errorCode, resultData, headers)
        if errorCode == 200 then
            local success, data = pcall(json.decode, resultData)
            if success and data then
                if data.status == "valid" then
                    self.authenticated = true
                    print("^2[SunLicense] License validated successfully^0")
                else
                    print("^1[SunLicense] License validation failed^0")
                    Wait(5000)
                    os.exit()
                end
            end
        else
            print("^1[SunLicense] Failed to connect to license server^0")
            Wait(5000)
            os.exit()
        end
    end, 'POST', payload, {
        ['Content-Type'] = 'application/json',
        ['Content-Length'] = #payload
    })
end

-- Generate a unique hardware identifier
function SunLicenseValidator:getHWID()
    -- You can implement your own HWID generation logic here
    -- This is a simple example that combines server information
    local serverID = GetConvar("sv_licenseIdentifier", "")
    local port = GetConvar("endpoint_port", "")
    return string.format("fivem-server-%s-%s", serverID, port)
end
```

### Step 3: Initialize the License Check

Create an initialization file (`init.lua`):

```lua
-- init.lua
local validator = SunLicenseValidator.new()

AddEventHandler('onResourceStart', function(resourceName)
    if GetCurrentResourceName() ~= resourceName then return end
    
    Wait(1000) -- Wait for server to fully initialize
    validator:validateWithRetry(3)
end)
```

### Step 4: Configure Your Resource

Update your `fxmanifest.lua`:

```lua
fx_version 'cerulean'
game 'gta5'

author 'Your Name'
description 'Your Resource Description'
version '1.0.0'

server_scripts {
    'server/license_check.lua',
    'server/init.lua',
    -- Your other server scripts
}

-- Add your convar for the license key
convar_category 'Licensing' {
    "License Configuration",
    {
        { "License Key", "sunlicense_key", "CV_STRING", "Your SunLicense key" }
    }
}
```

### Best Practices

1. **License Key Security**
   * Store your license key in server.cfg
   * Never expose the key in client-side code
   * Regularly rotate keys if possible
2. **Error Handling**
   * Implement proper logging
   * Handle network timeouts
   * Provide clear error messages
3. **Validation Timing**
   * Validate on resource start
   * Implement periodic validation if needed
   * Use reasonable retry intervals

### Common Issues and Solutions

#### Network Connectivity Problems

```lua
-- Add this to your validation function
if not self:checkConnection() then
    print("^1[SunLicense] No network connection available^0")
    Wait(10000)
    return false
end
```

#### Invalid License Format

```lua
-- Add this validation check
function SunLicenseValidator:isValidLicenseFormat(key)
    -- Check for the format: XXXX-XXXX-XXXX-XXXX-XXXX
    return type(key) == "string" and key:match("^%w%w%w%w%-%w%w%w%w%-%w%w%w%w%-%w%w%w%w%-%w%w%w%w$") ~= nil
end
```

#### Failed Validation Response

```lua
-- Add this helper function
function SunLicenseValidator:handleValidationError(response)
    if response.error then
        print(string.format("^1[SunLicense] Validation error: %s^0", response.error))
        return false
    end
    return true
end
```


# PHP Projects

SunLicense Integration Guide for PHP Projects

### Prerequisites

* PHP 7.4 or higher
* Composer (optional)
* cURL extension enabled
* SunLicense API credentials

### Integration Steps

#### 1. Create License Validator Class

```php
<?php

class SunLicenseValidator {
    private string $licenseKey;
    private int $productId;
    private string $apiUrl;
    private string $version;

    public function __construct(string $licenseKey, int $productId, string $version = '1.0.0') {
        $this->licenseKey = $licenseKey;
        $this->productId = $productId;
        $this->version = $version;
        $this->apiUrl = 'YOUR_API_URL/api/v1/validate';
    }

    public function validate(): bool {
        $data = [
            'licenseKey' => $this->licenseKey,
            'productId' => $this->productId,
            'productVersion' => $this->version,
            'hwid' => $this->getHWID() // Optional
        ];

        $ch = curl_init($this->apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception('License validation failed: ' . $response);
        }

        return true;
    }

    private function getHWID(): string {
        // Implement your HWID generation logic here
        return 'YOUR-HWID';
    }
}
```

#### 2. Implementation Example

```php
<?php

require_once 'SunLicenseValidator.php';

try {
    $validator = new SunLicenseValidator(
        'YOUR-LICENSE-KEY',
        YOUR_PRODUCT_ID,
        '1.0.0'
    );

    if ($validator->validate()) {
        echo "License is valid!";
        // Continue with your application logic
    }
} catch (Exception $e) {
    die("License validation failed: " . $e->getMessage());
}
```

#### 3. Using with Framework (Laravel Example)

```php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class LicenseService
{
    private $validator;

    public function __construct()
    {
        $this->validator = new SunLicenseValidator(
            config('license.key'),
            config('license.product_id'),
            config('license.version')
        );
    }

    public function validateLicense()
    {
        // Cache result for 24 hours
        return Cache::remember('license_status', 86400, function () {
            return $this->validator->validate();
        });
    }
}
```

### Best Practices

1. **Error Handling**
   * Implement proper try-catch blocks
   * Log validation failures
   * Graceful error handling
2. **Caching**
   * Cache validation results
   * Implement proper cache invalidation
   * Handle offline scenarios
3. **Security**
   * Store license key in environment variables
   * Implement proper error logging
   * Secure API communication

### Common Issues and Solutions

1. **cURL Errors**
   * Verify cURL installation
   * Check SSL certificates
   * Confirm API endpoint accessibility
2. **Validation Failures**
   * Check license key validity
   * Verify product ID
   * Monitor API response codes


# Python Projects

SunLicense Integration Guide for Python Projects

### Prerequisites

* Python 3.6 or higher
* requests library (`pip install requests`)
* SunLicense API credentials

### Integration Steps

#### 1. Create License Validator Class

```python
import requests
from typing import Optional
import platform

class SunLicenseValidator:
    def __init__(self, license_key: str, product_id: int, version: str = "1.0.0"):
        self.license_key = license_key
        self.product_id = product_id
        self.version = version
        self.api_url = "YOUR_API_URL/api/v1/validate"

    def validate(self) -> bool:
        data = {
            "licenseKey": self.license_key,
            "productId": self.product_id,
            "productVersion": self.version,
            "hwid": self.get_hwid(),  # Optional
            "operatingSystem": platform.system(),
            "operatingSystemVersion": platform.version()
        }

        try:
            response = requests.post(
                self.api_url,
                json=data,
                headers={"Content-Type": "application/json"}
            )
            response.raise_for_status()
            return response.status_code == 200
        except requests.exceptions.RequestException as e:
            raise ValueError(f"License validation failed: {str(e)}")

    @staticmethod
    def get_hwid() -> str:
        # Implement your HWID generation logic here
        return "YOUR-HWID"
```

#### 2. Basic Implementation

```python
def main():
    try:
        validator = SunLicenseValidator(
            license_key="YOUR-LICENSE-KEY",
            product_id=YOUR_PRODUCT_ID,
            version="1.0.0"
        )

        if validator.validate():
            print("License is valid!")
            # Continue with your application
        else:
            print("License validation failed!")
            exit(1)
    except Exception as e:
        print(f"Error: {str(e)}")
        exit(1)

if __name__ == "__main__":
    main()
```

#### 3. Advanced Implementation (Using Decorators)

```python
from functools import wraps

def requires_license(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        validator = SunLicenseValidator(
            license_key="YOUR-LICENSE-KEY",
            product_id=YOUR_PRODUCT_ID
        )
        
        if validator.validate():
            return func(*args, **kwargs)
        else:
            raise ValueError("Invalid license")
    return wrapper

# Usage example
@requires_license
def protected_function():
    print("This function only runs with valid license")
```

### Best Practices

1. **Configuration Management**
   * Use environment variables
   * Implement configuration files
   * Secure credential storage

```python
# config.py
import os
from dotenv import load_dotenv

load_dotenv()

LICENSE_KEY = os.getenv("LICENSE_KEY")
PRODUCT_ID = int(os.getenv("PRODUCT_ID"))
API_URL = os.getenv("LICENSE_API_URL")
```

2. **Error Handling**
   * Implement proper exception handling
   * Log validation failures
   * Graceful degradation
3. **Performance**
   * Cache validation results
   * Implement retry mechanisms
   * Handle offline scenarios

### Common Issues

1. **Network Problems**
   * Implement timeout handling
   * Add retry logic
   * Handle offline mode
2. **Validation Failures**
   * Check license key format
   * Verify product ID
   * Monitor API responses


# JavaScript Projects

SunLicense Integration Guide for JavaScript Projects

### Prerequisites

* Node.js environment (for backend) or modern web browser (for frontend)
* npm or yarn package manager
* SunLicense API credentials

### Integration Steps

#### 1. Backend Implementation (Node.js)

```javascript
const axios = require('axios');

class SunLicenseValidator {
    constructor(licenseKey, productId, version = '1.0.0') {
        this.licenseKey = licenseKey;
        this.productId = productId;
        this.version = version;
        this.apiUrl = 'YOUR_API_URL/api/v1/validate';
    }

    async validate() {
        try {
            const payload = {
                licenseKey: this.licenseKey,
                productId: this.productId,
                productVersion: this.version,
                hwid: this.getHWID(), // Optional
                operatingSystem: process.platform,
                operatingSystemVersion: process.version
            };

            const response = await axios.post(this.apiUrl, payload, {
                headers: { 'Content-Type': 'application/json' }
            });

            return response.status === 200;
        } catch (error) {
            throw new Error(`License validation failed: ${error.message}`);
        }
    }

    getHWID() {
        // Implement your HWID generation logic here
        return 'YOUR-HWID';
    }
}

// Usage example
const validator = new SunLicenseValidator('YOUR-LICENSE-KEY', YOUR_PRODUCT_ID);
validator.validate()
    .then(() => console.log('License valid!'))
    .catch(error => console.error(error));
```

#### 2. Frontend Implementation (Browser)

```javascript
class SunLicenseValidator {
    constructor(licenseKey, productId, version = '1.0.0') {
        this.licenseKey = licenseKey;
        this.productId = productId;
        this.version = version;
        this.apiUrl = 'YOUR_API_URL/api/v1/validate';
    }

    async validate() {
        try {
            const payload = {
                licenseKey: this.licenseKey,
                productId: this.productId,
                productVersion: this.version,
                operatingSystem: navigator.platform,
                operatingSystemVersion: navigator.userAgent
            };

            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return true;
        } catch (error) {
            throw new Error(`License validation failed: ${error.message}`);
        }
    }
}
```

#### 3. Integration with Popular Frameworks

**Express.js Middleware**

```javascript
function licensingMiddleware(licenseKey, productId) {
    const validator = new SunLicenseValidator(licenseKey, productId);
    
    return async (req, res, next) => {
        try {
            await validator.validate();
            next();
        } catch (error) {
            res.status(403).json({ error: 'Invalid license' });
        }
    };
}

// Usage in Express app
app.use(licensingMiddleware('YOUR-LICENSE-KEY', YOUR_PRODUCT_ID));
```

**React Component**

```javascript
import React, { useState, useEffect } from 'react';

function LicenseProtectedApp({ licenseKey, productId, children }) {
    const [isValid, setIsValid] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
        const validator = new SunLicenseValidator(licenseKey, productId);
        validator.validate()
            .then(() => setIsValid(true))
            .catch(err => setError(err.message));
    }, [licenseKey, productId]);

    if (error) return <div>License Error: {error}</div>;
    if (!isValid) return <div>Validating license...</div>;
    return children;
}
```

### Best Practices

1. **Security**
   * Never expose license key in frontend code
   * Implement server-side validation
   * Use secure communication (HTTPS)
2. **Error Handling**
   * Implement proper error handling
   * Show user-friendly error messages
   * Log validation failures
3. **Performance**
   * Cache validation results
   * Implement retry mechanisms
   * Handle offline scenarios

### Common Issues and Solutions

1. **CORS Issues**
   * Configure proper CORS headers
   * Use proxy for API requests
   * Handle preflight requests
2. **Network Problems**
   * Implement timeout handling
   * Add retry logic
   * Cache validation results


# Lua Projects

SunLicense Integration Guide for Lua Projects

### Prerequisites

* Lua 5.1 or higher
* LuaSocket library
* JSON library (dkjson or similar)
* SunLicense API credentials

### Integration Steps

#### 1. Create License Validator

```lua
local socket = require("socket")
local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("dkjson")

local SunLicenseValidator = {}
SunLicenseValidator.__index = SunLicenseValidator

function SunLicenseValidator.new(licenseKey, productId, version)
    local self = setmetatable({}, SunLicenseValidator)
    self.licenseKey = licenseKey
    self.productId = productId
    self.version = version or "1.0.0"
    self.apiUrl = "YOUR_API_URL/api/v1/validate"
    return self
end

function SunLicenseValidator:validate()
    local payload = {
        licenseKey = self.licenseKey,
        productId = self.productId,
        productVersion = self.version,
        hwid = self:getHWID() -- Optional
    }

    local jsonPayload = json.encode(payload)
    local response = {}

    local _, code = http.request{
        url = self.apiUrl,
        method = "POST",
        headers = {
            ["Content-Type"] = "application/json",
            ["Content-Length"] = #jsonPayload
        },
        source = ltn12.source.string(jsonPayload),
        sink = ltn12.sink.table(response)
    }

    if code ~= 200 then
        error("License validation failed with code: " .. tostring(code))
    end

    return true
end

function SunLicenseValidator:getHWID()
    -- Implement your HWID generation logic here
    return "YOUR-HWID"
end
```

#### 2. Basic Implementation

```lua
local function main()
    local validator = SunLicenseValidator.new(
        "YOUR-LICENSE-KEY",
        YOUR_PRODUCT_ID,
        "1.0.0"
    )

    local success, err = pcall(function()
        return validator:validate()
    end)

    if success then
        print("License is valid!")
        -- Continue with your application
    else
        print("License validation failed: " .. tostring(err))
        os.exit(1)
    end
end

main()
```

#### 3. Integration with LOVE2D (Game Framework)

```lua
function love.load()
    validator = SunLicenseValidator.new(
        "YOUR-LICENSE-KEY",
        YOUR_PRODUCT_ID
    )
    
    success, err = pcall(function()
        return validator:validate()
    end)
    
    if not success then
        error_message = err
        love.event.quit()
    end
end

function love.draw()
    if error_message then
        love.graphics.print("License Error: " .. error_message, 10, 10)
    end
end
```

### Best Practices

1. **Error Handling**
   * Use pcall for error handling
   * Implement proper logging
   * Handle network timeouts
2. **Security**
   * Secure storage of license key
   * Implement HTTPS communication
   * Handle sensitive data carefully
3. **Performance**
   * Cache validation results
   * Implement retry logic
   * Handle offline scenarios

### Common Issues

1. **Network Problems**
   * Implement timeout handling
   * Add retry logic
   * Handle connection errors
2. **SSL/HTTPS Issues**
   * Configure proper SSL certificates
   * Handle HTTPS requirements
   * Verify API endpoint security
3. **JSON Parsing**
   * Handle malformed responses
   * Validate response format
   * Proper error handling


# Managed Hosting

Get your license server up and running with secure, reliable, and fully managed by our team.

<figure><img src="https://3109748106-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBwwOcTA6nKTPkkbFskVu%2Fuploads%2FWd67T7FCqvpygT2tnsdB%2FSunLicenseManaged.png?alt=media&amp;token=d84817fd-2eca-4a75-9efb-9fc06278b5bd" alt=""><figcaption></figcaption></figure>

{% embed url="<https://store.sundevs.net/l/sunlicense-mh>" fullWidth="false" %}
click above to purchase
{% endembed %}

***

### 💻 Managed Hosting Plans

#### **1. Managed Hosting – $2.50 / Month**

Ideal for starting quickly with zero hassle.

**Included Features:**

* ✅ Web Dashboard Hosting
* ✅ Automatic Regular Updates
* ✅ Automatic On-Demand Scaling
* ✅ Random Subdomain
* ✅ 3 Days of Backups
* ✅ Priority Support

**Limitations:**

* ❌ No Direct Access
* ❌ No SSL (HTTP only)

***

#### **2. Managed Hosting Plus – $5.00 / Month**

Perfect for full control and professional setup.

**Included Features:**

* ✅ Everything in Managed Hosting
* ✅ Link Custom Domain (`yourdomain.com`)
* ✅ Custom Subdomain
* ✅ SSL Certificate (HTTPS)
* ✅ 7 Days of Backups
* ✅ Uptime Monitoring
* ✅ Unlimited Backup Requests
* ✅ Priority Support

**Limitations:**

* ❌ No Direct Server Access

***

### ⚠️ Important Requirement

Both hosting plans **require a valid SunLicense license key** to activate and use the dashboard.


# Disaster Management

<figure><img src="https://mermaid.ink/img/pako:eNqFU01v2zAM_SuEThvgBLGdNIkPGxont3YI6u6wJT2otuwItUVPopZ5Qf775I-kHTpgOokfj-Tjk04sxUywiOUlHtMD1wSP670CdxJy1oddgpWgg1QFHIUiOGpUxdPHPuUOC6lOMVfQoIWytYAQ6CCglKlQRkCNmnj5-dwDYmvoqxEXiIbUOVwDbcC65BZYa8xsShfE7S7WgpMADiuevtgaco0VPHd3AzUvXEhlkOFRlcgzkPTUI1e7jeLPZV91LQ03JDTcO7p9iUQQOVoGtq7GgIl3MSriKUFi1d1AIbF1y6Jrcx1mqyVqSc01-iB-WGEuzdevY1dcWV4OEwPmkHHikGOZCT1kb3aPumk3JzO3Y5k3Xa8HYbD82c-_1eioVF6Lc0r1nDC1lcvnJFGBkdSyeKMdjEafeoneqOWc8E2YLjao8Zc0bfwLduHbQYHOWA1L7YzNMHZf5R3-Un_zP8x1oqHj8PLW_wAwj7lnUnGZucd6akN75pZQiT2L3DXj-mXP9urs8rglTBqVsoi0FR7TaIsDi3JeGmfZ2u1frCUvNK-u3pqr74jVBVLots8AF8opFaNVxKLpct4ls-jEfrEonPnjcDL3_eXUn4VBsPBYw6KRH8zGk9lyES7CaRBOgql_9tjvrr4_nkyW8_mNw0xvwmWwCDwmMkmo7_uP2P3H8x8oCCA2?type=png" alt=""><figcaption></figcaption></figure>


