【问题标题】:How to add multiple stripe button in one page?如何在一页中添加多个条纹按钮?
【发布时间】:2021-04-15 06:16:48
【问题描述】:

我正在按照本指南将条带结帐添加到我的自制网站。 https://stripe.com/docs/checkout/integration-builder

我有一个数据库和一个 PHP 页面。在这个页面中,我用产品循环了一个 mysql 表,并为每个产品显示信息并添加一个“立即购买”条纹按钮。 我用唯一的名称(标签 ID 和名称)调用每个按钮。跟随示例:

<?php
    <button id="checkout-button-<?php $row['productid']; ?>">Buy <?php echo $row['productname']; ?></button>
?>

我的问题在于 javascript:

<!-- Start Stripe Integration -->
<script type="text/javascript">
  // Create an instance of the Stripe object with your publishable API key
  var stripe = Stripe("<?php echo $stripe_key_public ?>");
  var checkoutButton = document.getElementById("checkout-button **$$Here is the problem$$**");
  checkoutButton.addEventListener("click", function() {
    fetch("my-stripe-checkout.php", {
        method: "POST",
      })
        .then(function(response) {
          return response.json();
        })
        .then(function(session) {
          return stripe.redirectToCheckout({
            sessionId: session.id
          });
        })
        .then(function(result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function(error) {
          console.error("Error:", error);
        });
  });
</script>
<!-- End Stripe Integration -->

如何为我的 PHP 循环之外的每个按钮添加自定义 eventListener 或参数化 javascript 函数(带有项目描述、价格/金额等)?

还是我错误的方法解决方案?有没有更好的方法为产品列表添加条纹结帐按钮?

谢谢

【问题讨论】:

    标签: javascript php stripe-payments


    【解决方案1】:

    您需要将 JavaScript 添加到页面以侦听和处理来自页面上所有按钮的事件。有几种方法可以解决这个问题,但我建议更改按钮,使它们的工作方式如下:

    <button onclick="checkoutButtonPressed('<?php $row['productid']; ?>')">Buy <?php echo $row['productname']; ?> </button>
    

    然后在 JavaScript 中实现checkoutButtonPressed() 函数,根据提供的产品 ID 创建一个 Checkout Session:

    var stripe = Stripe("<?php echo $stripe_key_public ?>");
    
    function checkoutButtonPressed(productID) {
        var session = // Fetch Checkout Session using productID
    
        stripe.redirectToCheckout({ sessionId: session.id });
    }
    

    【讨论】:

      【解决方案2】:

      如果您想呈现结帐按钮列表,最好使用data attributes

      代码

      为结帐按钮添加数据属性:

      <?php
        <button 
          data-product-id="<?php $row['productid']; ?>"
        >
          Buy <?php echo $row['productname']; ?>
        </button>
      ?>
      

      并将事件监听器添加到具有该数据属性的所有按钮:

      // getting buttons with specific data attribute
      let checkout_btns = document.querySelectorAll("[data-product-id]");
      
      // adding the event listener by looping
      checkout_btns.forEach((checkout_btn) => {
        checkout_btn.addEventListener("click", function (event) {
          // retrieving the dataset
          let product_data = event.target.dataset;
          
          // getting stripe session id
          fetch("my-stripe-checkout.php", {
              method: "POST",
              body: JSON.stringify(product_data), // passing all data attributes to the backend
            })
            .then(function (response) {
              return response.json();
            })
            .then(function (session) {
              return stripe.redirectToCheckout({ sessionId: session.id });
            })
            .then(function (result) {
              if (result.error) {
                alert(result.error.message);
              }
            })
            .catch(function (error) {
              console.error("Error:", error);
            });
        });
      });
      
      

      注意:

      product_data是一个包含所有数据属性的对象,意思是

      body: JSON.stringify(product_data)
      

      正在将一个对象传递给您的后端。

      如果你只想传递产品id,你需要这样做:

      let product_id = product_data['productId']; // camelCase of 'product-id'
      

      并将product_id 传递到您的后端。

      如果您想将event.target.dataset 转换为json 对象以供以后使用,您也可能会看到this

      使用.dataset的优势

      您可以使用 data 属性存储额外的数据,并通过调用 .dataset property 获取它们。例如,您可以为按钮添加额外的数据属性:

      <?php
        <button 
          data-product-id="<?php $row['productid']; ?>"
          data-product-description="<?php $row['productdescription']; ?>"
          data-product-price="<?php $row['productprice']; ?>"
        >
          Buy <?php echo $row['productname']; ?>
        </button>
      ?>
      

      由于您在 POST 调用中发送 product_data,因此您不必修改事件侦听器。这使您的代码具有更高的灵活性并且更易于管理。

      【讨论】:

        猜你喜欢
        • 2020-11-12
        • 1970-01-01
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多