Back

Step by Step Guide to Building a Stripe API Integration in PHP

Jul 19, 20247 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of online payments? Stripe's API is your ticket to hassle-free transactions, and we're about to make it even easier with PHP. We'll be using the stripe/stripe-php package, so buckle up and let's get started!

Prerequisites

Before we jump in, make sure you've got:

  • A PHP environment (you're a pro, so I'm sure you've got this covered)
  • Composer installed (because who doesn't love dependency management?)
  • A Stripe account with API keys (if you don't have one, go grab it – it's free!)

Installation

First things first, let's get that Stripe PHP package installed:

composer require stripe/stripe-php

Easy peasy, right?

Configuration

Now, let's set up those API keys and get Stripe initialized:

require_once 'vendor/autoload.php'; \Stripe\Stripe::setApiKey('your_secret_key_here');

Pro tip: Keep your API keys safe and out of version control. Use environment variables or a config file that's not tracked by git.

Basic API Operations

Creating a Customer

Let's create a customer – it's like rolling out the red carpet for your users:

$customer = \Stripe\Customer::create([ 'email' => '[email protected]', 'name' => 'John Doe' ]);

Adding a Payment Method

Time to arm your customer with a payment method:

$paymentMethod = \Stripe\PaymentMethod::create([ 'type' => 'card', 'card' => [ 'number' => '4242424242424242', 'exp_month' => 7, 'exp_year' => 2024, 'cvc' => '314', ], ]); $customer->attachPaymentMethod($paymentMethod->id);

Creating a Charge

Now for the fun part – let's make it rain:

$charge = \Stripe\Charge::create([ 'amount' => 2000, // That's $20.00 'currency' => 'usd', 'customer' => $customer->id, 'source' => $paymentMethod->id, ]);

Handling Webhooks

Webhooks are like Stripe's way of sliding into your DMs. Here's how to handle them:

$endpoint_secret = 'whsec_...'; $payload = @file_get_contents('php://input'); $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE']; try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $endpoint_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload http_response_code(400); exit(); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid signature http_response_code(400); exit(); } // Handle the event switch ($event->type) { case 'payment_intent.succeeded': $paymentIntent = $event->data->object; // Then define and call a method to handle the successful payment intent. break; // ... handle other event types default: echo 'Received unknown event type ' . $event->type; } http_response_code(200);

Error Handling

Errors happen. Let's catch 'em all:

try { // Your Stripe API call here } catch(\Stripe\Exception\CardException $e) { // Since it's a decline, \Stripe\Exception\CardException will be caught echo 'Status is:' . $e->getHttpStatus() . '\n'; echo 'Type is:' . $e->getError()->type . '\n'; echo 'Code is:' . $e->getError()->code . '\n'; // param is '' in this case echo 'Param is:' . $e->getError()->param . '\n'; echo 'Message is:' . $e->getError()->message . '\n'; } catch (\Stripe\Exception\RateLimitException $e) { // Too many requests made to the API too quickly } catch (\Stripe\Exception\InvalidRequestException $e) { // Invalid parameters were supplied to Stripe's API } catch (\Stripe\Exception\AuthenticationException $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) } catch (\Stripe\Exception\ApiConnectionException $e) { // Network communication with Stripe failed } catch (\Stripe\Exception\ApiErrorException $e) { // Display a very generic error to the user, and maybe send // yourself an email } catch (Exception $e) { // Something else happened, completely unrelated to Stripe }

Testing

Remember, Stripe has a test mode. Use it! Create test customers, payments, and events to make sure everything's working smoothly before you go live.

Security Considerations

  • Never, ever store raw card data. That's what Stripe is for!
  • Use Stripe.js or Elements to collect card info client-side.
  • Keep your API keys secret and secure.
  • Stay PCI compliant by letting Stripe handle the sensitive stuff.

Conclusion

And there you have it! You're now armed and dangerous with Stripe integration skills. Remember, this is just scratching the surface – Stripe can do so much more. Play around with subscriptions, invoices, and refunds when you're ready to level up.

Keep coding, keep learning, and may your transactions always be successful! 🚀💳