Skip to content

About

TypeScript SDK for Transbank Webpay Plus with first-class Next.js App Router support

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

webpay-next

TypeScript SDK for Transbank Webpay Plus with first-class Next.js App Router support.

Built for Chilean e-commerce teams that don't want to wrap a 10-year-old SDK in a 200-line shim every time they ship a Next.js app. Tiny, typed, ESM/CJS dual, zero runtime deps, Edge-runtime friendly.

npm license node


Why webpay-next

transbank-sdk (official) webpay-next
Typed responses Partial (untyped JSON) Full TypeScript, camelCase
State model Static mutable class config Per-instance new WebpayClient(...)
Framework hooks Express examples only Next.js Route Handler + Server Action helpers
Edge runtime Not officially supported Yes (uses fetch only)
Bundle CommonJS only, ~80 KB ESM + CJS, ~7 KB core, ~11 KB Next adapter
Runtime deps axios + axios-cookiejar-support + tough-cookie None
Webpay POST-redirect helper Roll your own Built in (buildRedirectHtml)

Honest disclaimers:

  • The official SDK has been around longer and has Oneclick / Webpay Mall coverage — webpay-next v0.1 is Webpay Plus only.
  • The official SDK is what Transbank's support team will recognise first; if you're running through certification with them, you may want to dual-write.

Install

npm install webpay-next
# or
pnpm add webpay-next
# or
bun add webpay-next
# or
yarn add webpay-next
  • Node: 18.17+ (needs global fetch)
  • Next.js (optional): 14, 15, or 16 — peer dep is optional, you only need it if you import from webpay-next/next
  • Module formats: ESM + CJS dual export, full .d.ts typings
  • Runtime deps: none

Quickstart (Next.js App Router)

1) Server Action that starts the payment

// app/checkout/actions.ts
"use server";
import { startPayment } from "webpay-next/next";

export async function pagar(formData: FormData) {
  return startPayment({
    environment: process.env.NODE_ENV === "production" ? "production" : "integration",
    commerceCode: process.env.WEBPAY_COMMERCE_CODE,
    apiKey: process.env.WEBPAY_API_KEY,
    buyOrder: String(formData.get("buyOrder")),
    sessionId: String(formData.get("sessionId")),
    amount: Number(formData.get("amount")),
    returnUrl: "https://tu-sitio.cl/api/webpay/return",
  });
}

Wire it to a <form action={pagar}>. The action returns an HTML page that auto-POSTs the user into Transbank — redirect() won't work because Webpay requires POST, not GET.

2) Route handler for the return

// app/api/webpay/return/route.ts
import { createWebpayHandler } from "webpay-next/next";

const handler = createWebpayHandler({
  environment: process.env.NODE_ENV === "production" ? "production" : "integration",
  commerceCode: process.env.WEBPAY_COMMERCE_CODE,
  apiKey: process.env.WEBPAY_API_KEY,
  returnUrl: "https://tu-sitio.cl/api/webpay/return",
  onSuccess: async (tx) => {
    await marcarOrdenComoPagada(tx.buyOrder, tx.authorizationCode);
    return `/checkout/gracias?orden=${tx.buyOrder}`;
  },
  onCancel: () => "/checkout/cancelado",
});

export const GET = handler;
export const POST = handler;

That's the full Webpay Plus loop in ~25 lines.

Env vars

# .env.local
WEBPAY_COMMERCE_CODE=597055555532
WEBPAY_API_KEY=579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C

These are Transbank's public sandbox credentials. If environment === "integration" and you pass nothing, the SDK uses them automatically. In production, both are required — the SDK throws at construction time if missing.


Recipes

Refund a paid transaction

import { WebpayClient } from "webpay-next";

const wp = new WebpayClient({
  environment: "production",
  commerceCode: process.env.WEBPAY_COMMERCE_CODE!,
  apiKey: process.env.WEBPAY_API_KEY!,
});

const refund = await wp.refund(token, 19990);
// refund.type === "REVERSED" if same-day, "NULLIFIED" if after settlement.
// Partial nullifications are allowed up to the captured amount.

Check transaction status without committing

const status = await wp.status(token);
if (status.status === "AUTHORIZED") {
  // Already paid — safe to short-circuit a duplicate commit.
}

This is the right call to make from a webhook or cron that polls slow webhooks. commit() is single-use per token; status() is safe to call any number of times.

Typed error handling

import {
  WebpayApiError,
  WebpayValidationError,
  WebpayNetworkError,
} from "webpay-next";

try {
  await wp.commit(token);
} catch (e) {
  if (e instanceof WebpayApiError) {
    // Transbank rejected the request. e.status (HTTP), e.body (parsed JSON).
    console.error("webpay api error", e.status, e.body);
  } else if (e instanceof WebpayValidationError) {
    // Local validation: bad amount, missing token, returnUrl not http(s).
  } else if (e instanceof WebpayNetworkError) {
    // fetch threw — DNS, TCP, TLS, timeout. Safe to retry idempotently with status().
  } else {
    throw e;
  }
}

Deferred capture (auth now, charge later)

// 1) Auth — same as a normal create + commit, but your commerce code must
//    be provisioned for deferred capture by Transbank.
await wp.commit(token); // status: "AUTHORIZED", but not yet captured.

// 2) Capture later (up to ~7 days, ask Transbank for your window).
const cap = await wp.capture(token, {
  buyOrder: "ORD-001",
  authorizationCode: "123456",
  captureAmount: 19990,
});

Use the low-level client outside Next.js

import { WebpayClient, buildRedirectHtml } from "webpay-next";

const wp = new WebpayClient({ environment: "integration" });
const { token, url } = await wp.create({
  buyOrder: "ORD-001",
  sessionId: "sess-42",
  amount: 19990,
  returnUrl: "https://example.com/return",
});

// In Express/Hono/Fastify: respond with an auto-submit form.
res.send(buildRedirectHtml(url, token));

How it works

Customer browser              Your Next.js                Transbank
─────────────────             ─────────────               ──────────
form submit  ───►  Server Action `startPayment`
                       │
                       │  POST /transactions  (commerceCode + apiKey)
                       │ ─────────────────────────────────────────►
                       │ ◄───────────────────────────────────────── { token, url }
                       │
                   HTML auto-POST ◄── returned to browser
                       │
form auto-submits ─────────────────────────────────────────► Webpay payment UI
                                                              (cards, RUT, etc.)
                       ◄────────────────── 302 with token_ws ─────
Browser POSTs token_ws to your `returnUrl`
                       │
                Route handler `createWebpayHandler`
                       │  PUT /transactions/{token}   (commit)
                       │ ─────────────────────────────────────────►
                       │ ◄───────────────────────────────────────── TransactionResult
                       │
                  onSuccess(tx) → redirect to /gracias

Three things make the Next.js integration awkward without the helpers, and the SDK papers over them:

  1. Webpay requires POST redirect with token_ws in the body. next/navigation's redirect() only emits 307/308 GETs. startPayment returns an HTML body that auto-submits.
  2. Return URLs receive both GET (cancel) and POST (success). createWebpayHandler accepts the same handler for both verbs and figures out the right thing.
  3. Transbank speaks snake_case JSON. The client camelCases everything on its way out so your TS types match TS conventions.

API reference

webpay-next

Export Description
WebpayClient Stateless Webpay Plus client. Methods: create, commit, status, refund, capture.
WebpayClientOptions environment, commerceCode, apiKey, baseUrl, fetch, timeoutMs (default 30 s).
WebpayError, WebpayApiError, WebpayValidationError, WebpayNetworkError Typed error hierarchy.
BASE_URLS, INTEGRATION_CREDENTIALS Constants for the two environments.
Environment, CreateTransactionInput, TransactionResult, RefundResponse, CaptureInput, CaptureResponse, PaymentTypeCode, TransactionStatus Types.

webpay-next/next

Export Description
createWebpayHandler(opts) Returns a function usable as both GET and POST exports of a Route Handler.
startPayment(opts) Server Action helper. Returns an HTML Response that auto-POSTs to Webpay.
buildRedirectHtml(url, token) Lower-level helper if you want to roll your own response.
redirectToWebpay(url, token) Returns a Response ready to ship from any framework.

Re-exports everything from webpay-next so you don't need two imports.


Test cards (integration environment)

Card Number CVV Expiry
Visa (approved) 4051 8856 0044 6623 123 any future
Mastercard (declined) 5186 0595 5959 0568 123 any future
Redcompra (debit approved) 4051 8842 3993 7763 — —

On the Transbank form: RUT 11.111.111-1, password 123.


Troubleshooting / FAQ

Webpay POST /transactions failed: 401 Almost always wrong commerce code or wrong API key. Double-check you copied the secret from the Transbank portal exactly (no trailing whitespace) and that you haven't accidentally pointed environment at production while passing sandbox credentials.

commit() returns status: "FAILED" but no exception Webpay treats a declined card as a 200 OK with status and responseCode indicating the failure. Inspect tx.status (string) and tx.responseCode (number, 0 = approved, anything else = declined). Don't rely on try/catch alone.

Does it work in Edge runtime? Yes. The core client uses fetch only and the Next adapter doesn't touch Node-only APIs. Your onSuccess callback runs in the same runtime as the route, so if you write to a Node-only DB driver there you'll need export const runtime = "nodejs".

Why does startPayment return HTML instead of just redirecting? Webpay requires the browser to arrive at its UI by POST with token_ws in the form body. redirect() from next/navigation only emits GET-based 307/308. We return a tiny HTML page that auto-submits a hidden form — same pattern the official SDK uses internally.

I'm getting network request failed intermittently. Transbank's sandbox is occasionally slow. Bump timeoutMs (default 30 s) and use status(token) to recover idempotently — if the request actually went through, status will show the result.

Can I share one WebpayClient across requests? Yes. It's stateless. Construct it once at module scope.

Does this handle Oneclick / Webpay Mall? Not in v0.1. They're on the roadmap. For now, fall back to the official SDK for those flows.

Cross-origin cookies and same-site issues? Webpay redirects users between domains, so make sure any session cookie you depend on in onSuccess is SameSite=None; Secure or — better — pass the order context through buyOrder / sessionId and look it up from your DB.

Will the SDK detect duplicate commits? No, but Transbank does — calling commit(token) twice on the same token returns the original authorization. That said, prefer guarding with status() first so you don't depend on Transbank's behaviour.


Versioning

We follow semver. Until 1.0:

  • Patch (0.1.x) — bug fixes, doc tweaks.
  • Minor (0.x.0) — additive APIs (e.g. Oneclick support) and well-flagged breaking changes pre-1.0.
  • Major (1.0.0) — first stability commitment.

See CHANGELOG.md for the per-release diff.


Roadmap

  • Webpay Plus (create / commit / status / refund / capture)
  • Next.js App Router handler + Server Action helper
  • Edge runtime compatibility
  • Oneclick Mall (inscription + recurring charges)
  • Webpay Mall (multi-commerce)
  • Webhook helpers for async notification (POST /webhook signature verification)
  • Built-in idempotency key support
  • Hono / Fastify / Express adapters in webpay-next/<framework>

Contributing

PRs welcome:

  1. Open an issue first for non-trivial changes — the API surface is intentionally small.
  2. npm test && npm run typecheck must pass.
  3. Conventional commits preferred (feat:, fix:, chore:, docs:).
  4. Update CHANGELOG.md under ## Unreleased.

Local dev:

git clone https://github.com/freyesperales/webpay-next
cd webpay-next
npm install
npm test
npm run build   # tsup → dist/

License

MIT © Francisco Reyes

About

TypeScript SDK for Transbank Webpay Plus with first-class Next.js App Router support

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages