Skip to Content
Docs
Set up a new card

Tokenize a card

Collect card details from a customer, convert them into a secure token, and use the token to create a charge, hold, or stored payment method.

Tokenization combines client-side and server-side steps. Pay.com.js securely captures a customer's card details and converts them into a token, so sensitive card data never touches your servers. No payment is processed during tokenization.

Your server then sends the token to the Pay.com API to create a charge, place a hold on a payment, or store a payment method for future use.

Tokenization supports cards only. The only payment method type a tokenization session accepts is card. If you need 3D Secure authentication, you must handle it separately after tokenizing.

Requirements

Tokenization runs in the browser with Pay.com.js:

  • Install Pay.com.js and initialize it with your merchant ID: Pay.com({ identifier: 'YOUR_MERCHANT_ID' }).

Tokenize and use a card

Create a tokenization session on your server, tokenize the card in the browser, then use the token from your server.

  1. 1

    Create a tokenization session

    Tokenization uses a different session type than payment flows. On your server, call POST /v1/sessions/tokenization to get a client_secret and session id.

    const auth = Buffer.from(`:${process.env.PAY_COM_API_KEY}`).toString("base64");
    const response = await fetch("https://api.sandbox.pay.com/v1/sessions/tokenization", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Basic ${auth}`
      }
    });
    
    const session = await response.json();

    A successful response returns a client_secret, valid for 60 minutes, and the session id:

    {
      "id": "ts_217940156986951680",
      "resource": "tokenization_session",
      "client_secret": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
    }

    See the tokenization session API reference for full request and response details.

  2. 2

    Create a checkout instance

    On the frontend, pass the client_secret from your tokenization session to pay.checkout(). The onSuccess and onFailure callbacks are optional for tokenization because the token is returned directly from checkout.headless().

    const checkout = pay.checkout({
      clientSecret: session.client_secret,
    })
    ParameterTypeRequiredDescription
    clientSecretstringYesThe client_secret from the tokenization session.
    onSuccess(result) => voidNoOptional callback fired on success.
    onFailure(error) => voidNoOptional callback fired on failure.
  3. 3

    Collect card details and tokenize

    Build your own custom form to collect the customer's card details. When the customer submits the form, pass the values to checkout.headless(): the payment method type as the first argument, and the card data object as the second argument.

    try {
      const result = await checkout.headless('card', {
        number: '4111111111111111',
        cvv: '123',
        expirationMonth: '12',
        expirationYear: '28',
        name: 'Jane Smith',
      })
    } catch (error) {
      console.log('Tokenization failed:', error.message)
    }
    FieldTypeRequiredDescription
    numberstringYesCard number, no spaces or dashes.
    cvvstringYesCard security code.
    expirationMonthstringYesTwo-digit month, for example '12'.
    expirationYearstringYesTwo-digit year, for example '28'.
    namestringNoCardholder name as it appears on the card.

    A successful call resolves with an object containing a token that represents the customer's card details. If tokenization fails, checkout.headless() calls onFailure (if set) and rejects, so wrap it in try/catch. The resolved token looks like this:

    {
      "token": { "id": "tok_card_685104577720095744" },
      "type": "token"
    }

    Send the token to your server. Use it to create a charge, a hold, or a stored payment method for that customer.

  4. 4

    Use the token

    Use the tokenized card to create one of the following:

    To create a charge, pass the tokenized card object in source_data and send a POST request to /v1/charges (amount is in minor units, so 1000 is $10.00 USD). For the complete list of request parameters and responses, see the charges API reference.

    {
      "currency": "usd",
      "amount": 1000,
      "source_data": {
        "type": "token",
        "token": {
          "id": "tok_card_685104577720095744"
        },
        "billing_details": {
          "email": "jane.smith@example.com",
          "address": {
            "line1": "123 Main Street",
            "city": "San Francisco",
            "postal_code": "94102",
            "country": "US"
          },
          "phone": "+14155551234"
        }
      }
    }

    A charge returns one of three outcomes:

    OutcomeDescription
    succeededThe payment went through.
    requires_authenticationThe customer's bank requires 3DS verification before the charge can complete.
    Payment method errorThe card was declined or an error occurred.

    If a charge, hold, or payment method returns requires_authentication, the customer's bank is requesting additional verification before the transaction can complete. Follow the 3DS authentication flow to complete the verification. When you confirm manually (confirm: false), call the confirm endpoint for that resource: /v1/charges/{id}/confirm, /v1/holds/{id}/confirm, or /v1/payment_methods/{id}/confirm.

Complete example

The browser code initializes Pay.com.js, creates a checkout instance, and tokenizes the card:

import Pay from '@pay-com/js'

// 1. Initialize the SDK with your merchant ID (not the session ID)
const pay = await Pay.com({
  identifier: 'YOUR_MERCHANT_ID'
})

// 2. Create a checkout instance
const checkout = pay.checkout({
  clientSecret: session.client_secret,
})

// 3. Tokenize the card
const result = await checkout.headless('card', {
  number: '4111111111111111',
  cvv: '123',
  expirationMonth: '12',
  expirationYear: '28',
  name: 'Jane Smith',
})

console.log('Token:', result.token.id)

Next steps

Was this page helpful?