Skip to content

Integrating MetaMask Payments with Stripe for Web3 Commerce

Posted on:November 5, 2023 at 05:06 AM

What follows is a conceptual demonstration of a service that enables payments for traditional fiat services using your MetaMask wallet without any on chain infra like smart contracts etc. Leveraging the new MetaMask SDK, this guide extends the ideas I presented at Permissionless 2023.

Setting the Stage

The MetaMask SDK provides a seamless way to interact with Ethereum’s blockchain. When combined with Stripe’s robust payment infrastructure, it opens up the possibility for a hybrid payment system that accepts both fiat and cryptocurrency. This post will guide you through the process of setting up such a system. A better example might be a service that uses toast’s api to do this in real time at a resturant in leu of stripe as they are already working on crypto support.

Prerequisites

Before diving into the code, ensure you have:

Step 1: Listening for Stripe Webhooks

First, we’ll create an endpoint to handle incoming Stripe webhooks:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());

app.post('/stripe-webhook', (req, res) => {
  const event = req.body;

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded': //there is a better webhook for this I just don't know it off the top of my head.
      const paymentIntent = event.data.object;
      handlePaymentIntent(paymentIntent);
      break;
    // ... handle other event types
    default:
      console.log(`Unhandled event type ${event.type}`);
  }

  // Acknowledge the event
  res.json({received: true});
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Step 2: Converting Fiat to Ethereum

Upon a successful payment event, we convert the fiat amount to Ethereum:

const axios = require('axios');

async function convertFiatToEth(amount, currency) {
  const response = await axios.get('https://api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD');
  const rates = response.data;
  return amount / rates[currency];
}

Step 3: Initiating a MetaMask Transaction

With the Ethereum amount calculated, we can prompt the user to confirm the transaction via MetaMask:

const { MetaMaskSDK } = require('@metamask/sdk');

async function handlePaymentIntent(paymentIntent) {
  const ethAmount = await convertFiatToEth(paymentIntent.amount_received, paymentIntent.currency);

  // Initialize MetaMask SDK
  const sdk = new MetaMaskSDK({ /* ...options */ });
  const accounts = await sdk.connect();
  const ethereum = sdk.getProvider();

  // Define the transaction parameters
  const txParams = {
    from: accounts[0],
    to: paymentIntent.vendor_wallet,
    value: ethereum.utils.toHex(ethereum.utils.toWei(ethAmount.toString(), 'ether')),
    // Include appropriate gas settings
  };

  // Prompt the user for transaction confirmation
  try {
    const txHash = await ethereum.request({
      method: 'eth_sendTransaction',
      params: [txParams],
    });
    console.log(`Transaction successful with hash: ${txHash}`);
  } catch (error) {
    console.error(`Transaction failed: ${error.message}`);
  }
}

Wrapping Up: Just a Taste of What’s Possible

Alrighty, I’ve just scratched the surface of what could be a game-changer for crypto payments with the Metamask SDK. What I’ve shown you today is more of a ‘what if’ scenario, a peek into a future where swapping your Ether for that must-have gadget is as easy as clicking “Pay with MetaMask.”

Keep in mind, this isn’t something you’d want to roll out in a production environment – not yet, anyway. Think of it more like a proof of concept, a bit of playful tinkering to get those gears turning. I’ve taken some liberties, glossed over the nitty-gritty details, and left out the all-important error handling that would make this ready for the prime time.

But hey, that’s how all the best ideas start, right? A little bit of “what’s this button do?” mixed with a healthy dose of imagination. So take this idea, run with it. And who knows? Maybe the next time we’re at a conference, you’ll be the one on stage, showing off how you turned this half-baked idea into a fully-baked revolution.

Until then, keep hacking, keep building shit, and remember – in tech, the only limit is how far you’re willing to push the boundaries. Catch you on the flip side!