We’re going to create a simple example demonstrating how to accept payments using Checkout in the browser and PHP on the server.
You’ll need to have the following before going any further:
- A PHP >= 5.3.3 environment
- The Stripe PHP library
Let’s create a file called
config.php, where we’re going to set up some initial configuration.
<?php require_once('vendor/autoload.php'); $stripe = array( "secret_key" => "sk_test_BQokikJOvBiI2HlWgH4olfQ2", "publishable_key" => "pk_test_g6do5S237ekq10r65BnxO6S0" ); \Stripe\Stripe::setApiKey($stripe['secret_key']); ?>
require_once() line assumes you’ve installed the Stripe PHP library via Composer. After then including the Composer autoloader, Composer will take care of dynamically loading the necessary classes.
Also note that we’ve placed your test API keys in the example above. You’ll need to swap it out with your live keys in production. You can see all your keys in the Dashboard.
Next let’s create the form that’s going to do the charging. We’re going to use Checkout, an embedded HTML form that will take care of form validation, error handling, and sending credit card numbers securely to Stripe.
<?php require_once('./config.php'); ?> <form action="charge.php" method="post"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="<?php echo $stripe['publishable_key']; ?>" data-description="Access for a year" data-amount="5000" data-locale="auto"></script> </form>
Notice we’re passing through an amount and description. These are just for display purposes only, they don’t get passed onto Stripe. Instead, once the user completes the Checkout process, a hidden field will be inserted into the form called
stripeToken, and then the form submitted to the server.
charge.php, we can use the
stripeToken POST parameter to actually charge the card:
<?php require_once('./config.php'); $token = $_POST['stripeToken']; $email = $_POST['stripeEmail']; $customer = \Stripe\Customer::create(array( 'email' => $email, 'source' => $token )); $charge = \Stripe\Charge::create(array( 'customer' => $customer->id, 'amount' => 5000, 'currency' => 'usd' )); echo '<h1>Successfully charged $50.00!</h1>'; ?>
And that’s it! Couldn’t be more simple.