Braintree is PayPal's full-stack payments gateway. A single integration gives you PayPal, cards, Venmo, Apple Pay, Google Pay, ACH, and local payment methods. This guide uses the official braintree Node SDK (3.x) and the server-side PayPal flow.
Pick the right Braintree SDK
Braintree ships two server SDKs and PayPal ships a third. Don't mix them up:
braintree (this guide): the long-standing Braintree server SDK with a promise-based API, and what Braintree's Node docs use.
@braintree/graphql-client-node: a thin GraphQL client for the same gateway. Useful if you want to write GraphQL queries directly.
@paypal/paypal-server-sdk: the PayPal REST SDK (Checkout / Orders v2). Different product, different account, different API. Don't install it for a Braintree integration.
In Settings -> Processing, link your sandbox PayPal Business account so PayPal nonces flow through the same gateway as cards. Leave duplicate transaction checking enabled; it is on by default.
When you're ready, repeat with a production account and swap Environment.Sandbox for Environment.Production.
2. Install
bash
pnpm add braintree
bash
npm install braintree
bash
yarn add braintree
bash
bun add braintree
bash
pnpm add -D @types/braintree
bash
npm install --save-dev @types/braintree
bash
yarn add --dev @types/braintree
bash
bun add --dev @types/braintree
The braintree package ships no TypeScript declarations. The community @types/braintree package on DefinitelyTyped provides them; its version trails the SDK, so expect occasional gaps for newer fields.
3. Environment variables
.envbash
BRAINTREE_ENVIRONMENT=sandbox # or "production"BRAINTREE_MERCHANT_ID=use_your_merchant_idBRAINTREE_PUBLIC_KEY=use_your_public_keyBRAINTREE_PRIVATE_KEY=use_your_private_key
Public and private keys are both server-side secrets despite the names. Keep both out of client bundles.
4. Plugin
src/plugins/braintree.tsts
import braintree from "braintree";import type { App } from "@daloyjs/core";const gateway = new braintree.BraintreeGateway({ environment: process.env.BRAINTREE_ENVIRONMENT === "production" ? braintree.Environment.Production : braintree.Environment.Sandbox, merchantId: process.env.BRAINTREE_MERCHANT_ID!, publicKey: process.env.BRAINTREE_PUBLIC_KEY!, privateKey: process.env.BRAINTREE_PRIVATE_KEY!,});export interface BraintreeClient { gateway: braintree.BraintreeGateway; clientToken(customerId?: string): Promise<string>; sale(input: { amount: string; // decimal string from your order, e.g. "10.00" paymentMethodNonce: string; deviceData?: string; orderId: string; // also feeds Braintree's duplicate checking }): Promise<{ id: string; status: string; amount: string; currencyIsoCode: string }>; parseWebhook(signature: string, payload: string): Promise<braintree.WebhookNotification>;}// Exported so job handlers (which run outside a request) can use it too.export const braintreeClient: BraintreeClient = { gateway, async clientToken(customerId) { const res = await gateway.clientToken.generate(customerId ? { customerId } : {}); return res.clientToken; }, async sale(input) { const result = await gateway.transaction.sale({ amount: input.amount, paymentMethodNonce: input.paymentMethodNonce, deviceData: input.deviceData, orderId: input.orderId, options: { submitForSettlement: true }, }); if (!result.success) { // result.message and result.errors.deepErrors() carry the details; keep them in logs. throw Object.assign(new Error("Braintree sale failed"), { code: "BRAINTREE_SALE_FAILED", errors: result.errors?.deepErrors?.() ?? [], }); } const tx = result.transaction; return { id: tx.id, status: tx.status, amount: tx.amount, currencyIsoCode: tx.currencyIsoCode }; }, parseWebhook(signature, payload) { return gateway.webhookNotification.parse(signature, payload); },};// Call with the root app, not through app.register(): a decoration made// inside a registered plugin is visible only to that plugin's own routes.export function braintreePlugin(app: App) { app.decorate("braintree", braintreeClient);}declare module "@daloyjs/core" { interface AppState { braintree: BraintreeClient; }}
5. Generate a client token
Your browser SDK (Drop-in, Hosted Fields, Fastlane) needs a fresh client token to talk to Braintree. A token generated with a customerId exposes that customer's vaulted payment methods, so the id must come from the authenticated session, never from the request body. The route relies on the shared app wiring (session, scoped csrf() and rateLimit()).
src/routes/checkout-braintree.tsts
import { z } from "zod";import { UnauthorizedError } from "@daloyjs/core";import { braintreePlugin } from "../plugins/braintree.ts";import { orders } from "../orders.ts";import { db } from "../db.ts";braintreePlugin(app);app.post( "/checkout/client-token", { operationId: "createBraintreeClientToken", responses: { 200: { description: "ok", body: z.object({ clientToken: z.string() }) }, }, }, async ({ state }) => { const userId = state.session.get<string>("userId"); if (!userId) throw new UnauthorizedError("Sign in to check out."); // The Braintree customer id is stored on your user record, server-side. const user = await db.users.get(userId); return { status: 200, body: { clientToken: await state.braintree.clientToken(user?.braintreeCustomerId) } }; },);
With bearer tokens instead of cookie sessions, put jwk() or bearerAuth() on the route and read the user from ctx.state.user.
6. Create a transaction
Once the browser SDK returns a paymentMethodNonce (and, for fraud scoring, deviceData), submit a sale for the amount stored on the order. Braintree takes the amount as a decimal string; formatMinor() from the overview produces it without float rounding.
ts
import { formatMinor, toMinor } from "../money.ts";app.post( "/checkout/braintree", { operationId: "checkoutBraintree", request: { body: z.object({ orderId: z.string().min(1).max(127), paymentMethodNonce: z.string().min(1).max(512), deviceData: z.string().max(4_096).optional(), }).strict(), }, responses: { 201: { description: "transaction submitted", body: z.object({ id: z.string(), status: z.string() }) }, }, }, async ({ body, state }) => { const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId")); const tx = await state.braintree.sale({ amount: formatMinor(order.amountMinor, order.currency), // server-side total paymentMethodNonce: body.paymentMethodNonce, deviceData: body.deviceData, orderId: order.id, }); // The sale is synchronous: record it now. markPaid() still checks amount and currency. await orders.markPaid(order.id, { amountMinor: toMinor(tx.amount, tx.currencyIsoCode), currency: tx.currencyIsoCode, providerRef: tx.id, }); return { status: 201, body: { id: tx.id, status: tx.status } }; },);
Braintree's duplicate checking rejects a second successful-looking transaction with the same amount and payment method (and the same orderId, when you send one) inside a short window, which is 30 seconds by default, with gateway_rejected and reason duplicate. Treat it as a backstop; your own order state (and idempotency() on the route) is the primary guard. Each merchant account settles in one currency, so make sure the order currency matches the merchant account you charge.
For recurring charges that reuse a vaulted payment method while the customer is offline, swap paymentMethodNonce for paymentMethodToken and add transactionSource: "recurring". Braintree's built-in Recurring Billing sets this for you.
02noteDaloyJS routeDaloyJS routewebhookNotification.parse() verifies the signaturerejects tampered payloads
03responseDaloyJS routeBraintree401 when parse throws{ error: 'invalid signature' }
04asyncDaloyJS routeJob workerenqueue keyed by kind + subject + timestamp, then 200duplicate deliveries collapse into one job
The SDK verifies the signature for you, so reject parse failures with 401, dedupe on the notification's kind, subject id, and timestamp, and hand the work to a background job.
Braintree posts webhooks as application/x-www-form-urlencoded with two fields, bt_signature and bt_payload. webhookNotification.parse() verifies the signature and rejects tampered payloads; you don't hash anything yourself. Notifications carry no event id, so build the dedupe key from the kind, the subject's id, and the notification timestamp:
The worker refetches the subject (for example gateway.transaction.find(subjectId) or gateway.dispute.find(subjectId)) before acting, and registers in your single app.useJobs() call as described in the webhook pattern. Braintree expects a quick 2xx and retries failed deliveries, so keep the route itself fast.
Refunds
Expose refunds only through a protected refund route. The SDK call is gateway.transaction.refund(order.providerRef, formatMinor(amountMinor, order.currency)); a transaction that has not settled yet must be voided (gateway.transaction.void(id)) instead.
Errors & result objects
The SDK doesn't throw on declined transactions; it resolves with result.success === false and details under result.message, result.transaction.processorResponseCode, and result.errors.deepErrors(). The plugin turns the unsuccessful result into a thrown error that keeps the details for logs, so your problem+json mapper can return a stable message. Genuine network failures throw directly.
Runtimes
The braintree package uses Node's http/https modules and Buffer. It runs on Node hosts: long-lived Node, Vercel Node.js functions, AWS Lambda, and Azure Functions. It does not run on Cloudflare Workers or Vercel Edge; there, call the Braintree GraphQL API directly over fetch with HTTP Basic auth (public key + private key). Deno is not verified. See the runtime table.
Deprecation policy
Braintree publishes a server SDK deprecation policy describing how long each major version is supported. Pin a recent major in package.json and stay current; old SDKs lose support for new payment methods, new fields, and security fixes.