---
title: Save Venmo for purchase later with JavaScript SDK v6
description: Save a payer's Venmo account to a seller's vault with the v6 save
  payment session, so your platform or marketplace can charge it later.
---

# Save Venmo for purchase later with JavaScript SDK v6 (/platforms/checkout/save-payment-methods/purchase-later/js-sdk/venmo-v6)



Save a payer's Venmo account without a purchase, and receive a vault ID (payment token) to charge later. The payer approves in Venmo, and no money moves while you save.

This integration is for platforms and marketplaces that save Venmo accounts for their sellers. The vault belongs to the seller, and your server calls PayPal on the seller's behalf with the `PayPal-Auth-Assertion` header. For JavaScript SDK v5, see [Save Venmo for purchase later with JavaScript SDK v5](/platforms/checkout/save-payment-methods/purchase-later/js-sdk/venmo/). For a server-only integration, see [Save Venmo for purchase later with the Payment Method Tokens API](/platforms/checkout/save-payment-methods/purchase-later/payment-tokens-api/venmo/).

With this integration, you can:

* Receive a vault ID (payment token) and customer ID to store for your payer
* Reference the vault ID in a later order
* Save a payer's Venmo account at any point, without a purchase

## Availability [#availability]

Venmo is available only in the US.

## Prerequisites [#prerequisites]

Complete the following before you start:

1. Create a PayPal sandbox app (client ID and secret) with **Vault** enabled. In the Developer Dashboard, select your app, then go to **App Feature Options** > **Accept payments** > **Advanced options** > **Vault**.
2. Onboard a sandbox seller to your app. Get the seller's merchant ID, your BN code, and the seller's [PayPal-Auth-Assertion](/api/rest/requests/#paypal-auth-assertion).
3. Get a Venmo sandbox payer account. Venmo sandbox accounts aren't self-service. See [Venmo testing](/venmo/test).

To go live, [onboard your sellers](/platforms/checkout/save-payment-methods/onboarding/) and complete PayPal vetting to save Venmo accounts.

> **Warning:** PayPal requires Risk Data Acquisition (RDA) to reduce fraud. Collect device data with [FraudNet](/limited-release/fraudnet) and [Magnes](/limited-release/magnes). Send the client metadata ID (CMID) that FraudNet used in the `PayPal-Client-Metadata-Id` header on every customer-initiated transaction (CIT) that charges a saved Venmo payment token. When the payer isn't present, store the CMID from the session that collected the device data, and send it with the charge. A CMID with no matching FraudNet session doesn't link the charge to device data. Payment attempts without RDA data are likely to be declined because of insufficient risk identifiers.

## Key concepts [#key-concepts]

The following concepts explain how the v6 flow differs from v5.

### Auth assertion [#auth-assertion]

Send `PayPal-Auth-Assertion` (the seller) and `PayPal-Partner-Attribution-Id` (your BN code) on every PayPal call, so PayPal stores the vault with the seller. Vault objects resolve only under the assertion that created them. Any other lookup returns `404`.

### SDK initialization [#sdk-initialization]

Initialize the SDK with one of the following:

* **Client token (recommended):** Mint the token with the seller's assertion, so it already targets the seller. You don't need `merchantId`.
* **Client ID:** Pass your client ID and the seller's `merchantId` to `createInstance`. The flow works, but the SDK's `findEligibleMethods` method fails in this mode with `ERR_INIT_FIND_ELIGIBLE_METHODS`.

### Setup token and payment token [#setup-token-and-payment-token]

The `start()` method takes a Promise that resolves `{ vaultSetupToken }`. Your server creates the setup token inside that Promise. After the payer approves, your server exchanges the setup token for a payment token. The `id` of the payment token is the vault ID.

### The start method and onApprove [#the-start-method-and-onapprove]

Keep the following in mind when you call `start()` and handle `onApprove`:

* The `start()` method resolves when the setup token exists, not when the payer approves. Approval arrives in `onApprove`.
* The `onApprove` payload is `{ orderId, billingToken, payerId, fundingSource: "venmo" }`. The payload has no `vaultSetupToken`. The `orderId` value is the setup token, and the same value is in `session.vaultSetupToken`.
* Call `start()` synchronously in the click handler, and pass the Promise without `await`. Otherwise, the browser blocks the popup.

### Sandbox behavior [#sandbox-behavior]

Pass `sandboxSupport: { enabled: true }` to `start()` in the sandbox only. Without it, the desktop popup opens a generic PayPal error page and the SDK reports nothing. In the sandbox, the payer sees the Venmo web login in the popup. QR code and app switch aren't available.

## How it works [#how-it-works]

The integration follows this flow:

1. Your server mints a client token with the seller's assertion.
2. The page loads the SDK, calls `createInstance`, and creates the save session.
3. The payer selects the Venmo button, and the page calls `session.start()` with a Promise.
4. Your server creates the setup token inside that Promise with `POST /v3/vault/setup-tokens`.
5. The payer logs in to Venmo and approves.
6. The `onApprove` callback runs. Your server exchanges the setup token with `POST /v3/vault/payment-tokens` and stores the vault ID and customer ID.
7. Later, your server creates an order with the vault ID using `POST /v2/checkout/orders`.

## Set up your front end [#set-up-your-front-end]

Load the SDK, add the button, and create the save session. For more about SDK setup, see [Set up JavaScript SDK v6](/sdk/js/set-up).

### Load the SDK [#load-the-sdk]

Add the script for your environment. Use the sandbox script for testing:

```html
<script async src="https://www.sandbox.paypal.com/web-sdk/v6/core" onload="onSdkLoad()"></script>
```

For the live environment, use this script instead:

```html
<script async src="https://www.paypal.com/web-sdk/v6/core" onload="onSdkLoad()"></script>
```

### Add the button [#add-the-button]

Add the Venmo button element. Leave off the `type` attribute because no save label exists, and `type="pay"` renders **Pay with Venmo**.

```html
<venmo-button id="venmo-save-button" hidden></venmo-button>
```

### Initialize the SDK and create the session [#initialize-the-sdk-and-create-the-session]

Replace `BN-CODE` with your BN code. Remove `sandboxSupport` in the live environment.

```javascript
async function onSdkLoad() {
  const { clientToken } = await (await fetch("/api/client-token")).json();
  const sdkInstance = await window.paypal.createInstance({
    clientToken,
    partnerAttributionId: "BN-CODE",
    pageType: "checkout",
    components: ["venmo-payments"],
  });

  const session = sdkInstance.createVenmoSavePaymentSession({
    async onApprove() {
      // The payload has no vaultSetupToken. The session holds it.
      const res = await fetch("/api/vault/payment-token", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ vaultSetupToken: session.vaultSetupToken }),
      });
      if (!res.ok) throw new Error("Could not save the payment method");
      const { id, customerId } = await res.json();
      console.log("Vault ID:", id, "Customer ID:", customerId);
    },
    onCancel(data) {
      console.log("Payer canceled:", data);
    },
    onError(err) {
      console.error("Venmo error:", err.code, err.message);
    },
    onComplete({ paymentSessionState }) {
      // "approved", "canceled", or "error"
      console.log("Session ended:", paymentSessionState);
    },
  });

  const button = document.querySelector("#venmo-save-button");
  button.removeAttribute("hidden");
  button.addEventListener("click", async () => {
    try {
      await session.start(
        { presentationMode: "auto", sandboxSupport: { enabled: true } },
        createVaultSetupToken() // A Promise. Don't await it.
      );
    } catch (err) {
      console.error("Start error:", err);
    }
  });
}

async function createVaultSetupToken() {
  const res = await fetch("/api/vault/setup-token", { method: "POST" });
  if (!res.ok) throw new Error("Could not create the setup token");
  const { id } = await res.json();
  return { vaultSetupToken: id }; // The key must be vaultSetupToken.
}
```

To initialize with your client ID instead of a client token, replace the client token fetch and the `createInstance` call with the following. Replace `CLIENT-ID`, `MERCHANT-ID`, and `BN-CODE` with your values.

```javascript
const sdkInstance = await window.paypal.createInstance({
  clientId: "CLIENT-ID",
  merchantId: "MERCHANT-ID",
  partnerAttributionId: "BN-CODE",
  pageType: "checkout",
  components: ["venmo-payments"],
});
```

### Check eligibility [#check-eligibility]

Optional: Check whether Venmo is eligible for the save flow. This check requires a client token, and the result is informational. The Venmo flow doesn't enforce it.

```javascript
const methods = await sdkInstance.findEligibleMethods({
  currencyCode: "USD",
  paymentFlow: "VAULT_WITHOUT_PAYMENT",
});
const venmoEligible = methods.isEligible("venmo");
```

## Set up your back end [#set-up-your-back-end]

The following samples are ES modules. Save them in order as `server.mjs`, and run `node --env-file=.env server.mjs` with Node 20.6 or later. Install Express with `npm install express`. Keep the client secret and the assertion on the server, not in the browser.

### Set environment variables [#set-environment-variables]

Create a `.env` file with your values:

```bash
PAYPAL_CLIENT_ID=your_client_id
PAYPAL_CLIENT_SECRET=your_client_secret
PAYPAL_BN_CODE=your_bn_code
PAYPAL_AUTH_ASSERTION=the_sellers_auth_assertion_jwt
PORT=3000
```

### Get an access token [#get-an-access-token]

The `getAccessToken` function logs in with your client credentials and the seller's assertion. With `response_type: "client_token"`, it returns the client token for the front end. Without it, the function returns the access token for REST calls. Cache the access token until `expires_in`.

```javascript
import express from "express";
import { randomUUID } from "node:crypto";

const {
  PAYPAL_CLIENT_ID,
  PAYPAL_CLIENT_SECRET,
  PAYPAL_BN_CODE,
  PAYPAL_AUTH_ASSERTION, // The seller's PayPal-Auth-Assertion
  PORT = 3000,
} = process.env;

// For production, use https://api-m.paypal.com
const PAYPAL_BASE = "https://api-m.sandbox.paypal.com";

// Sent on every PayPal call so the vault belongs to the seller.
const SELLER = {
  "PayPal-Partner-Attribution-Id": PAYPAL_BN_CODE,
  "PayPal-Auth-Assertion": PAYPAL_AUTH_ASSERTION,
};

async function getAccessToken(extraParams = {}) {
  const res = await fetch(`${PAYPAL_BASE}/v1/oauth2/token`, {
    method: "POST",
    headers: {
      Authorization: `Basic ${Buffer.from(`${PAYPAL_CLIENT_ID}:${PAYPAL_CLIENT_SECRET}`).toString("base64")}`,
      "Content-Type": "application/x-www-form-urlencoded",
      ...SELLER,
    },
    body: new URLSearchParams({ grant_type: "client_credentials", ...extraParams }),
  });
  const data = await res.json();
  if (!res.ok) throw Object.assign(new Error("Access token request failed"), { status: res.status, details: data });
  return data.access_token;
}

async function paypal(path, { method = "POST", body, headers = {} } = {}) {
  const res = await fetch(`${PAYPAL_BASE}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${await getAccessToken()}`,
      "Content-Type": "application/json",
      ...(method === "POST" && { "PayPal-Request-Id": randomUUID() }),
      ...SELLER,
      ...headers,
    },
    ...(body && { body: JSON.stringify(body) }),
  });
  const text = await res.text();
  return { status: res.status, data: text ? JSON.parse(text) : {} };
}

const app = express();
app.use(express.json());

const route = (handler) => (req, res) =>
  handler(req, res).catch((err) => res.status(err.status ?? 500).json({ error: err.message, details: err.details }));

// Returns the client token for createInstance
app.get("/api/client-token", route(async (_req, res) => {
  res.json({ clientToken: await getAccessToken({ response_type: "client_token" }) });
}));
```

### Create a setup token [#create-a-setup-token]

The front end calls this route from the Promise it passes to `start()`. The route returns the setup token `id`.

The `return_url` and `cancel_url` fields are accepted only with `app_switch_context`. Placeholder URLs are fine. For an in-app flow, set `source` to `NATIVE_APP` and omit `buyer_user_agent`.

```javascript
app.post("/api/vault/setup-token", route(async (req, res) => {
  const userAgent = req.headers["user-agent"] ?? "";
  const { status, data } = await paypal("/v3/vault/setup-tokens", {
    body: {
      payment_source: {
        venmo: {
          usage_type: "MERCHANT",
          usage_pattern: "IMMEDIATE",
          customer_type: "CONSUMER",
          permit_multiple_payment_tokens: false,
          experience_context: {
            brand_name: "Merchant Store",
            shipping_preference: "NO_SHIPPING",
            user_action: "SETUP_NOW",
            return_url: "https://www.merchant.com/vault-return",
            cancel_url: "https://www.merchant.com/vault-cancel",
            app_switch_context: {
              source: /Mobi|Android|iPhone|iPad/i.test(userAgent) ? "MOBILE_WEB" : "DESKTOP_WEB",
              buyer_user_agent: userAgent, // The payer's own User-Agent. Don't hardcode it.
            },
          },
        },
      },
    },
  });
  res.status(status).json(data);
}));
```

### Create a payment token [#create-a-payment-token]

The `onApprove` callback calls this route. Store the `id` (the vault ID) and the `customer.id` for your payer. This `customer.id` differs from the one on the setup token. Keep this one.

```javascript
app.post("/api/vault/payment-token", route(async (req, res) => {
  const { status, data } = await paypal("/v3/vault/payment-tokens", {
    body: { payment_source: { token: { id: req.body.vaultSetupToken, type: "SETUP_TOKEN" } } },
  });
  if (status >= 400) return res.status(status).json(data);
  // Store data.id (the vault ID) and data.customer.id for your payer.
  res.json({ id: data.id, customerId: data.customer.id, userName: data.payment_source.venmo.user_name });
}));
```

### Charge the saved payment method [#charge-the-saved-payment-method]

Create an order that references the vault ID, with the same seller assertion. Send the CMID from the FraudNet session that collected the device data in the `PayPal-Client-Metadata-Id` header. The sandbox doesn't support subsequent purchases with saved Venmo tokens, so a sandbox charge can fail even when your integration is correct. See [Venmo testing](/venmo/test).

The default Create Order response is minimal and omits `purchase_units`. The `Prefer: return=representation` header in the following sample returns the full order. You can also call [Get Order](/api/orders/v2/orders-get). Before you fulfill the order, check that `purchase_units[0].payments.captures[0].status` is `COMPLETED`. An order status of `COMPLETED` can include a declined payment. For an order status of `APPROVED`, call `POST /v2/checkout/orders/{ORDER-ID}/capture`. To charge again later, create a new order with the same `vault_id`.

```javascript
app.post("/api/orders/charge-saved", route(async (req, res) => {
  const { status, data } = await paypal("/v2/checkout/orders", {
    body: {
      intent: "CAPTURE",
      purchase_units: [{ amount: { currency_code: "USD", value: "5.00" } }],
      payment_source: { venmo: { vault_id: req.body.vaultId } },
    },
    headers: {
      Prefer: "return=representation",
      // The CMID from the FraudNet session that collected the device data
      "PayPal-Client-Metadata-Id": req.body.cmid,
    },
  });
  res.status(status).json(data);
}));

app.listen(PORT, () => console.log(`Listening on ${PORT}`));
```

These routes are samples without payer authentication. In the live environment, authenticate the payer and read the vault ID and the CMID from your own records, not from the browser.

## Next steps [#next-steps]

Continue with the following:

* [Create an order](/api/orders/v2/orders-create) for subsequent or recurring transactions with the saved payment token.
* [Delete a payment token](/api/payment-tokens/v3#payment-tokens_delete) with the Payment Method Tokens API.
* [Test and go live](/sdk/js/production) with this integration.

## See also [#see-also]

* [Orders v2 API reference](/api/orders/v2)
* [Payment Method Tokens v3 API reference](/api/payment-tokens/v3)
