Code Examples
Complete, working examples for common integration scenarios. Copy and adapt these to your needs.
Full Inventory Sync
Push your complete inventory to CTCGX. This example shows how to format items and handle the response.
const CTCGX_API_KEY = process.env.CTCGX_API_KEY;
const BASE_URL = 'https://api.ctcgx.com/api/v1';
async function syncInventory(items) {
const response = await fetch(`${BASE_URL}/inventory/sync`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${CTCGX_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
mode: 'overwrite',
items: items.map(item => ({
tcgplayerId: item.tcgplayerId,
quantity: item.quantity,
price: Math.round(item.price * 100), // Convert to cents
condition: item.condition,
finish: item.finish,
})),
}),
});
if (!response.ok) {
throw new Error(`Sync failed: ${response.status}`);
}
return response.json();
}
// Example usage
const myInventory = [
{ tcgplayerId: '12345', quantity: 4, price: 5.99, condition: 'NM', finish: 'nonfoil' },
{ tcgplayerId: '67890', quantity: 2, price: 12.99, condition: 'LP', finish: 'foil' },
];
syncInventory(myInventory)
.then(result => console.log('Sync complete:', result))
.catch(error => console.error('Sync failed:', error));Webhook Handler
Receive and verify webhook events from CTCGX. This example includes signature verification and event handling.
const crypto = require('crypto');
const express = require('express');
const app = express();
const WEBHOOK_SECRET = process.env.CTCGX_WEBHOOK_SECRET;
// Parse raw body for signature verification
app.use('/webhooks/ctcgx', express.raw({ type: 'application/json' }));
function verifySignature(payload, signature, secret) {
const [tPart, v1Part] = signature.split(',');
const timestamp = tPart.split('=')[1];
const expectedSig = v1Part.split('=')[1];
const signedPayload = `${timestamp}.${payload}`;
const computedSig = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(computedSig),
Buffer.from(expectedSig)
);
}
app.post('/webhooks/ctcgx', (req, res) => {
const signature = req.headers['x-ctcgx-signature'];
const payload = req.body.toString();
// Verify signature
if (!verifySignature(payload, signature, WEBHOOK_SECRET)) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Parse and handle the event
const event = JSON.parse(payload);
console.log('Received event:', event.event);
switch (event.event) {
case 'order.created':
console.log('New order:', event.data.order.orderNumber);
// Add to fulfillment queue
break;
case 'order.shipped':
console.log('Order shipped:', event.data.order.orderNumber);
// Update tracking in your system
break;
case 'inventory.low':
console.log('Low inventory:', event.data.listing.product.name);
// Send restock alert
break;
}
// Respond quickly
res.status(200).json({ received: true });
});
app.listen(3000);Quick Test with cURL
Test the API quickly from your terminal.
# Set your API key
export CTCGX_API_KEY="ctcgx_sk_test_..."
# Look up a product
curl "https://api.ctcgx.com/api/v1/products/lookup?source=tcgplayer&externalId=12345" \
-H "Authorization: Bearer $CTCGX_API_KEY"
# Add a listing
curl -X POST "https://api.ctcgx.com/api/v1/inventory" \
-H "Authorization: Bearer $CTCGX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"items": [{
"tcgplayerId": "12345",
"quantity": 4,
"price": 599,
"condition": "NM"
}]
}'
# Get your inventory
curl "https://api.ctcgx.com/api/v1/inventory" \
-H "Authorization: Bearer $CTCGX_API_KEY"