import express from 'express';
import { config } from 'dotenv';
import { createCreemDataFastClient, creemDataFastWebhook } from 'creem-datafast-integration';
config();
const app = express();
const CREEM_API_KEY = process.env.CREEM_API_KEY!;
const DATAFAST_API_KEY = process.env.DATAFAST_API_KEY!;
const CREEM_WEBHOOK_SECRET = process.env.CREEM_WEBHOOK_SECRET;
const creemClient = createCreemDataFastClient({
apiKey: CREEM_API_KEY,
});
// ---------- Landing page ----------
app.get('/', (_req, res) => {
res.send(`
CREEM + DataFast Integration Example
CREEM + DataFast Integration
This example demonstrates automatic revenue attribution between CREEM and DataFast.
How it works:
DataFast tracking script sets the datafast_visitor_id cookie
On checkout, the visitor ID is injected into CREEM metadata
When CREEM sends a webhook, payment data + visitor ID are forwarded to DataFast
Buy Now - $29.99
Product: Premium Plan
`);
});
// ---------- Checkout API ----------
app.use('/api', express.json());
app.post('/api/create-checkout', async (req, res) => {
try {
const { visitorId } = req.body;
const checkout = await creemClient.createCheckoutWithVisitorId(
{
productId: process.env.CREEM_PRODUCT_ID!,
successUrl: `${req.protocol}://${req.get('host')}/success`,
},
visitorId ?? null
);
res.json({
checkoutId: checkout.checkoutId,
checkoutUrl: checkout.checkoutUrl,
});
} catch (error) {
console.error('Checkout error:', error);
res.status(500).json({ error: 'Failed to create checkout' });
}
});
// ---------- Webhook ----------
// Use express.raw() so we get the raw body for signature verification.
app.post(
'/webhooks/creem',
express.raw({ type: 'application/json' }),
creemDataFastWebhook({
creemApiKey: CREEM_API_KEY,
datafastApiKey: DATAFAST_API_KEY,
webhookSecret: CREEM_WEBHOOK_SECRET,
onPaymentSuccess: async ({ creemEvent, datafastResponse }) => {
console.log('Payment forwarded to DataFast:', datafastResponse);
console.log('CREEM event type:', creemEvent.eventType);
},
onError: async (error) => {
console.error('Webhook processing error:', error.message);
},
})
);
// ---------- Success page ----------
app.get('/success', (_req, res) => {
res.send(`
Payment Successful
✓
Payment Successful!
Your payment has been recorded and revenue attributed to your traffic source.
Back to Home
`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/creem`);
});