问题描述
我需要为我网站上的按钮添加交易功能,我该怎么做?单击按钮后(我使用 Firefox 浏览器的 Metamask 扩展),Metamask 界面应该打开,显示交易的详细信息。我使用了下面的代码,但在浏览器控制台中看到了该消息:“未捕获(承诺)ReferenceError:未定义 Web3”。可能是什么问题?
<!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">Pay</button>
<div id="status"></div>
</div>
<script type="text/javascript">
window.addEventListener('load',async() => {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
initPayButton()
} catch (err) {
$('#status').html('User denied account access',err)
}
} else if (window.web3) {
window.web3 = new Web3(web3.currentProvider)
initPayButton()
} else {
$('#status').html('No Metamask (or other Web3 Provider) installed')
}
})
const initPayButton = () => {
$('.pay-button').click(() => {
// paymentAddress
const paymentAddress = '0x01910833896EEdf036A99b2CC34df6Da01BB15E3'
const amountEth = 1
web3.eth.sendTransaction({
to: paymentAddress,value: web3.toWei(amountEth,'ether')
},(err,transactionId) => {
if (err) {
console.log('Payment Failed',err)
$('#status').html('Payment Failed')
} else {
console.log('Payment successful',transactionId)
$('#status').html('Payment successful')
}
})
})
}
</script>
</body>
</html>
解决方法
我正在构建解决此问题的服务。用法就像打开一个弹出窗口一样简单:
const to = '0x9ebf6f16c0dad9f92eaaca8dbd40944e614338ae'
const value = 0.01 // ether
window.open(`https://pay.buildship.dev/to/${to}?value=${value}`,'payment','width=500,height=800');
如果您遇到任何问题或有兴趣提出一些问题,可以联系我https://t.me/buildship
,我发现 Metamask 在 1 月份更新了他们的 API,这就是代码不起作用的原因。
您可以在此处找到迁移指南:
https://docs.metamask.io/guide/provider-migration.html
,您必须导入 web3.js 库并添加以下行:
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
或者您可以按照以下说明进行安装:https://github.com/ChainSafe/web3.js