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

Seb*_*ham 6 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>
Run Code Online (Sandbox Code Playgroud)

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();


?>
Run Code Online (Sandbox Code Playgroud)

duc*_*uck 8

<form>您放置Checkout的位置,您还需要添加输入以从用户收集金额.请注意我给我输入的名称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>
Run Code Online (Sandbox Code Playgroud)

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

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

// your code to create a charge
// ...
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • @DeltaFlyer您始终需要一个后端!但这并不需要太多。您可以在任何Web主机上使用Heroku,AWS Lambda之类的小型实例。 (2认同)