将实时更新传递给Stripe Checkout金额

时间:2015-02-01 19:46:55

标签: javascript ruby-on-rails stripe-payments pusher

我正在尝试在Stripe Checkout UI中实现一个可变价格,该价格将由Pusher更新。

首先,我将Pusher消息分配给名为 price 的全局变量。

  <script type="text/javascript">
      var pusher = new Pusher('7a5433c6fc39502a4a02');
      var channel = pusher.subscribe('the_channel');
      var price
      channel.bind('the_event', function(data) {
      price = data.message
      });
  </script>

如果我将价格分配给数据金额,我会面临两个问题:

1-在流程方面,默认情况下该字段为空,仅在Pusher发送消息时填充。

2-语法方面,当推送时,变量当前甚至不呈现消息

<%= form_tag charges_path, class: 'stripeform' do %>
    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
            data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
            data-amount= <%= @price %>
    </script>
<% end %>

怎么办?

1 个答案:

答案 0 :(得分:4)

我建议您在Rails控制器中为@price设置默认值。

然后按照Stripe上的文档,你可以使用这样的东西来创建一个价格可变的按钮。请记住,正如条纹文档所说,您仍然需要以正确的金额创建费用

<script src="https://checkout.stripe.com/checkout.js"></script>

<div id="price-display">$<%= @price %></div>
<button id="customButton">Purchase</button>

<script>
  var price = parseInt("<%= @price %>");

  var pusher = new Pusher('7a5433c6fc39502a4a02');
  var channel = pusher.subscribe('the_channel');
  channel.bind('the_event', function(data) {
    price = parseInt(data.message);
    document.getElementById('price-display').innerHTML = "$" + data.message;
  });

  var handler = StripeCheckout.configure({
    key: "<%= Rails.configuration.stripe[:publishable_key] %>",
    image: '/square-image.png',
    token: function(token) {
      // Use the token to create the charge with a server-side script.
      // You can access the token ID with `token.id`
    }
  });

  $('#customButton').on('click', function(e) {
    // Open Checkout with further options
    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: price
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation
  $(window).on('popstate', function() {
    handler.close();
  });
</script>

请点击此处了解更多与条纹相关的信息:https://stripe.com/docs/checkout#integration-custom