Press "Enter" to skip to content

Add Metamask payments to any website with just a few lines of code.

Metamask updated their API recently which means a lot of examples of code on integrating MetaMask to your website are now not working. The new examples require Node.js but I was trying to create a simpler way to implement as a simple payment on a website www.wolfterritories.org .

So the following code allows you pretty much to set it up so that a user can hit your page click the buy button and get MetaMask to create the transaction.

Here’s the code.

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>
<button class="pay-button " onclick="javascript:buycoin()">Pay</button>
<button id="connectButton" onclick="javascript:connect()">Connect to MetaMask</button>
<div id="status"></div>
</div>
<script type="text/javascript">
   async function connect() {
      const accounts = await    ethereum.request({method:'eth_requestAccounts'});
     const account = accounts[0];
 }

async function buycoin() {
const accounts = await ethereum.request({method: 'eth_requestAccounts'});
const account = accounts[0];
const transactionParameters = {
from: ethereum.selectedAddress, // must match user's active address.
to: '0x00000 PUT YOUR PAYMENT ADDRESS HERE 00000' // Required except during contract publications.
// amount: '0xfe'; - add if you want to
};
alert(ethereum.selectedAddress + " " + transactionParameters.to);
txHash = await ethereum.request({
method: 'eth_sendTransaction',
params: [transactionParameters]
});
}
</script>
</body>
</html>

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

(C)Copyright UK Bitcoinblog.com all rights reserved. Images copyright of their original authors.