首页 文章

使用Stripe和PHP处理可变金额(捐赠)

提问于
浏览
5

我需要允许用户使用Stripe输入自定义金额 . 他们输入他们想要输入的内容 . 然后我有一个脚本收集默认条带结帐按钮下面的金额 . 但我怎么能在 charge.php 上处理充电服务器端?

donation.php

//user enter custom amount
    <input type="number" class='form-control' 
    id="custom-donation-amount" 
    placeholder="$50.00" min="0" step="10.00 " />

    //default stripe checkout button
      <script
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key="pk_test_XXXXXXXXXXXXXXX"
        data-amount="0"
        data-name="ORGANIZATION"
        data-description="Saving Penguins"
        data-image="logo.png"
        data-locale="auto"
        data-zip-code="true"
        data-billing-address="true"
        data-label="DONATE"
        data-currency="usd">
      </script>

//script to collect variable amount
  <script type="text/javascript">
    $(function() {
        $('.donate-button').click(function(event) {
            var amount = $('#custom-donation-amount').val();        
            $('.stripe-button').attr('data-amount', amount)
        });
    });
</script>

charge.php

<?php require_once('./config.php');

  $token  = $_POST['stripeToken'];
  $email  = $_POST['stripeEmail'];

  $customer = \Stripe\Customer::create(array(
      'source'  => $token,
      'email' => $email)
  );

  $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $amount,
      'currency' => 'usd'
  ));

   header("Location: confirmation.php");
die();


?>

1 回答

  • 7

    在你放置Checkout的 <form> 内,你'd also want to add an input to collect the Amount from the user. Note the name I' ve给我的输入名称 amount

    <form method="POST" action="/charge.php">
    <input type="number" class="form-control" name="amount" id="custom-donation-amount" placeholder="50.00" min="0" step="10.00" />
    <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_XXXXXXXXXXXXXXX"
    data-name="ORGANIZATION"
    data-description="Saving Penguins"
    data-image="logo.png"
    data-locale="auto"
    data-billing-address="true"
    data-label="DONATE"
    data-currency="usd">
    </script>
    </form>
    

    在你的后端,你可以在Checkout提交时 grab 这个 amount 字段,就像你在Stripe创建的令牌一样

    $token  = $_POST['stripeToken'];
    $email  = $_POST['stripeEmail'];
    $amount = $_POST['amount'];
    
    // your code to create a charge
    // ...
    

    如果您希望动态更改Checkout窗口中显示的金额,则应使用Custom Checkout,而不是基本的Checkout块,否则可能无法正确更新 .

    https://stripe.com/docs/checkout#integration-custom

    或者,对于小提琴:https://jsfiddle.net/ywain/g2ufa8xr/

相关问题