Getting Started with the JavaScript SDK Invite Only

    Set up the Stripe Terminal JavaScript SDK and Verifone reader so you can begin accepting in-person payments.

    Setting up the JavaScript SDK requires just four steps:

    1. Set up the JavaScript SDK (via the SDK)
    2. Set up the connection token endpoint (SDK and backend)
    3. Initialize the SDK (SDK)
    4. Register and discover the reader (SDK and backend)

    After completing these steps, you can collect your first payment.

    Try out the example app

    The Stripe Terminal SDK includes an example React app, which you can use to familiarize yourself with the SDK before starting your own integration. The SDK also includes a reader simulator, so you can begin your integration before receiving a physical reader. To get started with the example app, navigate to our repo on [GitHub](https://github.com/stripe/example-terminal-js-client)

    Step 1: Set up the JavaScript SDK

    To get started, include this script on your pages—it should always be loaded directly from https://js.stripe.com:

    <script src="https://js.stripe.com/terminal/v1/sdk-b1.js"></script>

    Step 2: Set up the connection token endpoint

    To connect to a reader, the JavaScript SDK needs to retrieve a short-lived connection token from Stripe, proxied through your backend. On your backend, add an endpoint that creates a connection token and returns its value.

    curl https://api.stripe.com/v1/terminal/connection_tokens \
       -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \
       -X POST
    
    
    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    Stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    # Using Sinatra
    post 'terminal_connection_token' do
      token = Stripe::Terminal::ConnectionToken.create
      token.to_json
    end
    
    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    # Flask
    from flask import Flask, jsonify, request
    @app.route('terminal_connection_token', methods=['POST'])
    def terminal_connection_token():
        token = stripe.terminal.ConnectionToken.create()
        return jsonify(token)
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    var stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
    
    // Using Express
    app.post('terminal_connection_token', (req, res) => {
        var token = stripe.terminal.connectionTokens.create().then((token) => {
            res.status(200).json(token);
        }).catch((err) => {
            res.status(500).end();
        });
    });
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc";
    
    // Using Spark framework (http://sparkjava.com)
    post(new Route("terminal_connection_token") {
        @Override
        public Object handle(final Request request,
                             final Response response) {
            try {
                Map<String, Object> params = new HashMap<String, Object>();
                ConnectionToken token = ConnectionToken.create(params);
                return token.getRawJson();
            } catch (StripeException e) {
                response.status(500);
                return e;
            }
        }
    });
    
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.Key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
    
    // net/http
    func terminalConnectionTokenHandler(w http.ResponseWriter, r *http.Request, customerId string) {
        token, err := New(&stripe.TerminalConnectionTokenParams{})
        if err != nil {
            log.Printf("Stripe bindings call failed, %v
    ", err)
            w.WriteHeader(500)
            return
        }
        w.Write(token.RawJSON)
    }
    

    To give the SDK access to this endpoint when Stripe initializes it, create a function in your application that requests a connection token from your backend.

    /**
     * fetchConnectionToken() returns a Promise that asynchronously returns
     * a connection token as a string, e.g., "pst_test_xxxx"
     */
    function fetchConnectionToken() {
      // Your backend should call /v1/terminal/connection_tokens and return the JSON response from Stripe
      return fetch('https://{YOUR_BACKEND_URL}/terminal_connection_token', { method: "POST" }).then(response =>
        response.data.secret
      );
    }
    /**
     * fetchConnectionToken() returns a connection token as a string
     * e.g., "pst_test_xxxx"
     */
    async function fetchConnectionToken() {
      // Your backend should call /v1/terminal/connection_tokens and return the JSON response from Stripe
      const response = await fetch('https://{YOUR_BACKEND_URL}/terminal_connection_token', { method: "POST" });
      return response.data.secret;
    }

    This function is called whenever the SDK is initialized. It's also called when a new token is needed to connect to a reader (for example, when your app disconnects from a reader). If the SDK is unable to retrieve a new token from your backend, connecting to a reader fails with the error (also provided by your backend).

    Do not cache or hardcode the connection token. The JavaScript SDK manages the token's lifecycle.

    Step 3: Initialize the SDK

    The StripeTerminal object made available by the SDK exposes a generic interface for discovering readers, connecting to a reader, and creating payments. To initialize a StripeTerminal instance in your JavaScript client, provide the connection token function implemented in Step 2.

    var terminal = StripeTerminal.create({
      // fetchConnectionToken must be a function that returns a promise
      onFetchConnectionToken: fetchConnectionToken,
    });
    const terminal = StripeTerminal.create({
      // fetchConnectionToken must be a function that returns a promise
      onFetchConnectionToken: fetchConnectionToken,
    });

    Step 4: Register and discover the reader

    Before connecting to a reader for the first time, you'll need to register the device. Enter the key sequence 0-7-1-3-9 on the reader to display its unique registration code. Provide the code to Stripe:

    curl https://api.stripe.com/v1/terminal/readers \
      -u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \
      -d registration_code="{{READER_REGISTRATION_CODE}}" \
      -d label="Optional display name"
    

    To confirm that you've registered the device correctly, you can list all the readers you've registered:

    curl https://api.stripe.com/v1/terminal/readers \
      -u sk_test_4eC39HqLyjWDarjtT1zdp7dc:
    

    After you've registered the reader, call terminal.discoverReaders in your application to find and display readers to connect to:

    terminal.discoverReaders().then(function(discoverResult) {
      if (discoverResult.error) {
        console.log('Failed to discover: ', discoverResult.error);
      } else if (discoverResult.discoveredReaders.length === 0) {
        console.log('No available readers.');
      } else {
        // You should show the list of discoveredReaders to the
        // cashier here and let them select which to connect to (see below).
        connectReader(discoverResult);
      }
    });
    async () => {
      const discoverResult = await terminal.discoverReaders();
      if (discoverResult.error) {
        console.log('Failed to discover: ', discoverResult.error);
      } else if (discoverResult.discoveredReaders.length === 0) {
        console.log('No available readers.');
      } else {
        // You should show the list of discoveredReaders to the
        // cashier here and let them select which to connect to (see below).
        connectReader(discoverResult);
      }
    }

    To connect to a reader, call terminal.connectReader with the selected reader.

    function connectReader(discoverResult) {
      // Just select the first reader here.
      var selectedReader = discoverResult.discoveredReaders[0];
    
      terminal.connectReader(selectedReader).then(function(connectResult) {
        if (connectResult.error) {
          console.log('Failed to connect: ', connectResult.error);
        } else {
          console.log('Connected to reader: ', connectResult.connection.reader.label);
        }
      });
    }
    async function connectReader(discoverResult) {
      // Just select the first reader here.
      const selectedReader = discoverResult.discoveredReaders[0];
    
      const connectResult = await terminal.connectReader(selectedReader);
      if (connectResult.error) {
        console.log('Failed to connect:', connectResult.error);
      } else {
        console.log('Connected to reader:', connectResult.connection.reader.label);
      }
    }

    Behind the scenes, the StripeTerminal object uses the fetchConnectionToken function you defined in Step 2 to fetch a connection token, if it does not already have one. It then uses the connection token and reader information to create a reader session.

    The SDK comes with a built-in reader simulator, which you can use to develop and test your integration without any physical hardware. To use the reader simulator, simply configure your call to discoverReaders to use the provided simulator.

    var configuration = {method: 'simulated'}
    terminal.discoverReaders(configuration).then(function(discoverResult) {
        // connect to the simulated reader
    });
    
    const configuration = {method: 'simulated'}
    const discoverResult = await terminal.discoverReaders(configuration);
    

    Next step

    Congratulations! You've set up your SDK and reader. Next, collect your first Stripe Terminal payment.

    Questions?

    We're always happy to help with code or other questions you might have! Search our documentation, contact support, or connect with our sales team. You can also chat live with other developers in #stripe on freenode.

    Was this page helpful? Yes No

    Send

    Thank you for helping improve Stripe's documentation. If you need help or have any questions, please consider contacting support.