Variable amount handling (donation) with Stripe & PHP
I need to allow users to enter custom amounts using Stripe. They enter what they want to pay in the tab. Then I have a script that collects the sum below the standard strip check button. But how should I handle the charging server 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();
?>
source to share
In <form>
where you place Checkout, you also want to add an input to collect the amount from the user. Pay attention to the name I gave my name inputamount
<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>
In your backend you can grab this field amount
when Checkout is sent, just like the token generated by Stripe
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
// your code to create a charge
// ...
If you want to dynamically change the quantity displayed in the Checkout window, you must use a Custom Checkout and not the basic Checkout block, or it may not update correctly.
See https://stripe.com/docs/checkout#integration-custom
Or, for fiddle: https://jsfiddle.net/ywain/g2ufa8xr/
source to share