Using Checkout and PHP

    This tutorial will help you integrate Stripe and PHP. If you need help after reading this, search our documentation or check out answers to common questions. You can even chat live with other developers in #stripe on freenode.

    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:

    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_6pRNASCoBOKtIshFeQd4XMUh"
    );
    
    \Stripe\Stripe::setApiKey($stripe['secret_key']);
    ?>

    The 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.

    In charge.php, we can use the stripeToken POST parameter to actually charge the card:

    <?php
      require_once('./config.php');
    
      $token  = $_POST['stripeToken'];
    
      $customer = \Stripe\Customer::create(array(
          'email' => 'customer@example.com',
          '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. You can find the full source code for this tutorial here.