> Index of every page: https://docs.merchantservicedepot.com/llms.txt

# @myela/elements

> The hosted card field that keeps card numbers out of your code.

Elements puts one hosted card field in your page. The shopper types into a cross-origin iframe, and your page gets back a single-use token. The card number never reaches your page or your server: your server charges the token with [`@myela/payments`](https://docs.merchantservicedepot.com/docs/sdks/node/).

## Load Elements

Import Elements as an ES module, create a card field, mount it, and call `tokenize()` when the shopper pays. Pass `apiBase`: the default host doesn't resolve, so a field without it can't open a session. Use `https://payments-api-sandbox.merchantservicedepot.com` with a test key; the live host comes with your live key.

Elements is in preview and pre-1.0. Confirm the hosted field is enabled for your account before you build on it.

**checkout.html**

```html title="checkout.html"
<script type="module">
  import { Myela } from 'https://js.merchantservicedepot.com/v1/elements.js';

  const myela = Myela({
    publishableKey: 'myela_pk_test_...',
    apiBase: 'https://payments-api-sandbox.merchantservicedepot.com',
  });
  const card = myela.elements().create('card');

  await card.mount('#card-field');

  card.on('change', (e) => (payButton.disabled = !e.complete));

  payButton.addEventListener('click', async () => {
    const { token, error } = await card.tokenize();
    if (error) return showError(error.message);

    // token is opaque: "mtok_...". Send it to YOUR server.
    await fetch('/checkout', { method: 'POST', body: JSON.stringify({ token }) });
  });
</script>
```

**server.ts**

```ts title="server.ts"
await myela.gateway.payments.create({ amount: 4999, currency: 'USD', paymentToken: token });
```

The package is also on npm. It ships its source as ES modules with type declarations and no build step. Import it from your bundler instead of the hosted URL:

```ts title="checkout.ts"
import { Myela, kits } from '@myela/elements';
```

The hosted `elements.js` is the package's `index.js`, copied by the host. The package itself has no `elements.js`. Elements needs a browser with ES modules, cross-origin iframes, and `postMessage`.

## Options

`Myela(options)` takes your publishable key and the API host:

| Option | Type | Required | What it does |
| --- | --- | --- | --- |
| `publishableKey` | `string` | Yes | Your publishable key. Anything not starting with myela_pk_ throws invalid_publishable_key, so a secret key can't slip into the browser. |
| `apiBase` | `string` | Yes, in practice | The API host. The built-in default doesn't resolve, so always pass it. The frame accepts only Myela API hosts and loopback; anything else fails with api_base_untrusted. |
| `frameOrigin` | `string` | No | The origin of the hosted frame. Leave it unset. |

`.elements({ appearance })` sets the styling for every field in the group. Then `.create('card', { mount?, intent? })` makes the field. `card` is the only element type; anything else throws `unknown_element`.

## The card field

| Member | What it does |
| --- | --- |
| `mount(target?)` | Opens a checkout session and builds the iframe in the target (a selector or an element). Rejects with mount_timeout after 20 seconds. Mounting again replaces the first mount. |
| `tokenize({ amount? })` | Resolves with \{ token \} or \{ error \}. It doesn't throw for card errors. Times out with tokenize_timeout after 30 seconds. Pass amount, in minor units, when the token is for a payment. |
| `on(event, handler)` | change gives \{ complete, error? \}. ready fires when the field is ready. error gives an ElementsError. Chainable. |
| `unmount()` | Removes the iframe and its listener. Safe to call twice. destroy() still works but is deprecated. |
| `updateAppearance(appearance)` | Restyles the field without losing what the shopper typed. Returns the rejected tokens as \{ code, message \}\[\]. |
| `appearanceErrors` | Read-only list of appearance tokens that were rejected. |
| `chargeModifiers` | Read-only list of charge modifiers on the session. Empty before mount. |
| `quote(modifiers?)` | In the types, but its route isn't live. Don't build on it yet. |

## Checkout sessions and origins

`mount()` opens a checkout session: it calls `POST /v1/checkout_sessions` with your publishable key and an `intent` of `one_time` (the default) or `store`. The session is what the iframe loads. It isn't a hosted page you can send a shopper to.

A session opens only from an origin on your key's allow-list. The list starts empty, and an empty list refuses every origin with `401`, so add your checkout page's origin in your Myela account under Settings, API keys before your first mount. Rotating the publishable key breaks every page that embeds it at once.

`intent: 'store'` doesn't save the card. Your server still saves it with `POST /v1/payment_methods`; see [Save a card, then charge it](https://docs.merchantservicedepot.com/docs/payments/save-a-card/).

## Charge the token

`tokenize()` returns a Myela token, `mtok_…`. It is single-use and short-lived. Send it to your server and spend it there with your secret key: charge it with `myela.gateway.payments.create`, or save it to a customer. The publishable key in the browser can open a session and tokenize, nothing else. Start with [Accept a payment](https://docs.merchantservicedepot.com/docs/payments/accept-a-payment/).

## Styling

Pick a kit, `minimal` (the default), `midnight`, `soft`, or `bordered`, and override variables on top of it.

```ts title="checkout.ts"
import { Myela, kits } from '@myela/elements';
import Status from '../../../../components/mdx/Status.astro';

<Status tone="preview">Preview</Status>

const myela = Myela({ publishableKey: 'myela_pk_...' });

const card = myela
  .elements({
    appearance: {
      kit: 'midnight',
      variables: { colorAccent: '#ff0055', borderRadius: '10px' },
    },
  })
  .create('card');
```

| Group | Variables | Values |
| --- | --- | --- |
| Color | `colorBackground, colorText, colorPlaceholder, colorBorder, colorBorderFocus, colorAccent, colorDanger, colorDangerBackground` | Hex (#rgb, #rrggbb, #rrggbbaa), rgb(), rgba(), hsl(), hsla(), or transparent. |
| Type | `fontFamily, fontSize, fontWeight` | No url() and no @import. |
| Shape and space | `borderRadius, borderWidth, fieldPaddingY, fieldPaddingX, fieldGap, focusRingWidth` | Non-negative px, rem, em, or %. |

There is no CSS and no `className`. There's no variable for `position`, `z-index`, `transform`, `content`, `display`, `overflow`, or `opacity`, and there won't be. A rejected variable is dropped and listed in `appearanceErrors`; it doesn't stop the field.

## Errors

Errors are `{ code, message }`. The codes are stable; branch on `code`, never on `message`. Calls that fail outright, such as a bad key or a mount that times out, throw or reject with a `MyelaElementsError` that carries the same `code`. Card errors from `tokenize()` come back in `error` instead of throwing.

| Where | Codes |
| --- | --- |
| Your page | `invalid_publishable_key, unknown_element, mount_target_not_found, session_failed, mount_timeout, not_mounted, tokenize_timeout, quote_invalid` |
| Frame setup | `frame_origin_unknown, session_missing, api_base_missing, api_base_untrusted, mock_refused, parent_origin_missing, capture_unsupported, modifiers_invalid, capture_unavailable, amount_invalid` |
| Card field | `incomplete_number, incomplete_expiry, incomplete_cvc, incomplete, mount_failed, not_mounted, network_error` |
| Tokenizer | `incomplete_number, incomplete_expiry, incomplete_cvc, incomplete, tokenization_failed` |
| Appearance | `unknown_kit, unknown_token, invalid_token_value` |

`session_failed` may be replaced by the API's own error code when the session request fails.

Source: https://docs.merchantservicedepot.com/docs/sdks/elements/
