comecerodocs
Tutorials

Hello World

Build a test checkout in one HTML page. Get a limited token from the browser, create a cart, pay it with a test card and show the result.

In this tutorial you build a checkout that runs in the browser: one HTML page that gets a limited token, creates a cart, pays for it with a test card and shows the result. There is no server code and no token in the page.

Want the finished page? Download hello-world.html and read the comments.

Before you start

  • A Comecero account (sign up). Your account ID, for example AB1234, is under Administration > Account Info in the dashboard.
  • An active test product. Make one in the Quickstart, or in the dashboard with Test on under Store > Products. Note its id, such as hello-ebook.test.
  • A local web server, such as npx serve or python3 -m http.server 8000. The API allows browser calls from localhost and 127.0.0.1. For any other host name, add it under Settings > Technical > CORS Allowed Origins. See CORS.

This page uses a limited token, the only kind that belongs in a browser. It can read your public catalog and change only the carts and payments it created, and it may not set prices. Never put a secret token in a web page.

Start the page

Create index.html with a small form and an empty log:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello World checkout</title>
</head>
<body>
  <form id="checkout">
    <label>Account ID <input id="account-id" placeholder="AB1234" required></label>
    <label>Product ID <input id="product-id" placeholder="hello-ebook.test" required></label>
    <label>Card number <input id="card-number" value="4444555566661111" required></label>
    <button type="submit">Pay</button>
  </form>
  <div id="log"></div>

  <script>
    // The code from the next steps goes here.
  </script>
</body>
</html>

Add two helpers

log writes a line on the page. api sends a POST with JSON and throws when the API answers with an error. Errors come back as { "error": { "type", "code", "message" } }.

const API = 'https://api.comecero.com/api/v1';

function log(message) {
  const line = document.createElement('p');
  line.textContent = message;
  document.getElementById('log').append(line);
}

async function api(path, { token, body } = {}) {
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers.Authorization = `Bearer ${token}`;

  const response = await fetch(`${API}${path}`, {
    method: 'POST',
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await response.json();
  if (!response.ok) {
    const error = new Error(data.error?.message ?? `HTTP ${response.status}`);
    error.status = response.status;
    error.code = data.error?.code;
    throw error;
  }
  return data;
}

Get a limited test token

Call Create a limited token with no Authorization header. Send your account_id, and test=true for a test token. The response holds the token in token, starting with limited.test..

async function createLimitedToken(accountId) {
  const params = new URLSearchParams({ account_id: accountId, test: 'true' });
  const auth = await api(`/auths/limited?${params}`);
  return auth.token;
}

The token lasts two hours and each use moves the expiry forward. In a real shop, keep it for the shopper's visit (for example in sessionStorage) instead of making a new one for every cart.

If this call returns 403, your account does not allow public test tokens. Turn on Allow Public Test Orders under Settings > Technical in live mode. See Account and test mode.

Create the cart

Call Create a cart with the token. Each item needs a product_id. Do not send reference_price: a limited token may not set prices (403). The cart is bound to this token, so only this token can change it.

async function createCart(token, productId) {
  return api('/carts', {
    token,
    body: {
      currency: 'USD',
      items: [{ product_id: productId, quantity: 1 }],
      customer: {
        name: 'John Doe',
        email: 'john@example.com',
        billing_address: { country: 'US', postal_code: '94101' },
      },
    },
  });
}

The response is the cart, with cart_id, total and the order_id it gets when paid.

Pay for the cart

Call Pay for a cart. The amount comes from the cart, so you send only the payment method. 4444555566661111 succeeds in test mode and 4444555566669999 is declined.

async function payCart(token, cartId, cardNumber) {
  return api(`/carts/${cartId}/payments`, {
    token,
    body: {
      payment_method: {
        type: 'credit_card',
        data: { number: cardNumber, exp_month: 12, exp_year: 2030, cvv: '123' },
      },
    },
  });
}

A successful payment returns 201 with status completed (or pending when your settings only authorize). The cart closes and the order is made. A declined card returns 402 with code payment_declined.

Run the steps and show the result

Join the steps when the form is sent:

async function checkout(event) {
  event.preventDefault();
  document.getElementById('log').replaceChildren();

  const accountId = document.getElementById('account-id').value.trim();
  const productId = document.getElementById('product-id').value.trim();
  const cardNumber = document.getElementById('card-number').value.trim();

  try {
    log('Creating a limited test token...');
    const token = await createLimitedToken(accountId);

    log('Creating the cart...');
    const cart = await createCart(token, productId);
    log(`Cart ${cart.cart_id} created. Total: ${cart.total} ${cart.currency}.`);

    log('Paying for the cart...');
    const payment = await payCart(token, cart.cart_id, cardNumber);
    log(`Paid! Payment ${payment.payment_id} is ${payment.status}. Order ${cart.order_id} is ready.`);
  } catch (error) {
    log(`Failed (${error.status} ${error.code ?? ''}): ${error.message}`);
  }
}

document.getElementById('checkout').addEventListener('submit', checkout);

Try it

Start your local server, open the page (for example http://localhost:8000), enter your account ID and product ID, and click Pay. You see each step, then the payment and order ids.

Change the card to 4444555566669999 and pay again to see a decline. More cards are in Test cards.

Sign in to the dashboard with Test on and look under Sales > Carts, Sales > Payments and Sales > Orders to see what you made.

Before you use this in a real shop

  • Payments that need the shopper. Some gateways answer with status initiated and a next step in response_data, such as a 3-D Secure check or a PayPal redirect. When the shopper is done, get the payment and call Commit a payment only while it is still initiated. The built-in test gateway never does this.
  • Live mode. Leave out test=true to get a live limited token. Live payments work once your account is live.
  • Card data. When shoppers type card numbers into your own page, your site handles card data and falls under the card industry's PCI rules. The hosted storefront and checkout take card details on Comecero's pages instead.
  • Your own domain. Add it to CORS Allowed Origins before you go live.

Accounts that sell through Comecero as the reseller cannot create payments from a browser page: the API refuses the call. Take payments on your server with a secret token, or use the hosted checkout.

On this page