# HTML & iframe

Any website with a small server-side endpoint can take OnCharge payments. The endpoint creates the checkout session (it holds the API secret); the page shows the checkout with a script tag or a plain iframe.

## The page

```html title="checkout.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Checkout</title>
  </head>
  <body>
    <main>
      <h1>Pay for order #1001</h1>
      <div id="oncharge-checkout"></div>
      <p id="checkout-error" role="alert" hidden></p>
    </main>

    <script src="https://app.oncharge.io/js/v1/oncharge.js"></script>
    <script>
      async function startCheckout() {
        const res = await fetch('/create-checkout', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ orderId: '1001' }),
        });
        if (!res.ok) throw new Error('Could not start checkout');
        const { checkoutUrl } = await res.json();

        window.OnCharge.mountCheckout('#oncharge-checkout', {
          url: checkoutUrl,
          minHeight: 480,
          onComplete: () => (window.location.href = '/order-complete.html?order=1001'),
          onRedirect: ({ url }) => window.location.assign(url),
          onError: (error) => console.warn(error),
        });
      }

      startCheckout().catch((err) => {
        const el = document.getElementById('checkout-error');
        el.textContent = err.message;
        el.hidden = false;
      });
    </script>
  </body>
</html>
```

`mountCheckout` adds the embed parameters, checks each message's origin, source and nonce, and resizes the frame; the options are listed under [Script tag](https://oncharge.io/docs/checkout#script-tag). Prefer no external script? Use the [plain iframe and message listener](https://oncharge.io/docs/checkout#embedded-iframe) instead.

No JavaScript at all? Make `/create-checkout` respond with a `303` redirect to the checkout URL and submit a normal form to it. That is the [hosted redirect](https://oncharge.io/docs/checkout#hosted-redirect) flow.

## The endpoint

Each version reads the order from your database, creates the session and returns `{ "checkoutUrl": … }`. They use the signing helpers from [Authentication & signing](https://oncharge.io/docs/authentication#examples), saved as their own files without the example calls at the bottom.

### Node (Express)

```js title="server.mjs"
import express from 'express';
import { onchargeRequest } from './oncharge.mjs'; // the Authentication page's helper, without its example calls

const app = express();
app.use(express.static('public'));

app.post('/create-checkout', express.json(), async (req, res) => {
  const order = await db.orders.find(req.body.orderId); // your data
  const session = await onchargeRequest(
    'POST',
    '/api/v1/checkout/sessions',
    {
      amount: order.totalCents,
      currency: 'USD',
      reference: `order-${order.id}`,
      order_id: String(order.id),
      return_url: `https://shop.example.com/order-complete.html?order=${order.id}`,
      customer_email: order.email,
      shipping: order.shipping, // { name, line1, line2, city, state, postal_code, country }
    },
    { idempotencyKey: `order-${order.id}` },
  );
  res.json({ checkoutUrl: new URL(session.iframe_url, 'https://app.oncharge.io').href });
});

app.listen(3000);
```

### PHP

```php title="create-checkout.php"
<?php
require __DIR__ . '/oncharge.php'; // oncharge_request() from the Authentication page, without its example calls

$input = json_decode(file_get_contents('php://input'), true);
$order = find_order($input['orderId'] ?? ''); // your data

$session = oncharge_request('POST', '/api/v1/checkout/sessions', [
    'amount' => $order['total_cents'],
    'currency' => 'USD',
    'reference' => 'order-' . $order['id'],
    'order_id' => (string) $order['id'],
    'return_url' => 'https://shop.example.com/order-complete.php?order=' . $order['id'],
    'customer_email' => $order['email'],
    'shipping' => $order['shipping'], // name, line1, line2, city, state, postal_code, country
], 'order-' . $order['id']);

header('Content-Type: application/json');
echo json_encode(['checkoutUrl' => 'https://app.oncharge.io' . $session['iframe_url']]);
```

### Python (Flask)

```python title="app.py"
from flask import Flask, jsonify, request
from oncharge import oncharge_request  # the Authentication page's helper, without its example calls

app = Flask(__name__, static_folder="public", static_url_path="")


@app.post("/create-checkout")
def create_checkout():
    order = find_order(request.get_json()["orderId"])  # your data
    session = oncharge_request(
        "POST",
        "/api/v1/checkout/sessions",
        {
            "amount": order["total_cents"],
            "currency": "USD",
            "reference": f"order-{order['id']}",
            "order_id": str(order["id"]),
            "return_url": f"https://shop.example.com/order-complete.html?order={order['id']}",
            "customer_email": order["email"],
            "shipping": order["shipping"],
        },
        idempotency_key=f"order-{order['id']}",
    )
    return jsonify(checkoutUrl="https://app.oncharge.io" + session["iframe_url"])
```

## Then

1. Add a [webhook endpoint](https://oncharge.io/docs/webhooks) (examples for Node, PHP and Python) and mark orders paid on `payment.captured`.
2. Report tracking numbers when you ship: [Shipments & payouts](https://oncharge.io/docs/shipments).
3. Register the domain that serves `checkout.html` for the store in the merchant portal.

## Site builders (Webflow, Framer, Squarespace, …)

Site builders let you add the page part with an **embed / custom code** element, but you still need a server for `/create-checkout` and the webhook, because the API secret cannot live in the page. Use a small serverless function (on any host you like) with the Node or Python endpoint above, call it from the embed, and register both the site's domain and the function's webhook URL in the portal. Order data then lives in your own backend, not in the site builder.
