Back

blockchain - 使用ETH进行第三方登录

发布时间: 2022-03-03 02:14:00

关键: 浏览器安装完metamask 之后, 会自动出现对象 window.ethereum

然后

const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
// accounts[0] 就是当前metamask的地址

下面是一个完整的代码例子:

document.querySelector('a.eth_connect').addEventListener('click', async () => {
  if (typeof window.ethereum !== 'undefined') {
     const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
     console.info("=== accounts: ", accounts)
     location.href="?address=" + accounts[0] + "&wallet_type=eth"
  }else {
    alert('You have not installed a wallet(e.g. Metamask) yet, please go to install it')
  }
});
对应的HTML:
<div>
  去中心化注册
  <a href='#' class='eth_connect' >
    <%= image_pack_tag('metamask.png', style: 'width: 24px; height: 24px') %>
    MetaMask
  </a>
</div>

点击上面的 .eth_connect 按钮后,就会获得当前metamask的accounts[0], 然后向后端API发起请求, 后端接收到这个参数,就会创建对应的account 了。

Back