# Prepare a test shop (/docs/getting-started/test-shop)

Create the test customer and payment method that your first bill, credit sale, access check or licensed device needs. Use a separate local folder for each exercise. Keep its saved state until you have checked the result.

In admin, choose **Test**, then open **Settings > Features**. You need permission to create customers, payment methods, products, plans and subscriptions, plus the resource permissions in your chosen guide. Setup restrictions can stop new feature work. Existing customer billing and access continue. Products that already carry the feature keep selling. Restrictions stop new setup, credit purchases and top-ups.

Use Node.js 18 or later. Set one secret test token:

```bash
export COMECERO_TEST_TOKEN='secret.test.REPLACE_WITH_YOUR_TOKEN'
node test-shop.mjs
```

Save this as `test-shop.mjs`. It verifies `/auths/me` before creating anything. The test card is accepted only in Test. The script saves returned IDs and original mutation requests in `guide-state.json`, readable only by your user. That file can contain a one-time usage key. Keep it out of source control and browsers.

```js title="test-shop.mjs"
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";

export const API = "https://api.comecero.com/api/v1";
export const METER = "https://usage.comecero.com";
const token = process.env.COMECERO_TEST_TOKEN;
if (!token?.startsWith("secret.test.")) throw new Error("Set COMECERO_TEST_TOKEN.");
export const state = existsSync("guide-state.json")
  ? JSON.parse(readFileSync("guide-state.json", "utf8"))
  : { suffix: randomUUID().slice(0, 8), steps: {} };
export function save() {
  writeFileSync("guide-state.json", JSON.stringify(state, null, 2), { mode: 0o600 });
}
export async function request(url, method = "GET", body, headers = {}) {
  const response = await fetch(url, {
    method,
    headers: { "Content-Type": "application/json", ...headers },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const answer = await response.json();
  if (!response.ok) throw new Error(JSON.stringify({
    status: response.status, error: answer.error ?? answer.message,
    retryAfter: response.headers.get("Retry-After"), results: answer.results,
  }));
  return answer;
}
export const api = (method, path, body, headers) => request(API + path, method, body, {
  Authorization: `Bearer ${token}`, ...headers,
});
export const auth = await api("GET", "/auths/me");
if (auth.test !== true) throw new Error("A verified test session is required.");
if (state.accountId && state.accountId !== auth.account_id) throw new Error("Use this exercise's original shop.");
state.accountId = auth.account_id;
save();

// Feature mutations replay the saved request. Ordinary commerce stops on an unknown outcome.
export async function step(name, method, path, body, replay = false) {
  let job = state.steps[name];
  if (job?.answer) return job.answer;
  if (job && !replay) throw new Error(`Read the saved records for ${name}; its outcome is unknown.`);
  if (!job) {
    job = state.steps[name] = { method, path, body, key: randomUUID() };
    save();
  }
  job.answer = await api(job.method, job.path, job.body,
    replay ? { "Idempotency-Key": job.key } : {});
  save();
  return job.answer;
}
export const mutate = (name, path, body) => step(name, "POST", path, body, true);
export const suffix = state.suffix;
const address = { name: "Test Merchant", address_1: "1 Test Street", city: "Austin",
  state_prov: "TX", postal_code: "78701", country: "US" };
export const customer = await step("customer", "POST", "/customers", {
  name: "Test Merchant", email: `success+guide-${suffix}@simulator.amazonses.com`,
  billing_address: address,
});
export const paymentMethod = await step("card", "POST",
  `/customers/${customer.customer_id}/payment_methods`, {
    type: "credit_card", is_default: true,
    data: { number: "4444555566661111", exp_month: 12, exp_year: 2030,
      cvv: "123", cardholder_name: "Test Merchant", billing_address: address },
  });
export const plan = await step("plan", "POST", "/subscription_plans", {
  name: `Test hourly ${suffix}`, billing_interval: 1, billing_interval_unit: "hour",
});
export const product = await step("product", "POST", "/products", {
  product_id: `guide-plan-${suffix}`, name: "Test usage plan", type: "service", active: true,
  prices: [{ price: 1, currency: "USD" }], subscription_plan_id: plan.subscription_plan_id,
});
export const subscription = await step("subscription", "POST",
  `/customers/${customer.customer_id}/subscriptions`, {
    subscription_plan_id: plan.subscription_plan_id, currency: "USD",
    items: [{ product_id: product.product_id, quantity: 1 }],
  });
export const startHour = state.startHour ??= new Date(Math.floor(Date.now() / 3_600_000) * 3_600_000).toISOString();
save();
console.log({ customer: customer.customer_id, paymentMethod: paymentMethod.payment_method_id,
  subscription: subscription.subscription_id, test: auth.test });

export async function buy(name, testProduct) {
  const cart = await step(`${name}-cart`, "POST", "/carts", {
    currency: "USD", customer: { customer_id: customer.customer_id },
    items: [{ product_id: testProduct.product_id, quantity: 1 }],
  });
  console.log(await api("GET", `/carts/${cart.cart_id}/options`));
  const payment = await step(`${name}-payment`, "POST", `/carts/${cart.cart_id}/payments`, {
    payment_method_id: paymentMethod.payment_method_id,
  });
  if (payment.status !== "completed") throw new Error("Read the payment before continuing.");
  const savedCart = await api("GET", `/carts/${cart.cart_id}`);
  return api("GET", `/orders/${savedCart.order_id}?expand=items.license`);
}
```

`startHour` saves the current whole UTC hour after the subscription exists. An agreement start must not be before the subscription's creation hour. Keep the saved hour, original request and idempotency key for retries.

A successful run prints returned customer, card and subscription IDs with `test: true`. In admin, open that customer under **Customers** and the subscription under **Sales > Subscriptions**.

`step` submits ordinary commerce once. A lost customer, subscription or payment response stops the script on rerun so you can read the saved records. Payments are never automatically retried. `mutate` retains the original feature request and `Idempotency-Key` after a timeout; rerunning replays that same request. Completed replies retain their original status and balance permanently. `credit_request_conflict` means the identity was reused with different input. `credit_request_pending` means the outcome remains reserved for investigation. Keep the key; do not replace it to force another attempt.

For eligible usage reads and usage meter events or checks, respect `Retry-After` on 429 and 503. If an AWS-managed error omits it, use bounded jittered backoff. Event retries retain their operation IDs. License activation retries retain the saved device fingerprint. These rules do not authorize retrying payments.

Continue with [your first usage bill](/docs/usage-billing/quickstart), [a credit sale](/docs/tutorials/sell-prepaid-credit), [an access check](/docs/entitlements/quickstart), or [a licensed device](/docs/license-keys/quickstart).
