---
url: https://simplepay.webmania.cc/en/recipes/nuxt.md
description: >-
  SimplePay integration in Nuxt 3 / Nuxt 4 with Nitro server routes: start a
  payment, handle the back URL, receive the IPN with readRawBody. Full example
  code.
---

# Nuxt / Nitro

This recipe works with Nuxt 3 and Nuxt 4 using Nitro server routes. The SDK uses Node.js `crypto` and `Buffer`, so it needs a Node.js runtime (the `node-server` preset, or `nodejs_compat` on Cloudflare).

The h3 helpers (`defineEventHandler`, `readBody`, `readRawBody`, `getHeader`, `setResponseHeader`, `createError`, `getQuery`) are auto-imported in Nuxt's server directory.

## Environment variables

```bash [.env]
SIMPLEPAY_MERCHANT_ID_HUF=P123456
SIMPLEPAY_MERCHANT_KEY_HUF=secret-key
SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back
```

The SDK reads `process.env` directly; you don't need `runtimeConfig`. In production set the variables in the server environment (Nuxt only loads `.env` in development).

## Start a payment

```ts [server/api/simplepay/start.post.ts]
import { startPayment } from 'simplepay-js-sdk'

export default defineEventHandler(async (event) => {
  const { orderId } = await readBody<{ orderId: string }>(event)
  const order = await getOrder(orderId) // from your database

  try {
    const response = await startPayment({
      orderRef: order.ref,
      total: order.total,
      customerEmail: order.email,
      invoice: order.invoice,
    })
    return { paymentUrl: response.paymentUrl }
  } catch (error) {
    console.error('SimplePay start', error)
    throw createError({ statusCode: 502, statusMessage: 'Could not start the payment' })
  }
})
```

On the client:

```vue
<script setup lang="ts">
const pay = async (orderId: string) => {
  const { paymentUrl } = await $fetch('/api/simplepay/start', { method: 'POST', body: { orderId } })
  await navigateTo(paymentUrl, { external: true })
}
</script>
```

## Back URL

`SIMPLEPAY_REDIRECT_URL` points to a Nuxt page (`/payment/back`). Verification runs on the server because it needs the secret key.

```ts [server/api/simplepay/result.get.ts]
import { getPaymentResponse } from 'simplepay-js-sdk'

export default defineEventHandler((event) => {
  const { r, s } = getQuery(event)
  if (typeof r !== 'string' || typeof s !== 'string') {
    throw createError({ statusCode: 400 })
  }

  try {
    const result = getPaymentResponse(r, s)
    return { event: result.event, orderRef: result.orderRef, transactionId: result.transactionId }
  } catch {
    throw createError({ statusCode: 400, statusMessage: 'Invalid redirect' })
  }
})
```

```vue [pages/payment/back.vue]
<script setup lang="ts">
const route = useRoute()
const { data, error } = await useFetch('/api/simplepay/result', {
  query: { r: route.query.r, s: route.query.s },
})
</script>

<template>
  <p v-if="error">Invalid redirect.</p>
  <p v-else-if="data?.event === 'SUCCESS'">Thank you! We are processing your payment. (SimplePay ID: {{ data.transactionId }})</p>
  <p v-else-if="data?.event === 'FAIL'">Payment failed. SimplePay transaction ID: {{ data.transactionId }}. Please check your card details or contact your bank.</p>
  <p v-else-if="data?.event === 'CANCEL'">You cancelled the payment.</p>
  <p v-else-if="data?.event === 'TIMEOUT'">The payment timed out.</p>
</template>
```

## IPN

The key point: **`readRawBody`**, not `readBody`. `readBody` parses the JSON and the signature won't match.

```ts [server/api/simplepay/ipn.post.ts]
import { handleIpnRequest } from 'simplepay-js-sdk'

export default defineEventHandler(async (event) => {
  const ipnBody = (await readRawBody(event, 'utf8')) ?? ''
  const incomingSignature = getHeader(event, 'signature') ?? ''

  let result
  try {
    result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!)
  } catch (error) {
    console.error('SimplePay IPN', error)
    throw createError({ statusCode: 400, statusMessage: 'Invalid signature' })
  }

  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
  }

  setResponseHeader(event, 'Content-Type', 'application/json')
  setResponseHeader(event, 'Signature', result.signature)
  return result.responseBody // as a string, unchanged
})
```

IPN URL in the SimplePay admin: `https://example.com/api/simplepay/ipn`.

::: tip Why does `return result.responseBody` work?
When an h3 handler returns a string, Nitro sends it unchanged. Don't return an object: Nitro would serialize it again.
:::

Choosing the key for several currencies: [IPN – Multiple currencies](../guide/ipn#multiple-currencies).

## Scheduled recurring charges

Call `startTokenPayment` from a Nitro scheduled task (experimental, `nitro.experimental.tasks`) or an external cron. See [Recurring payments](../guide/recurring-payments#_3-charging-a-token).
