metamask screens image

If you can code a JavaScript app, you can build Ethereum payments into it, using MetaMask.

MetaMask is a wallet for Ethereum. To describe them in their own words, MetaMask is a piece of software that lets you 'buy, store, send, and swap (Ethereum and Ethereum-like) tokens.'

It is available in two forms: as a browser extension, and as a mobile app.

This tutorial will focus on coding up ways for the user to use the browser extension to purchase things using the MetaMask browser extension.

Why would you want to use MetaMask for this, instead of coding it all up yourself?

One reason is because it's difficult to write a whole wallet - a way for users to store their own Ethereum - by yourself. You have to think about security, storage and a whole host of issues that are beyond the scope of this tutorial (or it would be 10 times as long).

By letting MetaMask handle it, you can get straight to the good part: getting payments from customers using Ethereum.

Another reason is because MetaMask has become accepted as an industry standard. People may not trust your app, but they do trust MetaMask. If a crypto project, or an Ethereum-accepting services, says 'open MetaMask to begin the payment process,' no one feels that's weird: it's a safe and common choice.

Of course, this does mean users will have to install MetaMask.

They'll need to go to the browser extension store for their browser. You can see the Google Chrome version of this page for MetaMask below, which also conveniently includes a great explainer video for MetaMask.

chrome.google.com/webstore/detail/metamask/nkb...

After a user installs MetaMask, restarts their browser, logs in, and deposits Ethereum into it - quite a few steps! - they'll be ready to go; they can then use the payment methods described here in your app.

As an example, here's what MetaMask looks like in the extensions bar of my own browser, what the password prompt looks like when I click on it, and what you see, after clicking, as a balance.

metamask browser extension

So those are the basics. What kind of app should we build?

Naturally, we'll be building a Web3 app.

As Ethereum.org defines it, in their Web2 vs. Web3 explainer:

Web3, in the context of Ethereum, refers to decentralized apps that run on the blockchain. These are apps that allow anyone to participate without monetising their personal data. [The aforementioned MetaMask video goes into more detail on the MetaMask->Web3 connection.]

Many Web3 app tutorials use React, so it helps to be conversant with it. I've written a 'how to learn React' guide, to get you started. You can also check out the official (and recently revised) React documentation, which is excellent.

I'm going to assume you can follow along with React, because I've written a demo app you can check out and run on your own, using React and ethers.js.

github.com/CurrentCoin/ecommerce-react-metamask

You can copy and run it locally using the standard methods (git clone , npm install, etc.)

Ethers.js is really important here, so important that I thought about calling this an ethers.js tutorial.

As ethers.js says on their webpage:

The ethers.js library aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem.

This is what's tying in your app to MetaMask, and through MetaMask, to the Ethereum blockchain. By learning Ethers.js, you'll learn how to include Ethereum payments in any JavaScript app you build.

For the repo: you can clone it, examine the code, run it locally, learn from it all you want.

If you want to see what this code looks like when running, just check out ccoin.live, where the whole site is viewable and clickable.

https://www.ccoin.live/

Note: this is a real running app, so please don't complete the payment flow using real Ethereum - you should not confirm when MetaMask asks you to confirm the payment.

Otherwise, make any adjustments you want to the code... it's there for you to learn.

Basically the live app has a few example services you can pay for, using Ethereum. You fill out a form uploading your information, then you click to connect MetaMask and pay.

On the landing page you'll see the options. The flow is that you select one and go to it. Those are all pretty standard pages under (hopefully) intuitively named components. You don't have to spend long looking at them, unless you want to.

The real meat is found in the PayerEth.js file.

github.com/CurrentCoin/ecommerce-react-metamask/blob/main/src/PayerEth.js

I'll take you through a few important code sections.

We start with the UI component that tells the user their options and asks them to connect and/or pay.
 export default function PayerEth() {
    const amount = '25000000000000000';
    const receiver = '0xDddcf46Ed02a81e38E1906f508CEBa65A8f3B7dD';
const [message, setMessage] = useState(<Button type="button" fullWidth variant="contained"
color="primary" onClick={() => connectMeta(setAccount, setMessage)} >
Connect MetaMask</Button>);
    const [account, setAccount] = useState("");
    if (account === "") {
	return (
	    <>
		{message}
		</>
	)
    } else {
	return (
		<>
		  <Button type="button" fullWidth variant="contained" color="primary"
		  onClick={() => payMeta(account, receiver, amount, setMessage)} >
		    Buy For 0.025 ETH</Button>
		</>
	)

    }
} 

First, you have to make sure that the user has MetaMask installed, and is connected to it.

async function connectMeta(accounted, msged) {
    let ethereum = window.ethereum;

    try {
	const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
	const account = accounts[0];
	accounted(account);
    } catch {
	console.log("connect fail!");
	msged(<><p>Please install MetaMask and reload this page.</p></>);
    }
} 

Then, you have the payment itself, shown below (note: code formatting slightly changed so as render safely here - please see original for ready-to-run version).

 async function payMeta(sender, receiver, strEther, msged) {
    console.log(payWithMetamask(receiver={receiver}, sender={sender}, strEther={strEther}))
    try {
	const params = {
	    from: sender,
	    to: receiver,
	    value: strEther,
	    gas: 39000
	};
        await window.ethereum.enable();
        window.web3 = new Web3(window.ethereum);	
	const sendHash = window.web3.eth.sendTransaction(params);
	console.log('txnHash is ' + sendHash);
    } catch(e) {
	console.log("payment fail!");
	console.log(e);
	msged(<p>Can't connect MetaMask. Please check MetaMask.</p>);	
    }
} 

So PayerEth.js has the MetaMask & Ethereum payment functionality, and the other pages are basically forms and explanations to the user, to lead them to this page and make sure they want to make a purchase.

And that's it!

Now experiment with including this component in your own app. The basics stay the same, no matter what app you use.

That's really all it takes, to include Ethereum payments, using ethers.js and MetaMask, in your app.

With the increasing dominance of Ethereum among blockchains after Bitcoin, this is a feature you can expect companies, individuals, and business owners to want to implement for a long time to come.