Scrawn.js
Collect Payment
Generate checkout links to collect payments from users
Overview
The collectPayment method generates a checkout link for users to complete their payment. This integrates with your configured payment provider (e.g., LemonSqueezy) to handle the payment flow.
Basic Usage
import { Scrawn } from '@scrawn/core';
const scrawn = new Scrawn({
apiKey: process.env.SCRAWN_KEY as `scrn_${string}`,
baseURL: process.env.SCRAWN_BASE_URL || 'http://localhost:8069',
});
// Generate checkout link
const checkoutLink = await scrawn.collectPayment('user-123');
// Redirect user to payment page
res.redirect(checkoutLink);In simple terms: Give me a payment link for user user-123 where they can go and pay all their outstanding amount (which is being tracked by scrawn).
Parameters
userId (required)
- Type:
string - Description: The unique identifier of the user to collect payment from
- Validation: Must be a non-empty string
Response
- Type:
Promise<string> - Returns: A checkout URL where the user can complete their payment
Examples
Express.js Endpoint
import express from 'express';
import { Scrawn } from '@scrawn/core';
const app = express();
app.use(express.json());
const scrawn = new Scrawn({
apiKey: process.env.SCRAWN_KEY as `scrn_${string}`,
baseURL: process.env.SCRAWN_BASE_URL || 'http://localhost:8069',
});
app.post('/api/collect-payment', async (req, res) => {
try {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ error: 'userId is required' });
}
const checkoutLink = await scrawn.collectPayment(userId);
res.redirect(checkoutLink);
} catch (error) {
console.error('Failed to collect payment:', error);
res.status(500).json({ error: 'Failed to create checkout link' });
}
});Error Handling
try {
const checkoutLink = await scrawn.collectPayment(userId);
console.log('Checkout link created:', checkoutLink);
} catch (error) {
console.error('Error creating checkout link:', error);
// Handle error appropriately
}Best Practices
1. Validate User ID
Always validate the user ID before generating a checkout link:
if (!userId || typeof userId !== 'string' || userId.trim().length === 0) {
return res.status(400).json({ error: 'Valid userId is required' });
}
const checkoutLink = await scrawn.collectPayment(userId);2. Exclude from Tracking
Make sure to exclude the payment endpoint from usage tracking middleware:
app.use(scrawn.middlewareEventConsumer({
extractor: (req) => ({
userId: req.user.id,
debitAmount: 10,
}),
blacklist: ['/api/collect-payment'], // Don't charge for payment collection
}));