# Hello World (/docs/tutorials/hello-world)

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](/resources/hello-world.html) and read the comments.

## Before you start [#before-you-start]

- A Comecero account ([sign up](https://signin.comecero.com/register)). Your **account ID**, for example `AB1234`, is under **Administration > Account Info** in the dashboard.
- An active **test product**. Make one in the [Quickstart](/docs/getting-started/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](/docs/basic-concepts/cors).

<Callout>
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.
</Callout>

<Steps>

<Step>

## Start the page [#start-the-page]

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

```html
<!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>
```

</Step>

<Step>

## Add two helpers [#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" } }`.

```js
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;
}
```

</Step>

<Step>

## Get a limited test token [#get-a-limited-test-token]

Call [Create a limited token](/api/auths/create-limited-auth) 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.`.

```js
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](/docs/getting-started/create-an-account#get-a-test-token).

</Step>

<Step>

## Create the cart [#create-the-cart]

Call [Create a cart](/api/carts/create-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.

```js
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.

</Step>

<Step>

## Pay for the cart [#pay-for-the-cart]

Call [Pay for a cart](/api/carts/create-cart-payment). The amount comes from the cart, so you send only the payment method. `4444555566661111` succeeds in test mode and `4444555566669999` is declined.

```js
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`.

</Step>

<Step>

## Run the steps and show the result [#run-the-steps-and-show-the-result]

Join the steps when the form is sent:

```js
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);
```

</Step>

<Step>

## Try it [#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](/docs/getting-started/create-an-account#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.

</Step>

</Steps>

## Before you use this in a real shop [#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](/api/payments/commit-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.

<Callout type="warn">
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.
</Callout>
