LogoNightPixel

Client API

NightPixel JavaScript Client API for game integration

NightPixel Client API

The NightPixel Client API allows you to integrate your game with the NightPixel platform, enabling authentication, user data access, wallet functionality, and seamless communication with NightPixel's backend services.

Overview

The NightPixel API provides a simple JavaScript client that handles:

  • Authentication: Automatic session token management from URL parameters
  • User Information: Access to player profiles and game data
  • Wallet Management: Token balance checking and deduction
  • Dynamic Purchasing: Flexible item purchasing with webhook-defined catalogs
  • Backend Communication: Secure API calls to NightPixel services
  • Global Access: Available as window.nightpixel

📘 Note

The NightPixel API is only accessible when your game is loaded within the NightPixel platform. Integration outside of the platform will result in authentication errors.

Installation & Loading

Including the Client

To use the NightPixel API in your game, include the client script in your HTML:

<script src="https://sdk.nightpixel.com/v1/client.js"></script>

Automatic Initialization

The client automatically initializes when the DOM is loaded:

// The API is automatically available after DOM load
document.addEventListener("DOMContentLoaded", () => {
  // API is now ready to use
  console.log("NightPixel API:", window.nightpixel);
});

API Reference

Global Objects

The API exposes itself through two global objects:

window.nightpixel;

Core Methods

bootstrap()

Initializes the API and extracts the session token from URL parameters. This is done automatically on page load

// Called automatically on DOM load
window.nightpixel.bootstrap();

What it does:

  • Extracts session token from URL query parameter np_game_auth_token
  • Sets up authentication for subsequent API calls

getGameAuthToken()

Returns the current session token used for authentication.

const token = window.nightpixel.getGameAuthToken();
console.log("Current session token:", token);

Returns: string - The session authentication token

isGuest()

Checks if the current user is a guest (not authenticated).

const isGuest = window.nightpixel.isGuest();
if (isGuest) {
  console.log("User is playing as a guest");
  // Handle guest user experience
} else {
  console.log("User is authenticated");
  // Handle authenticated user experience
}

Returns: boolean - true if user is a guest, false if authenticated

onReady(callback)

Registers a callback function to be executed when the NightPixel API is ready for use. If the API is already ready, the callback is executed immediately.

// Basic usage - wait for API to be ready
window.nightpixel.onReady(() => {
  console.log("NightPixel API is ready!");

  // Safe to make API calls now
  if (!window.nightpixel.isGuest()) {
    window.nightpixel.getUser().then((user) => {
      console.log("Welcome,", user.username);
    });
  }
});

// Alternative: Check if already ready
window.nightpixel.onReady(() => {
  // This will execute immediately if API is already initialized
  initializeGameUI();
});

Parameters:

  • callback (function): Function to execute when the API is ready

Usage Notes:

  • Always use onReady() before making API calls to ensure proper initialization
  • The callback executes immediately if the API is already ready
  • Multiple onReady() callbacks can be registered and will all execute

getUser()

Retrieves the current user's information from the NightPixel platform.

window.nightpixel
  .getUser()
  .then((user) => {
    console.log("User data:", user);
    console.log("Username:", user.username);
    console.log("User ID:", user.id);
  })
  .catch((error) => {
    console.error("Failed to get user:", error);
  });

Returns: Promise<Object> - User data object

Wallet API

The NightPixel API includes a built-in wallet system for managing in-game tokens and currencies.

wallet.hasBalance(token, amount)

Checks if the user has sufficient balance for a transaction (currently returns false - implementation pending).

const hasEnoughTokens = window.nightpixel.wallet.hasBalance(1, 100);
// Note: This method currently returns false and is not fully implemented

Dynamic Purchasing API

The Dynamic Purchasing API allows players to purchase virtual items without requiring pre-defined item catalogs. Your game dynamically defines items through webhook callbacks, enabling flexible in-game economies and real-time item generation.

purchaseItem(orderInfo)

Initiates a dynamic purchase by sending an order info string to your backend webhook, which defines the items to display to the user.

// Simple item purchase
window.nightpixel
  .purchaseItem({ orderInfo: "sword" })
  .then((response) => {
    console.log("Purchase initiated:", response);
    console.log("Order ID:", response.order_id);
    console.log("Items to purchase:", response.items);
    console.log("Total price:", response.total_price);

    // Show purchase confirmation dialog to user
    showPurchaseDialog(response.items, response.total_price, response.order_id);
  })
  .catch((error) => {
    console.error("Failed to initiate purchase:", error);
  });

**Parameters:**

- `orderInfo` (string): Identifier for the item(s) to purchase. This can be a simple string, item ID, or JSON string containing complex order data that your webhook understands.

**Returns:** `Promise<Object>` - Purchase response object

**Response Object:**

```javascript
{
  success: true,
  order_id: 12345,
  items: [
    {
      name: "Awesome Sword",
      description: "A really neat sword!",
      price: 10,
      image_url: "https://media.giphy.com/media/3o85xFGXZQIC29z74Q/giphy.gif"
    }
  ],
  total_price: 10
}

confirmPurchase(orderId)

Confirms a purchase after the user has reviewed the items and agreed to pay. This completes the transaction and awards the items to the player. This is done by the platform side and does n

// Confirm purchase after user approval
window.nightpixel
  .confirmPurchase(12345)
  .then((response) => {
    console.log("Purchase completed:", response);
    console.log("Order state:", response.state);
    console.log("New balance:", response.new_balance);

    if (response.state === "completed") {
      // Purchase successful - update game state
      showPurchaseSuccess();
      updatePlayerInventory();
      refreshBalanceDisplay();
    } else {
      // Purchase was canceled
      showPurchaseCanceled();
    }
  })
  .catch((error) => {
    console.error("Purchase confirmation failed:", error);
    showPurchaseError(error.message);
  });

Parameters:

  • orderId (number): The order ID returned from the purchaseItem() call

Returns: Promise<Object> - Confirmation response object

Response Object:

{
  success: true,
  order_id: 12345,
  state: "completed", // or "canceled"
  new_balance: 1390
}

Complete Purchase Flow Example

Here's a complete example of implementing dynamic purchasing in your game:

// Initialize purchase flow
async function buyItem(itemId) {
  try {
    // Step 1: Initiate purchase
    const purchaseResponse = await window.nightpixel.purchaseItem(itemId);

    // Step 2: Show items to user for confirmation
    const userConfirmed = await showPurchaseDialog(
      purchaseResponse.items,
      purchaseResponse.total_price
    );

    if (!userConfirmed) {
      console.log("User canceled purchase");
      return;
    }

    // Step 3: Confirm purchase
    const confirmResponse = await window.nightpixel.confirmPurchase(
      purchaseResponse.order_id
    );

    if (confirmResponse.state === "completed") {
      // Purchase successful
      showSuccessMessage("Item purchased successfully!");
      updateGameState();
    } else {
      // Purchase was canceled by server
      showErrorMessage("Purchase was canceled");
    }
  } catch (error) {
    console.error("Purchase error:", error);
    showErrorMessage("Purchase failed: " + error.message);
  }
}

// Example usage
document.getElementById("buy-sword").addEventListener("click", () => {
  buyItem("sword");
});

// Buy multiple items with complex order data
document.getElementById("buy-bundle").addEventListener("click", () => {
  const bundleOrder = {
    type: "bundle",
    items: ["sword", "shield", "potion"],
    discount: 0.1,
  };
  buyItem(JSON.stringify(bundleOrder));
});

🚧 Important

Dynamic purchasing requires your game to have a configured webhook endpoint that handles item_order_request and item_order_placed events. See the Dynamic Purchasing API documentation for webhook implementation details.

Parent Window Communication

The event system also enables communication with the parent NightPixel window through secure post-message events. These are handled automatically but can be customized:

parent-message

Fired when unknown messages are received from the parent window.

window.nightpixel.on("parent-message", (message) => {
  console.log("Custom parent message:", message);

  // Handle custom communication protocols
  if (message.type === "custom-game-command") {
    handleCustomCommand(message.data);
  }
});

Authentication

Session Token Flow

The NightPixel API uses session-based authentication:

  1. Token Injection: NightPixel injects a session token as the np_game_auth_token URL parameter when loading your game
  2. Automatic Extraction: The bootstrap() method extracts this token automatically
  3. Header Authentication: All API calls include the token in the NP-API-KEY header

Authentication Headers

// Automatically added to all API calls
headers: {
  "NP-API-KEY": sessionToken
}

Guest vs Authenticated Users

The API supports both guest and authenticated users:

if (window.nightpixel.isGuest()) {
  // Handle guest user - limited functionality
  console.log("Playing as guest");
  // Maybe show login prompt or limited features
} else {
  // Handle authenticated user - full functionality
  console.log("Authenticated user");
  // Access wallet, user data, etc.
}

Best Practices

Environment Variables

Make sure your game is configured with the correct session parameter handling based on your environment (development, staging, production).

Troubleshooting

Common Issues

Authentication Errors (401)

  • Ensure your game is loaded within the NightPixel platform
  • Check that the session token is being passed correctly in the URL as np_game_auth_token
  • Verify that bootstrap() has been called
  • Check if user is in guest mode using isGuest()

Wallet Operation Failures

  • Verify user is authenticated (not a guest)
  • Check token balance before attempting deductions
  • Handle insufficient balance scenarios gracefully

Network Errors

  • Check your internet connection
  • Verify that the NightPixel API endpoints are accessible
  • Ensure CORS is properly configured for your domain

API Not Available

  • Confirm the client script is loaded before your game code
  • Check browser console for script loading errors
  • Verify the script path is correct

Dynamic Purchasing Failures

  • Ensure your webhook endpoint is configured and accessible
  • Verify webhook returns proper JSON format for item_order_request events
  • Check that webhook handles both item_order_request and item_order_placed events
  • Validate order_info string format matches your webhook expectations
  • Ensure webhook responds within timeout limits (< 5 seconds)
  • Check that user has sufficient balance for the total purchase amount

Debug Mode

You can enable debug logging to troubleshoot issues:

// Check current session token
console.log("Session token:", window.nightpixel.getGameAuthToken());
console.log("Is guest:", window.nightpixel.isGuest());

// Test API connectivity
window.nightpixel
  .getUser()
  .then((user) => console.log("API working, user:", user))
  .catch((error) => console.error("API error:", error));

// Test wallet functionality
const hasBalance = window.nightpixel.wallet.hasBalance(1, 100);
console.log("Has sufficient balance:", hasBalance);

// Test dynamic purchasing functionality
window.nightpixel
  .purchaseItem("test-item")
  .then((response) => console.log("Purchase test:", response))
  .catch((error) => console.error("Purchase error:", error));

Ready to integrate your game with NightPixel? Start by including the client script and following the examples above. The wallet system provides powerful monetization opportunities through token-based economies. For additional support, check our developer resources or contact our support team.