Reactive payments

This guide lets a viewer watch the first seconds of a video for free. When the preview ends, the page pauses the video, hides its controls and shows a Qatom pay button over it. Once the viewer has paid and your server has confirmed the payment, the video carries on from where it stopped.

The same pattern works for any <audio> or <video> element, and for any other moment in your page where you want to ask for a payment.

Before you start

You need:

How it works

  1. The page creates the pay button when it loads and mounts it in an overlay that stays hidden.
  2. While the video plays, the browser fires timeupdate several times a second. When the playback position reaches the end of the preview, the page pauses the video, turns its controls off and shows the overlay.
  3. The viewer presses the pay button. Checkout opens over the page, and they sign in and pay.
  4. payment-js dispatches a payment event on document. The page sends its detail to your server, which confirms the payment with Qatom.
  5. Only when your server says the payment is good does the page hide the overlay, turn the controls back on and resume.

Checkout only opens when the viewer presses the pay button: payment-js has no method that opens it from code. That is why the overlay shows the button rather than opening checkout by itself.

The page

Replace <PUBLIC_SECRET> with your account’s public secret and <HASH> with your item’s hash, both in the script.

<div class="player">
  <video id="video" src="/media/episode-1.mp4" controls playsinline></video>

  <div id="paywall" class="paywall" hidden>
    <p>Enjoying it? Pay to keep watching.</p>
    <div id="pay"></div>
    <p id="paywall-error" role="alert" hidden></p>
  </div>
</div>

<style>
  .player {
    position: relative;
    max-width: 640px;
  }

  .player video {
    display: block;
    width: 100%;
  }

  .paywall {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    padding: 16px;
    background: rgb(0 0 0 / 0.75);
    color: #fff;
    text-align: center;
  }

  .paywall[hidden] {
    display: none;
  }
</style>

<script type="module">
  import "https://cdn.m.todaq.net/micropay.js";

  const HASH = "<HASH>";
  const FREE_SECONDS = 15;

  const video = document.querySelector("#video");
  const paywall = document.querySelector("#paywall");
  const paywallError = document.querySelector("#paywall-error");

  let paid = false;

  function showError(message) {
    paywallError.textContent = message;
    paywallError.hidden = false;
  }

  // 1. Create the pay button now, so it is ready when the preview ends.
  const micro = await loadMicroPayments("<PUBLIC_SECRET>", { apiVersion: "main" });
  const element = await micro.elements().create("payment", { hash: HASH });

  if (element) {
    element.mount("#pay");
  } else {
    // create() resolves to null when the item cannot be loaded,
    // for example when the hash does not exist.
    showError("Payments are unavailable right now. Please try again later.");
  }

  // 2. Stop at the end of the preview.
  function lock() {
    video.pause();
    video.controls = false;
    paywall.hidden = false;
  }

  function previewIsOver() {
    return !paid && video.currentTime >= FREE_SECONDS;
  }

  video.addEventListener("timeupdate", () => {
    if (previewIsOver()) {
      lock();
    }
  });

  // Also catch playback started another way, such as a keyboard shortcut.
  video.addEventListener("play", () => {
    if (previewIsOver()) {
      lock();
    }
  });

  // 3. Resume only once your server has confirmed the payment.
  document.addEventListener("payment", async (event) => {
    const { hash, nonce, timestamp } = event.detail;

    if (hash !== HASH) {
      return;
    }

    paywallError.hidden = true;

    let response;
    try {
      response = await fetch("/purchases", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ hash, nonce, timestamp }),
      });
    } catch {
      showError("We could not reach the server to confirm your payment. Please try again.");
      return;
    }

    if (!response.ok) {
      showError("We could not confirm your payment.");
      return;
    }

    paid = true;
    paywall.hidden = true;
    video.controls = true;

    // The browser may refuse to start playback on its own.
    // The controls are back, so the viewer can press play.
    video.play().catch(() => {});
  });
</script>

A few details:

If you build with a bundler, install payment-js with npm install @todaqmicro/payment-js and replace the import line with import { loadMicroPayments } from "@todaqmicro/payment-js";.

Confirm the payment on your server

Anyone can dispatch a payment event in their own browser, so the page above does not resume until /purchases on your server answers 200. That route redeems the payment with Qatom (POST /v4/payment/:hash/validate), using your account’s access token, which never goes in the page. For example, with Express:

app.post("/purchases", express.json(), async (req, res) => {
  const { hash, nonce, timestamp } = req.body ?? {};

  if (hash !== "<HASH>" || typeof nonce !== "string" || !Number.isInteger(timestamp)) {
    return res.status(400).end();
  }

  const response = await fetch(`https://pay.m.todaq.net/v4/payment/${hash}/validate`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ nonce, timestamp }),
  });

  // 200: the payment was valid and is now used. 400: it does not exist or was already redeemed.
  res.status(response.ok ? 200 : 402).end();
});

Redeeming uses the payment up, so the same nonce cannot unlock the video twice. Confirm each payment on your server explains both validate calls and their responses.

A pause in the browser only asks for payment: someone who edits the page can skip it. If the rest of the video must stay private, keep it off the page until the viewer has paid, for example by having /purchases answer with the address of the full video once the payment is redeemed, and setting video.src to it before resuming.

Next steps