简体   繁体   中英

Store ethereum transaction id (metamask) in php variable

I'm not used to javascript and I am using the code below to send an ethereum transaction via metamask, and it looks like it is all working fine, I can print the transaction's hash after it is sent with document.write, but can't find a way to store the hash in a php variable to afterwards deal with it in a database and whatever.

I need the value of 'txHash' in a php variable. Would appreciate a lot some help! Thanks

sendEthButton.addEventListener('click', () => {
  ethereum
    .request({
      method: 'eth_sendTransaction',
      params: [
        {
          from: accounts[0],
          to: '< - RECEIVING ACCOUNT - >',
          value: '0xDE0B6B3A7640000',
        },
      ],
    })
.then((txHash) => document.write(txHash))
.catch((error) => console.error);
});

PHP is executed before the browser JavaScript. It's not able to interact with MetaMask, as it doesn't have access to the window.ethereum object of the extension.

However, you can use JavaScript fetch() function to send the transaction ID (or any other data) from JS to a PHP script.

ethereum.request({
    // ...
}).then((txHash) => {
    fetch('/txIdReceiver.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'hash=' + txHash,
    })
})

Because of the x-www-form-urlencoded content type, the transaction hash is now available in the $_POST["hash"] variable of the PHP script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM