Next.js
App Router, route handlers. The SDK uses Node.js crypto, so the route handlers must run on the Node.js runtime (the default; it does not work on the Edge runtime).
Environment variables
bash
SIMPLEPAY_MERCHANT_ID_HUF=P123456
SIMPLEPAY_MERCHANT_KEY_HUF=secret-key
SIMPLEPAY_REDIRECT_URL=https://example.com/payment/backDon't give them a NEXT_PUBLIC_ prefix, or they end up in the browser.
Start a payment
ts
import { startPayment } from 'simplepay-js-sdk'
export const runtime = 'nodejs'
export async function POST(request: Request) {
const { orderId } = await request.json()
const order = await getOrder(orderId)
try {
const { paymentUrl } = await startPayment({
orderRef: order.ref,
total: order.total,
customerEmail: order.email,
})
return Response.json({ paymentUrl })
} catch (error) {
console.error('SimplePay start', error)
return Response.json({ error: 'Could not start the payment' }, { status: 502 })
}
}Back URL
tsx
import { getPaymentResponse } from 'simplepay-js-sdk'
export default async function PaymentReturn({ searchParams }: { searchParams: Promise<{ r?: string, s?: string }> }) {
const { r = '', s = '' } = await searchParams
let result
try {
result = getPaymentResponse(r, s)
} catch {
return <p>Invalid redirect.</p>
}
switch (result.event) {
case 'SUCCESS':
return <p>Thank you! We are processing your payment. (SimplePay ID: {result.transactionId})</p>
case 'FAIL':
return <p>Payment failed. SimplePay transaction ID: {result.transactionId}.</p>
case 'CANCEL':
return <p>You cancelled the payment.</p>
case 'TIMEOUT':
return <p>The payment timed out.</p>
}
}In Next.js 14 searchParams is not a Promise yet: use { searchParams }: { searchParams: { r?: string, s?: string } } without await.
IPN
ts
import { handleIpnRequest } from 'simplepay-js-sdk'
export const runtime = 'nodejs'
export async function POST(request: Request) {
const ipnBody = await request.text() // NOT request.json()
const incomingSignature = request.headers.get('Signature') ?? ''
let result
try {
result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!)
} catch (error) {
console.error('SimplePay IPN', error)
return new Response('Invalid signature', { status: 400 })
}
const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string }
if (ipn.status === 'FINISHED') {
await markOrderPaid(ipn.orderRef, ipn.transactionId) // make it idempotent
}
return new Response(result.responseBody, {
status: 200,
headers: { 'Content-Type': 'application/json', 'Signature': result.signature },
})
}Don't use Response.json(...) for the IPN answer: it would serialize the text again.
If you use middleware (for example for login checks), exclude the IPN route from it.
Several currencies: IPN – Multiple currencies.
