loading...

Web Monetization in Vue ⚡

wobsoriano profile image Robert Updated on ・2 min read

There is an awesome post for getting started with web monetization in React and was inspired to recreate it with Vue 3.

We're going to use a no-bundle dev server for Vue 3 called vite which allows us to develop Vue apps with Single-File Components without any bundling during development.

Create a vite app

Open up your terminal and do the following:

$ npx create-vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev

Creating a hook to see if a user is web monetized

In the root of your project folder, create a file named use-web-monetization.js and paste the code below.

import { ref, onMounted } from "vue";

export const useWebMonetization = () => {
  const isMonetized = ref(false);
  const isLoading = ref(true);

  onMounted(() => {
    if (!document.monetization) {
      // No web monetization polyfill is installed (e.g. Coil).
      isLoading.value = false;
      isMonetized.value = false;
      return;
    }

    // Check the value of document.monetization.state
    // to see if a user is web monetized.
    const { state } = document.monetization;

    if (state === "stopped") {
      // Not currently sending micropayments, nor trying to.
      isLoading.value = false;
      isMonetized.value = false;
    }

    // Determine when Web Monetization has started actively paying
    document.monetization.addEventListener("monetizationstart", (event) => {
      isLoading.value = false;
      isMonetized.value = true;
    });
  });

  return {
    isMonetized,
    isLoading,
  };
}

We created a file that has a reusable hook named useWebMonetization that returns isMonetized and isLoading states.

And now we can use it inside any .vue file like below.

<template>
    <div>
      <div v-if="isLoading">
        Loading...
      </div>
      <div v-else-if="isMonetized">
        Some exclusive content!
      </div>
      <div v-else>
        Show ads here!
      </div>
    </div>
</template>

<script>
import { useWebMonetization } from "./use-web-monetization";

export default {
  setup() {
    const { isLoading, isMonetized } = useWebMonetization();

    return {
      isLoading,
      isMonetized,
    };
  }
};
</script>

Testing Web Monetization

test-web-monetization is a website that provides a bookmarklet that we can use to test our projects without signing up for a Coil account.

Sample App

Here's a sample simulator app to get you started.

demo

Good luck to everyone who's joining the #gftwhackathon!

Posted on by:

wobsoriano profile

Robert

@wobsoriano

Apparently, this user prefers to keep an air of mystery about them.

Discussion

markdown guide