Introduction
In the ever-evolving landscape of web development, the integration of Web3 technology has become a game-changer, particularly in the realm of payments. Web3 enables decentralized applications (dApps) that leverage blockchain technology, providing enhanced security, transparency, and efficiency. In this guide, we will walk you through the process of integrating Web3 payments into a React JS web application. By the end of this tutorial, you’ll have a working dApp that can handle cryptocurrency transactions.
Prerequisites
Before diving into the code, ensure you have the following prerequisites:
- Node.js and npm: Install from Node.js official site.
- React JS: Basic understanding and setup.
- Metamask: Install the Metamask browser extension.
- Infura Account: Sign up for an account at Infura.
Setting Up the React Project
Step 1: Create a New React App
First, let’s create a new React application using Create React App:
npx create-react-app web3-payment-app
cd web3-payment-app
Step 2: Install Dependencies
Next, install the required dependencies for Web3 integration:
npm install web3 @metamask/detect-provider
Connecting to the Ethereum Network
Step 3: Configure Web3
Create a new file web3.js
in the src
directory to configure Web3 and connect to the Ethereum network:
import Web3 from 'web3';
import detectEthereumProvider from '@metamask/detect-provider';
const loadWeb3 = async () => {
const provider = await detectEthereumProvider();
if (provider) {
console.log('Ethereum provider detected');
window.web3 = new Web3(provider);
} else {
console.error('Please install Metamask');
}
};
export default loadWeb3;
Step 4: Initialize Web3 in App Component
Modify the App.js
file to initialize Web3 when the application loads:
import React, { useEffect } from 'react';
import loadWeb3 from './web3';
function App() {
useEffect(() => {
loadWeb3();
}, []);
return (
<div className="App">
<h1>Web3 Payment Integration</h1>
<button onClick={connectWallet}>Connect Wallet</button>
</div>
);
}
const connectWallet = async () => {
if (window.web3) {
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log('Wallet connected');
} catch (error) {
console.error('User rejected connection');
}
} else {
console.error('No Web3 provider found');
}
};
export default App;
Implementing Payment Functionality
Step 5: Create Payment Component
Create a new file Payment.js
to handle the payment functionality:
import React, { useState } from 'react';
const Payment = () => {
const [amount, setAmount] = useState('');
const handlePayment = async () => {
const accounts = await window.web3.eth.getAccounts();
const account = accounts[0];
const value = window.web3.utils.toWei(amount, 'ether');
window.web3.eth.sendTransaction({
from: account,
to: 'RECIPIENT_WALLET_ADDRESS',
value: value,
})
.then(() => {
console.log('Payment successful');
})
.catch(error => {
console.error('Payment failed', error);
});
};
return (
<div>
<h2>Make a Payment</h2>
<input
type="text"
placeholder="Amount in ETH"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
<button onClick={handlePayment}>Pay</button>
</div>
);
};
export default Payment;
Step 6: Integrate Payment Component in App
Modify the App.js
to include the Payment
component:
import React, { useEffect } from 'react';
import loadWeb3 from './web3';
import Payment from './Payment';
function App() {
useEffect(() => {
loadWeb3();
}, []);
return (
<div className="App">
<h1>Web3 Payment Integration</h1>
<button onClick={connectWallet}>Connect Wallet</button>
<Payment />
</div>
);
}
const connectWallet = async () => {
if (window.web3) {
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log('Wallet connected');
} catch (error) {
console.error('User rejected connection');
}
} else {
console.error('No Web3 provider found');
}
};
export default App;
Testing the Application
To test the application, follow these steps:
- Run the React application:
npm start
- Open the application in your browser.
- Connect your Metamask wallet.
- Enter an amount in ETH and click “Pay”.
Ensure your Metamask wallet has sufficient funds and is connected to the correct network.
Conclusion
Integrating Web3 payments into a React JS web application opens up new possibilities for decentralized finance and seamless cryptocurrency transactions. This step-by-step guide provides a foundational understanding of how to set up and implement Web3 payments. With further exploration and customization, you can enhance your dApp to offer more advanced features and a better user experience.
Happy coding!