Back to home

Get StartedSetting up .envMaking a simple charge with Stripe APIResources and Further Reading
Creating your first Stripe Charge with Slim + PHP in 5 minutes main image

Creating your first Stripe Charge with Slim + PHP in 5 minutes

In this short series, we are going to look at how to create a charge to Stripe in a number of their officially supported languages!

In this article, we are going to look at how to do so with PHP and Slim.

The expectations are that you have PHP + Composer installed and have your Stripe API keys setup and ready to go.

Get Started

Ensure composer is installed correctly and run the following. Note that you need to ensure that the downloaded composer.phar file from the installation instructions must be in your $PATH as composer.

1 2 3 4 5 6 7 8 9 10 11 mkdir slim-stripe && cd slim-stripe composer require slim/slim:"4.*" # required to enable App::Run() etc without manual ServerRequest composer require slim/psr7 # installing for Stripe composer require stripe/stripe-php # required to read dotenv vars composer require vlucas/phpdotenv mkdir -p src/public touch src/public/index.php touch .env

To check Slim is up and working, add this to src/public/index.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/../../vendor/autoload.php'; $app = AppFactory::create(); $app->get('/', function (Request $request, Response $response, $args) { $response->getBody()->write("Hello world!"); return $response; }); $app->run();

Once completed, change into src/public and run php -S localhost:8080.

If we now ping curl localhost:8080 we will see our Hello world! response.

Setting up .env

Our .env file should contain our keys for development. Get these from your Stripe Developer dashboard.

Add the following to the .env file in the root of your project directory:

1 2 SK_TEST_KEY= sk_test... PK_TEST_KEY=pk_test...

Making a simple charge with Stripe API

Let us update src/public/index.php to take a simple request to make a charge to our Stripe account.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/../../vendor/autoload.php'; $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../..'); $dotenv->load(); $stripeKey = getenv('SK_TEST_KEY'); \Stripe\Stripe::setApiKey($stripeKey); $app = AppFactory::create(); // Parse json, form data and xml $app->addBodyParsingMiddleware(); $app->addRoutingMiddleware(); $app->addErrorMiddleware(true, true, true); $app->get('/', function (Request $request, Response $response, $args) { $response->getBody()->write("Hello world!"); return $response; }); $app->post('/api/charge', function (Request $request, Response $response, $args) { try { $data = $request->getParsedBody(); // parse attributes from JSON $receiptEmail = $data['receiptEmail']; $amount = $data['amount']; // create the charge $charge = \Stripe\Charge::create([ 'amount' => $amount, 'currency' => 'usd', 'source' => 'tok_visa', 'receipt_email' => $receiptEmail ]); $response->getBody()->write('Successful charge'); $response->withStatus(201); return $response; } catch (Exception $e) { $response->getBody()->write('Failed charge'); $response->withStatus(500); return $response; } }); $app->run();

Note that in the above example we are loading keys from .env, setting the Stripe API key, then using Slim 4's body parsing middleware to help us with parsing the request body from JSON.

If we run http POST http://localhost:8080/api/charge amount:=1700 receiptEmail=hello_slim@example.com (using HTTPie) from the console, we will get our Successful charge message back.

I chose to use HTTPie because I feel it is a fun tool that more should know about! Alternative, you could do the above using curl as well (or anything that can make a POST request for a matter of fact).

1 2 3 4 curl --header "Content-Type: application/json" \ --request POST \ --data '{"amount":1700,"receiptEmail":"hello_slim@example.com"}' \ http://localhost:8080/api/charge

If you now go and check your Stripe dashboard, you will be able to see a charge.

Stripe Dashboard

Stripe Dashboard

Resources and Further Reading

  1. Composer installation
  2. Getting started with Slim
  3. Request Object - Slim
  4. PHP Exceptions
  5. Receiving input into a Slim 4 application
  6. PHP Dotenv
  7. Stripe PHP Github
  8. Stripe API
  9. getParsedBody Slim

Image credit: Sai Kiran Anagani