使用 Python 构建 Flask 应用程序加密货币支付结账

简要介绍如何使用 Python、Infura 和 Web3 模块在网站上开发加密货币支付结账

加密货币支付方式方便商家从买家处接收资金,避免传统银行支付的严格规定。在某种程度上,从长远来看,它还可以通过使用内部构建的加密货币支付方式来节省成本并促进业务扩展。

在本文中,我将简要介绍如何使用 Python、Infura 和 Web3 模块在网站上开发加密货币支付结账。在本教程结束时,您可以将其添加到您的网站上,让您的买家结帐并通过加密网络向您发送资金。

目录:使用 Python、Infura、Metamask 和 Web3 将加密货币支付方法添加到 Flask 应用程序

创建交易所需的参数和值

基本上,交易中有一些必须具有的参数和值,数据格式在字典中。基本公式如下:

transaction = { "gasPrice" : gasPrice , "chainId" : int (

        chain_id ), "from" : address , "to" : receiverAddress , "value" : valuetoSend , "nonce" : nonce }

    gas = w3 . eth . estimate_gas ( transaction )

    transaction [ 'gas' ] = gas

  • 发件人钱包地址:买家在结账时通过登录商家网站添加她/他的地址
  • 接收钱包地址(Flask.env 中默认添加的商户账户)
  • 支付数量
  • Gas价格:每笔交易的处理价格
  • Chaine ID:您正在连接的区块链节点ID
  • Nonce:来自发送者公共钱包 ID 的交易计数
  • 天然气总成本

可以通过以下方式获得一些参数值:

  • 天然气价格:w3.eth.gas_price
  • 链ID:https: //chainlist.org/
  • Nonce:w3.eth.getTransactionCount(买家钱包地址)
  • 天然气价格:w3.eth.gas_price
  • 天然气总成本:

gas = w3 . eth . estimate_gas ( transaction )

    transaction2 [ 'gas' ] = gas

Metamask 和 Infura API 节点连接以太坊区块链

我之前在另一篇文章中分享过关于Infura API连接和Metamask使用说明,请查看这篇文章了解更多详细信息。

https://www.easy2digital.com/web3/use-infura-and-metamask-in-python-scripts-to-deploy-web3-on-ethereum/

在添加到 Flask 应用程序的加密货币支付方法中,可以在脚本的全局级别添加此部分,该脚本可以共享以在每个本地函数中使用。样本如下:

# -------------- Connect ETH network using a node: Infura -------------- ##

w3 = Web3 ( Web3 . HTTPProvider (

    "Your API endpoint" ))

gasPrice = w3 . eth . gas_price

chain_id = your chain ID

private_key = os . environ . get ( 'PRIVATE_KEY2' )

def accountBalance ( address ):

    accountBalance = w3 . eth . get_balance ( address )

    return accountBalance

签署并发送交易

现在网络连接和交易模块已准备就绪。我们可以开始测试买家结帐。

   signed_txn = w3 . eth . account . sign_transaction (

        transaction2 , private_key = 'buyer Metamask sign-in authentication' )

    tx_hash = w3 . eth . send_raw_transaction ( signed_txn .rawTransaction)

    tx_receipt = w3 . eth . wait_for_transaction_receipt ( tx_hash)

烧瓶路线

最后但并非最不重要的一点是,我们需要将此函数与 Flask 主应用程序路由连接起来。代码示例如下:

@ app .route ( '/' , methods =[ 'GET' , 'POST' ])

def web3Transaction123 ():

    if request . args . get ( 'SenderAddress' ) and request . args . get ( 'sendingValue' ):

        prompt = request . args . get ( 'SenderAddress' )

        prompt3 = request . args . get ( 'sendingValue' )

        if request . args . get ( 'user_signed' ):

            response2 = web3Transaction (

                prompt , prompt3 , request . args . get ( 'user_signed' ))

            flash ( "Done! Thank you for your payment" )

            return render_template ( 'test.html' , response22 = response2 )

    return render_template ( 'test.html' )

关于使用Metamas登录的用户认证,我将在下一篇文章中分享。

使用 Infura、Metamask 和 Web3 创建加密货币支付方式的完整 Python 脚本

如果您对 Web3.0 教程 8 –使用 Infura、Metamask 和 Web3 创建加密货币支付方式感兴趣,请添加消息“Web3.0教程8”来订阅我们的新闻通讯。我们会立即将脚本发送到您的邮箱。

我希望您喜欢阅读 Web3.0 教程 8 –使用 Infura、Metamask 和 Web3 创建加密货币支付方式。如果您这样做了,请通过执行下列操作之一来支持我们,因为这总是对我们的频道有所帮助。