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!
Before we jump in, make sure you've got:
First things first, let's get that Stripe PHP package installed:
composer require stripe/stripe-php
Easy peasy, right?
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.
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' ]);
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);
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, ]);
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);
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 }
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.
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! 🚀💳