Home > Mobile >  Store ethereum transaction id (metamask) in php variable
Store ethereum transaction id (metamask) in php variable

Time:03-18

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);
});

CodePudding user response:

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.

  • Related