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

时间:2017-07-30 20:52:00

标签: php stripe-payments

我需要允许用户使用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 个答案:

答案 0 :(得分:8)

在您放置Checkout的<form>内,您还需要添加输入以从用户收集金额。请注意我输入的名称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提交时,您可以在后端获取此amount字段,就像Stripe创建的令牌一样

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

// your code to create a charge
// ...

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

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

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