使用Stripe和Node.js为自定义金额计费

时间:2018-01-20 15:35:01

标签: javascript html node.js stripe-payments

我将尝试尽可能彻底。所以我要做的就是向用户收取计算总体总数的百分比。我们如何得到总数?那么,总成本取决于用户回答的问题的进展。

如果用户需要特定的服务,那么成本可能会增加一点,比如100美元,但我们只想收取总额的10%,而不断变化如前所述。目前,金额是硬编码的,但由于金额根据其服务选择而变化,我不能对其进行硬编码。

我是Stripe和Node的新手,但有一种简单的方法,例如'document.getElementById'吗?类似的东西?充电和一切正常,但我相信我对路由感到困惑。

我的HTML表单(显示总计的区域):

<div class="" style="margin-top: 60px;">
   <h2 class="quote-info">Estimated total&#58; $<span id="new_text"></span> USD</h2>
   <h2 class="quote-info">Reservation deposit&#58; $<span id="new_text2"></span> USD</h2>
 </div>


 <!-- Payment form -->
    <form action="/charge" method="post" id="payment-form">
       <div class="form-row">
       <label for="card-element">
          Credit or debit card
       </label>
       <div id="card-element">
          <!-- a Stripe Element will be inserted here. -->
       </div>

       <!-- Used to display form errors -->
       <div id="card-errors"></div>
       </div>
       <input type="hidden" name="totalAmount" value="1000">
       <button>Submit Payment</button>
     </form>

我的HTML文件底部的脚本标记包含上述表单:

<script type="text/javascript">
  //Create a Stripe client
  var stripe = Stripe('my_key_should_go_here');

  // Create an instance of Elements
  var elements = stripe.elements();

  // Custom styling can be passed to options when creating an Element.
  // (Note that this demo uses a wider set of styles than the guide below.)
  var style = {
    base: {
      color: '#32325d',
      lineHeight: '24px',
      fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
      fontSmoothing: 'antialiased',
      fontSize: '16px',
      '::placeholder': {
        color: '#aab7c4'
      }
    },
    invalid: {
      color: '#fa755a',
      iconColor: '#fa755a'
    }
  };

  // Create an instance of the card Element
  var card = elements.create('card', {style: style});

  // Add an instance of the card Element into the `card-element` <div>
  card.mount('#card-element');

  // Handle real-time validation errors from the card Element.
  card.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  // Handle form submission
  var form = document.getElementById('payment-form');
  form.addEventListener('submit', function(event) {
    event.preventDefault();

    stripe.createToken(card).then(function(result) {
      if (result.error) {
        // Inform the user if there was an error
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
        // Send the token to your server
        stripeTokenHandler(result.token);
      }
    });
  });

  function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');

    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);

    form.appendChild(hiddenInput);
    var formData = JSON.stringify({
      mytoken: token.id
    });

    $.ajax({
      type: "POST",
      url: "/charge",
      data: formData,
      success: function(){alert("done")},
      dataType: "json",
      contentType: "application/json"
    });

    // alert("Created a token with value: "+token.id)
    form.submit();
  }
  </script>

最后,我的app.js文件:

const express = require('express');
const stripe = require('stripe')('deleted_key');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());

// Set Static Folder
app.use(express.static('public'));

// Index route
app.get('/charge', (req, res) => {
  res.send();
});

// charge route
app.post('/charge', (req, res) => {
  // const amount = 2500;
  const amount = req.body.totalAmount;

  stripe.customers.create({
    email: "random@gmail.com",
    source: req.body.mytoken
  })
  .then(customer =>  {
    stripe.charges.create({
    amount,
    description:'specified service description here',
    currency:'usd',
    customer:customer.id
  })})
  .then(charge => res.send('success'));
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

我的主要问题是,我如何获取HTML文件中'new_text'区域中给出的金额以便在节点中使用并向用户收费?

1 个答案:

答案 0 :(得分:0)

要使用getElementById,首先要在您的金额字段中添加ID:

<input type="hidden" name="totalAmount" id="totalAmount" value="1000">

然后您可以使用ID获取字段的值:

const amount = document.getElementById("totalAmount").value;

虽然,我可以看到你的输入类型是隐藏的 - 这是故意的吗?