TypeScript-first Node.js SDK for PlayCamp API integration
The official Node SDK (@playcamp/node-sdk) provides a type-safe way to integrate with the PlayCamp API. It handles authentication, pagination, retries, and error handling.
Installation
npm install @playcamp/node-sdk
Quick Start
import { PlayCampServer } from '@playcamp/node-sdk';
const server = new PlayCampServer('your_server_key:your_secret', {
environment: 'sandbox',
});
// Create a boost
const sponsor = await server.sponsors.create({
userId: 'user_12345',
creatorKey: 'ABC12',
});
// Register a payment
const payment = await server.payments.create({
userId: 'user_12345',
transactionId: 'txn_abc123',
productId: 'gem_pack_100',
amount: 9900,
currency: 'KRW',
platform: 'Android',
distributionType: 'MOBILE_STORE',
purchasedAt: new Date(),
});Client vs Server
The SDK provides two classes depending on your API key type:
| Class | API Key | Access | Use Case |
|---|---|---|---|
PlayCampClient |
Client Key | Read-only | Game client, public queries |
PlayCampServer |
Server Key | Read/Write | Game server, all operations |
import { PlayCampClient, PlayCampServer } from '@playcamp/node-sdk';
// Read-only access (Client Key)
const client = new PlayCampClient('your_client_key:your_secret');
// Full access (Server Key)
const server = new PlayCampServer('your_server_key:your_secret');Client Resources
| Resource | Methods |
|---|---|
campaigns |
listCampaigns(), listAllCampaigns(), getCampaign(), getCreators(), getPackages()
|
creators |
getCreator(), search()
|
coupons |
validate() |
sponsors |
getSponsor() |
Server Resources
| Resource | Methods |
|---|---|
campaigns |
listCampaigns(), listAllCampaigns(), getCampaign(), getCreators()
|
creators |
getCreator(), search(), getCoupons()
|
coupons |
validate(), redeem(), getUserHistory(), listAllUserHistory()
|
sponsors |
create(), getByUser(), update(), remove(), getHistory(), listAllHistory()
|
payments |
create(), getByTransactionId(), listByUser(), listAllByUser(), refund()
|
webhooks |
listWebhooks(), create(), update(), remove(), getLogs(), test()
|
Configuration
const client = new PlayCampClient('key:secret', {
environment: 'sandbox', // 'sandbox' | 'live' (default: 'live')
timeout: 30000, // Request timeout in ms (default: 30000)
isTest: false, // Enable test mode (default: false)
maxRetries: 3, // Max retry attempts (default: 3)
debug: true, // Enable debug logging (default: false)
});Environments
| Environment | URL | Purpose |
|---|---|---|
sandbox |
https://sandbox-sdk-api.playcamp.io |
Development/Testing |
live |
https://sdk-api.playcamp.io |
Production (default) |
You can also specify a custom URL directly:
const client = new PlayCampClient('key:secret', {
baseUrl: 'http://localhost:3003', // Overrides environment setting
});Pagination
List endpoints return paginated results:
// Get a single page
const { data, pagination, hasNextPage } = await client.campaigns.listCampaigns({
page: 1,
limit: 20,
});Use async iteration to automatically page through all results:
for await (const campaign of client.campaigns.listAllCampaigns()) {
console.log(campaign.campaignId);
}Error Handling
The SDK throws typed errors for different scenarios:
import {
PlayCampApiError,
PlayCampAuthError,
PlayCampNotFoundError,
PlayCampRateLimitError,
PlayCampNetworkError,
} from '@playcamp/node-sdk';
try {
await client.campaigns.getCampaign('invalid_id');
} catch (error) {
if (error instanceof PlayCampNotFoundError) {
console.log('Campaign not found');
} else if (error instanceof PlayCampAuthError) {
console.log('Invalid API key');
} else if (error instanceof PlayCampRateLimitError) {
console.log('Rate limited, retry after:', error.retryAfter);
} else if (error instanceof PlayCampNetworkError) {
console.log('Network error:', error.message);
} else if (error instanceof PlayCampApiError) {
console.log('API error:', error.code, error.message);
}
}
Webhook Verification
The SDK provides utilities for verifying incoming webhook signatures:
import { verifyWebhook } from '@playcamp/node-sdk';
app.post('/webhooks/playcamp', (req, res) => {
const result = verifyWebhook({
payload: req.rawBody,
signature: req.headers['x-webhook-signature'],
secret: 'your_webhook_secret',
tolerance: 300, // Max age in seconds (default: 300)
});
if (!result.valid) {
return res.status(401).json({ error: result.error });
}
for (const event of result.payload.events) {
switch (event.event) {
case 'coupon.redeemed':
console.log('Coupon redeemed:', event.data.couponCode);
break;
case 'payment.created':
console.log('Payment created:', event.data.transactionId);
break;
case 'sponsor.created':
console.log('Boost created:', event.data.userId);
break;
}
}
res.status(200).json({ received: true });
});For testing, you can generate signatures locally:
import { constructWebhookSignature } from '@playcamp/node-sdk';
const payload = JSON.stringify({
events: [{
event: 'coupon.redeemed',
timestamp: new Date().toISOString(),
data: { couponCode: 'TEST', userId: 'user_123', usageId: 1, reward: [] },
}]
});
const signature = constructWebhookSignature(payload, 'your_webhook_secret');See the Webhook Events page for more details on webhook event types and payloads.
Example Project
For a complete working example with Express server and Web UI covering all API endpoints, see the playcamp-node-sdk-example repository.
TypeScript Types
The SDK exports all types for use in your application:
import type {
Campaign,
Creator,
CouponValidation,
RedeemResult,
Sponsor,
Payment,
Webhook,
WebhookPayload,
} from '@playcamp/node-sdk';