@moneydevkit/replit
v0.22.0
Published
Money Dev Kit checkout package for Replit (Vite + Express).
Downloads
2,059
Keywords
Readme
@moneydevkit/replit
Money Dev Kit checkout package tuned for Replit workspaces: Vite + React on the client and Express on the server.
Setup
- Create a Money Dev Kit account at moneydevkit.com (or run
npx @moneydevkit/createlocally) and grab yourapi_key,webhook_key, and mnemonic. - Install the SDK in your Replit project (Express is a peer dependency):
npm install @moneydevkit/replit express - Add required secrets to
.env(or Replit Secrets):MDK_ACCESS_TOKEN=your_api_key_here MDK_MNEMONIC=your_mnemonic_here
Backend: Express route
Mount the unified Money Dev Kit endpoint at /api/mdk:
// server/index.ts (or server.js)
import express from 'express'
import { createMdkExpressRouter } from '@moneydevkit/replit/server/express'
const app = express()
app.use('/api/mdk', createMdkExpressRouter())
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000')
})Frontend: Vite + React
Trigger a checkout from your client code (the checkout component pulls in its own CSS; import @moneydevkit/replit/mdk-styles.css once globally only if you want to preload it):
// src/App.tsx
import { useCheckout } from '@moneydevkit/replit'
import { useState } from 'react'
export default function App() {
const { createCheckout, isLoading } = useCheckout()
const [error, setError] = useState<string | null>(null)
const handlePurchase = async () => {
setError(null)
const result = await createCheckout({
type: 'AMOUNT', // or 'PRODUCTS' for product-based checkouts
title: 'Purchase title for the buyer',
description: 'Description of the purchase',
amount: 500,
currency: 'USD',
successUrl: '/checkout/success',
metadata: { name: 'John Doe' },
})
if (result.error) {
setError(result.error.message)
return
}
window.location.href = result.data.checkoutUrl
}
return (
<div>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button onClick={handlePurchase} disabled={isLoading}>
{isLoading ? 'Creating checkout…' : 'Buy Now'}
</button>
</div>
)
}Render the hosted checkout page:
// src/routes/checkout/[id].tsx (or similar)
import { Checkout } from '@moneydevkit/replit'
export default function CheckoutPage({ params }: { params: { id: string } }) {
return <Checkout id={params.id} />
}Customer Data
Collect and store customer information with each checkout. Pass customer to pre-fill data and requireCustomerData to prompt the user for specific fields:
const result = await createCheckout({
type: 'AMOUNT',
title: "Premium Plan",
description: 'Monthly subscription',
amount: 1000,
currency: 'USD',
successUrl: '/checkout/success',
// Pre-fill customer data (optional)
customer: {
name: 'John Doe',
email: '[email protected]',
},
// Require fields at checkout (shows form if not provided)
requireCustomerData: ['name', 'email', 'company'],
})How it works
- If all
requireCustomerDatafields are already provided incustomer, the form is skipped - If some required fields are missing, a form is shown to collect only those fields
- Email is required to create a customer record. Without email, customer data is attached to the checkout but no customer record is created
- Field names are flexible:
tax_id,tax-id,taxId, orTax IDall normalize totaxId - Custom fields (beyond
name,email,externalId) are stored in customer metadata
Returning customers
Customers are matched by email or externalId. When a match is found:
- Existing customer data is preserved and not overwritten
- Only missing fields from
requireCustomerDataare requested - All checkouts and orders are linked to the same customer record
Using externalId for authenticated users
When your user is already authenticated in your app, pass externalId to link checkouts to their account:
const result = await createCheckout({
type: 'AMOUNT',
title: "Premium Plan",
description: 'Monthly subscription',
amount: 1000,
currency: 'USD',
successUrl: '/checkout/success',
customer: {
externalId: user.id, // Your app's user ID
name: user.name,
email: user.email,
},
requireCustomerData: ['name', 'email'],
})When externalId is provided:
- The system assumes the user is authenticated
- If the customer already exists (matched by
externalId), their storednameandemailare used - Only fields missing from the customer record are requested
- This prevents authenticated users from being asked for data you already have
Product Checkouts
Sell products defined in your Money Dev Kit dashboard using type: 'PRODUCTS':
import { useCheckout, useProducts } from '@moneydevkit/replit'
function ProductPage() {
const { createCheckout, isLoading } = useCheckout()
const { products } = useProducts()
const handleBuyProduct = async (productId: string) => {
const result = await createCheckout({
type: 'PRODUCTS',
product: productId,
successUrl: '/checkout/success',
})
if (result.error) return
window.location.href = result.data.checkoutUrl
}
return (
<div>
{products?.map(product => (
<button key={product.id} onClick={() => handleBuyProduct(product.id)}>
Buy {product.name} - ${(product.price?.priceAmount ?? 0) / 100}
</button>
))}
</div>
)
}Checkout Types
type: 'AMOUNT'- For donations, tips, or custom amounts. Requiresamountfield.type: 'PRODUCTS'- For selling products. Requiresproductfield with a product ID. Amount is calculated from product price.
Note: Product prices are returned in base currency units:
- USD: cents (divide by 100 for dollars)
- SAT: satoshis (no conversion needed)
Pay What You Want (CUSTOM prices)
Products can have CUSTOM prices that let customers choose their own amount. When a checkout includes a product with a CUSTOM price, the checkout UI automatically shows an amount input field:
// Create a checkout for a product with CUSTOM pricing
const result = await createCheckout({
type: 'PRODUCTS',
product: customPriceProductId, // Product configured with CUSTOM price in dashboard
successUrl: '/checkout/success',
})The customer enters their desired amount during checkout. For USD, amounts are in dollars (converted to cents internally). For SAT, amounts are in satoshis.
Verify successful payments
import { useCheckoutSuccess } from '@moneydevkit/replit'
export function SuccessPage() {
const { isCheckoutPaidLoading, isCheckoutPaid, metadata } = useCheckoutSuccess()
if (isCheckoutPaidLoading || isCheckoutPaid === null) return <p>Verifying payment…</p>
if (!isCheckoutPaid) return <p>Payment has not been confirmed.</p>
return <p>Payment confirmed for {metadata?.name ?? 'customer'}.</p>
}This wiring keeps the client pointed at /api/mdk, which the Express route handles by delegating to the shared Money Dev Kit core logic.
L402: Pay-per-call API Endpoints
Gate any Express route behind a Lightning payment. See the Next.js README L402 section for the full protocol explanation and client integration examples.
Basic usage
import express from 'express'
import { withPayment } from '@moneydevkit/replit/server/express'
const app = express()
// withPayment wraps a fetch-style handler (Request -> Response)
const handler = async (req: Request) => {
return Response.json({ content: 'Premium data' })
}
// Mount it on an Express route by converting the Express req/res yourself,
// or use it directly in a fetch-compatible server.
app.all('/api/premium', async (req, res) => {
const fetchReq = new Request(`${req.protocol}://${req.get('host')}${req.url}`, {
method: req.method,
headers: new Headers(req.headers as Record<string, string>),
})
const response = await withPayment({ amount: 100, currency: 'SAT' }, handler)(fetchReq)
response.headers.forEach((v, k) => res.setHeader(k, v))
res.status(response.status).send(Buffer.from(await response.arrayBuffer()))
})Deferred settlement
Use withDeferredSettlement when your service delivery might fail and you want the payer to be able to retry:
import { withDeferredSettlement, type SettleResult } from '@moneydevkit/replit/server/express'
const handler = async (req: Request, settle: () => Promise<SettleResult>) => {
const result = await doExpensiveWork()
// Only mark as used after successful delivery
const { settled } = await settle()
if (!settled) {
return Response.json({ error: 'settlement_failed' }, { status: 500 })
}
return Response.json({ result })
}If your handler returns without calling settle(), the credential stays valid and the payer can retry.
