Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Stripe PHP
https://github.com/stripe/stripe-php
Admin
The Stripe PHP library provides convenient access to the Stripe API from applications written in the
...
Tokens:
14,471
Snippets:
100
Trust Score:
8.9
Update:
3 weeks ago
Context
Skills
Chat
Benchmark
80.8
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Stripe PHP SDK The Stripe PHP SDK provides a comprehensive PHP library for integrating with the Stripe payment platform API. It enables developers to process payments, manage customers, handle subscriptions, create invoices, and implement various payment flows within PHP applications. The library supports all major Stripe API resources including PaymentIntents, Customers, Subscriptions, Checkout Sessions, Invoices, and over 100 other API objects. This SDK is designed for server-side PHP applications and follows PSR-4 autoloading standards. It provides type-safe objects for all Stripe API responses, handles authentication, request signing, webhook signature verification, and error handling automatically. The library supports both synchronous API calls and webhook-based event processing for building robust payment integrations. ## Installation Install the Stripe PHP SDK via Composer. ```bash composer require stripe/stripe-php ``` ## Configuration and Authentication Configure the Stripe client with your API key to authenticate all requests. ```php <?php require_once 'vendor/autoload.php'; // Option 1: Set global API key \Stripe\Stripe::setApiKey('sk_test_your_secret_key'); // Option 2: Use StripeClient instance (recommended) $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Configure with options $stripe = new \Stripe\StripeClient([ 'api_key' => 'sk_test_your_secret_key', 'stripe_version' => '2024-06-20', ]); ``` ## Customer Management Create and manage customer records to store payment methods and track purchase history. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a new customer $customer = $stripe->customers->create([ 'email' => 'customer@example.com', 'name' => 'John Doe', 'phone' => '+1234567890', 'address' => [ 'line1' => '123 Main St', 'city' => 'San Francisco', 'state' => 'CA', 'postal_code' => '94102', 'country' => 'US', ], 'metadata' => [ 'user_id' => '12345', 'plan' => 'premium', ], ]); echo "Created customer: " . $customer->id . "\n"; // Output: Created customer: cus_ABC123xyz // Retrieve a customer $customer = $stripe->customers->retrieve('cus_ABC123xyz'); // Update a customer $customer = $stripe->customers->update('cus_ABC123xyz', [ 'description' => 'Premium subscriber', 'metadata' => ['upgraded_at' => date('Y-m-d')], ]); // List all customers $customers = $stripe->customers->all(['limit' => 10]); foreach ($customers->data as $cust) { echo $cust->email . "\n"; } // Search customers $results = $stripe->customers->search([ 'query' => "email:'customer@example.com'", ]); // Delete a customer $deleted = $stripe->customers->delete('cus_ABC123xyz'); ``` ## PaymentIntent - Process Payments PaymentIntents represent the complete lifecycle of a payment attempt from creation to confirmation. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a PaymentIntent for a one-time payment $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 2000, // $20.00 in cents 'currency' => 'usd', 'customer' => 'cus_ABC123xyz', 'payment_method_types' => ['card'], 'description' => 'Order #12345', 'metadata' => [ 'order_id' => '12345', 'product' => 'Premium Widget', ], 'receipt_email' => 'customer@example.com', ]); echo "PaymentIntent created: " . $paymentIntent->client_secret . "\n"; // Use client_secret on frontend with Stripe.js // Create and confirm in one step $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 5000, 'currency' => 'usd', 'payment_method' => 'pm_card_visa', 'confirm' => true, 'automatic_payment_methods' => [ 'enabled' => true, 'allow_redirects' => 'never', ], ]); // Retrieve a PaymentIntent $paymentIntent = $stripe->paymentIntents->retrieve('pi_ABC123xyz'); // Confirm a PaymentIntent $paymentIntent = $stripe->paymentIntents->confirm('pi_ABC123xyz', [ 'payment_method' => 'pm_card_visa', 'return_url' => 'https://example.com/return', ]); // Capture a PaymentIntent (for manual capture) $paymentIntent = $stripe->paymentIntents->capture('pi_ABC123xyz', [ 'amount_to_capture' => 1500, // Partial capture ]); // Cancel a PaymentIntent $paymentIntent = $stripe->paymentIntents->cancel('pi_ABC123xyz', [ 'cancellation_reason' => 'requested_by_customer', ]); // List PaymentIntents $paymentIntents = $stripe->paymentIntents->all([ 'customer' => 'cus_ABC123xyz', 'limit' => 10, ]); // Search PaymentIntents $results = $stripe->paymentIntents->search([ 'query' => "status:'succeeded' AND amount>1000", ]); ``` ## Payment Methods Manage payment methods attached to customers for recurring or future payments. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a payment method (typically done client-side with Stripe.js) $paymentMethod = $stripe->paymentMethods->create([ 'type' => 'card', 'card' => [ 'number' => '4242424242424242', 'exp_month' => 12, 'exp_year' => 2025, 'cvc' => '123', ], 'billing_details' => [ 'name' => 'John Doe', 'email' => 'john@example.com', ], ]); // Attach payment method to a customer $paymentMethod = $stripe->paymentMethods->attach('pm_ABC123xyz', [ 'customer' => 'cus_ABC123xyz', ]); // Set as default payment method $stripe->customers->update('cus_ABC123xyz', [ 'invoice_settings' => [ 'default_payment_method' => 'pm_ABC123xyz', ], ]); // List customer's payment methods $paymentMethods = $stripe->customers->allPaymentMethods('cus_ABC123xyz', [ 'type' => 'card', ]); foreach ($paymentMethods->data as $pm) { echo "Card ending in " . $pm->card->last4 . "\n"; } // Detach a payment method $paymentMethod = $stripe->paymentMethods->detach('pm_ABC123xyz'); ``` ## SetupIntent - Save Payment Methods SetupIntents collect payment credentials without immediately charging, ideal for saving cards for future use. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a SetupIntent for saving a card $setupIntent = $stripe->setupIntents->create([ 'customer' => 'cus_ABC123xyz', 'payment_method_types' => ['card'], 'usage' => 'off_session', // For recurring/future charges 'metadata' => [ 'purpose' => 'subscription_setup', ], ]); echo "SetupIntent client_secret: " . $setupIntent->client_secret . "\n"; // Use on frontend to collect card details // Confirm SetupIntent (after collecting payment method on frontend) $setupIntent = $stripe->setupIntents->confirm('seti_ABC123xyz', [ 'payment_method' => 'pm_card_visa', 'return_url' => 'https://example.com/setup-complete', ]); // Retrieve a SetupIntent $setupIntent = $stripe->setupIntents->retrieve('seti_ABC123xyz'); // Check setup status if ($setupIntent->status === 'succeeded') { echo "Payment method saved: " . $setupIntent->payment_method . "\n"; } // Cancel a SetupIntent $setupIntent = $stripe->setupIntents->cancel('seti_ABC123xyz'); ``` ## Checkout Sessions Create hosted payment pages for one-time payments or subscription sign-ups. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a Checkout Session for a one-time payment $session = $stripe->checkout->sessions->create([ 'mode' => 'payment', 'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'https://example.com/cancel', 'customer_email' => 'customer@example.com', 'line_items' => [ [ 'price_data' => [ 'currency' => 'usd', 'product_data' => [ 'name' => 'Premium Widget', 'description' => 'High-quality widget with advanced features', 'images' => ['https://example.com/widget.jpg'], ], 'unit_amount' => 2999, // $29.99 ], 'quantity' => 1, ], [ 'price_data' => [ 'currency' => 'usd', 'product_data' => [ 'name' => 'Shipping', ], 'unit_amount' => 500, // $5.00 ], 'quantity' => 1, ], ], 'metadata' => [ 'order_id' => '12345', ], ]); echo "Redirect to: " . $session->url . "\n"; // Create a Checkout Session for subscription $session = $stripe->checkout->sessions->create([ 'mode' => 'subscription', 'success_url' => 'https://example.com/subscription-success', 'cancel_url' => 'https://example.com/subscription-cancel', 'customer' => 'cus_ABC123xyz', 'line_items' => [ [ 'price' => 'price_ABC123xyz', // Recurring price ID 'quantity' => 1, ], ], 'subscription_data' => [ 'trial_period_days' => 14, 'metadata' => ['plan' => 'premium'], ], ]); // Retrieve session after completion $session = $stripe->checkout->sessions->retrieve('cs_ABC123xyz', [ 'expand' => ['line_items', 'customer'], ]); // Get line items $lineItems = $stripe->checkout->sessions->allLineItems('cs_ABC123xyz'); // Expire a session $session = $stripe->checkout->sessions->expire('cs_ABC123xyz'); ``` ## Products and Prices Create products and prices for use in payments, subscriptions, and checkout. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a product $product = $stripe->products->create([ 'name' => 'Premium Plan', 'description' => 'Full access to all features', 'images' => ['https://example.com/premium.png'], 'metadata' => [ 'tier' => 'premium', 'features' => 'unlimited', ], ]); echo "Product ID: " . $product->id . "\n"; // Create a one-time price $price = $stripe->prices->create([ 'product' => $product->id, 'unit_amount' => 9999, // $99.99 'currency' => 'usd', ]); // Create a recurring price for subscriptions $recurringPrice = $stripe->prices->create([ 'product' => $product->id, 'unit_amount' => 1999, // $19.99/month 'currency' => 'usd', 'recurring' => [ 'interval' => 'month', 'interval_count' => 1, ], 'lookup_key' => 'premium_monthly', ]); // Create a tiered price $tieredPrice = $stripe->prices->create([ 'product' => $product->id, 'currency' => 'usd', 'billing_scheme' => 'tiered', 'tiers_mode' => 'graduated', 'tiers' => [ ['up_to' => 10, 'unit_amount' => 1000], ['up_to' => 100, 'unit_amount' => 800], ['up_to' => 'inf', 'unit_amount' => 500], ], 'recurring' => ['interval' => 'month'], ]); // List products $products = $stripe->products->all(['active' => true, 'limit' => 10]); // List prices for a product $prices = $stripe->prices->all([ 'product' => $product->id, 'active' => true, ]); // Update a product $product = $stripe->products->update($product->id, [ 'description' => 'Updated description', ]); // Archive a price (set inactive) $price = $stripe->prices->update($price->id, ['active' => false]); // Delete a product (only if no prices) $deleted = $stripe->products->delete($product->id); ``` ## Subscriptions Create and manage recurring billing subscriptions. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a subscription $subscription = $stripe->subscriptions->create([ 'customer' => 'cus_ABC123xyz', 'items' => [ ['price' => 'price_ABC123xyz'], ], 'default_payment_method' => 'pm_ABC123xyz', 'payment_behavior' => 'default_incomplete', 'payment_settings' => [ 'save_default_payment_method' => 'on_subscription', ], 'expand' => ['latest_invoice.payment_intent'], ]); echo "Subscription status: " . $subscription->status . "\n"; // Output: Subscription status: active // Create subscription with trial $subscription = $stripe->subscriptions->create([ 'customer' => 'cus_ABC123xyz', 'items' => [['price' => 'price_ABC123xyz']], 'trial_period_days' => 14, ]); // Retrieve a subscription $subscription = $stripe->subscriptions->retrieve('sub_ABC123xyz'); // Update subscription (change plan) $subscription = $stripe->subscriptions->update('sub_ABC123xyz', [ 'items' => [ [ 'id' => $subscription->items->data[0]->id, 'price' => 'price_new_plan', ], ], 'proration_behavior' => 'create_prorations', ]); // Add item to subscription $subscription = $stripe->subscriptions->update('sub_ABC123xyz', [ 'items' => [ ['price' => 'price_addon_feature'], ], ]); // Cancel subscription at period end $subscription = $stripe->subscriptions->update('sub_ABC123xyz', [ 'cancel_at_period_end' => true, ]); // Cancel subscription immediately $subscription = $stripe->subscriptions->cancel('sub_ABC123xyz'); // Resume a paused subscription $subscription = $stripe->subscriptions->resume('sub_ABC123xyz', [ 'billing_cycle_anchor' => 'now', ]); // List subscriptions $subscriptions = $stripe->subscriptions->all([ 'customer' => 'cus_ABC123xyz', 'status' => 'active', ]); // Search subscriptions $results = $stripe->subscriptions->search([ 'query' => "status:'active' AND metadata['plan']:'premium'", ]); ``` ## Invoices Create, manage, and finalize invoices for billing customers. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a draft invoice $invoice = $stripe->invoices->create([ 'customer' => 'cus_ABC123xyz', 'collection_method' => 'send_invoice', 'days_until_due' => 30, 'description' => 'Consulting services - January 2024', 'metadata' => ['project' => 'website_redesign'], ]); // Add invoice items $invoiceItem = $stripe->invoiceItems->create([ 'customer' => 'cus_ABC123xyz', 'invoice' => $invoice->id, 'amount' => 50000, // $500.00 'currency' => 'usd', 'description' => 'Web development - 10 hours @ $50/hr', ]); // Add another line item $stripe->invoiceItems->create([ 'customer' => 'cus_ABC123xyz', 'invoice' => $invoice->id, 'price' => 'price_hosting', // Use existing price 'quantity' => 1, ]); // Finalize the invoice $invoice = $stripe->invoices->finalizeInvoice($invoice->id); echo "Invoice PDF: " . $invoice->invoice_pdf . "\n"; echo "Hosted Invoice: " . $invoice->hosted_invoice_url . "\n"; // Send invoice to customer $invoice = $stripe->invoices->sendInvoice($invoice->id); // Pay an invoice immediately $invoice = $stripe->invoices->pay($invoice->id, [ 'payment_method' => 'pm_ABC123xyz', ]); // Void an invoice $invoice = $stripe->invoices->voidInvoice($invoice->id); // Mark as uncollectible $invoice = $stripe->invoices->markUncollectible($invoice->id); // List invoices $invoices = $stripe->invoices->all([ 'customer' => 'cus_ABC123xyz', 'status' => 'open', 'limit' => 10, ]); // Preview upcoming invoice for subscription $upcomingInvoice = $stripe->invoices->createPreview([ 'customer' => 'cus_ABC123xyz', 'subscription' => 'sub_ABC123xyz', ]); echo "Next invoice amount: $" . ($upcomingInvoice->amount_due / 100) . "\n"; ``` ## Refunds Process full or partial refunds for charges and payment intents. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Create a full refund for a PaymentIntent $refund = $stripe->refunds->create([ 'payment_intent' => 'pi_ABC123xyz', 'reason' => 'requested_by_customer', ]); echo "Refund status: " . $refund->status . "\n"; // Output: Refund status: succeeded // Create a partial refund $refund = $stripe->refunds->create([ 'payment_intent' => 'pi_ABC123xyz', 'amount' => 500, // Refund $5.00 of the charge ]); // Refund by charge ID (legacy) $refund = $stripe->refunds->create([ 'charge' => 'ch_ABC123xyz', 'amount' => 1000, 'reason' => 'duplicate', 'metadata' => ['reason_detail' => 'Customer charged twice'], ]); // Retrieve a refund $refund = $stripe->refunds->retrieve('re_ABC123xyz'); // Update refund metadata $refund = $stripe->refunds->update('re_ABC123xyz', [ 'metadata' => ['processed_by' => 'support_team'], ]); // List refunds $refunds = $stripe->refunds->all([ 'payment_intent' => 'pi_ABC123xyz', 'limit' => 10, ]); // Cancel a pending refund $refund = $stripe->refunds->cancel('re_ABC123xyz'); ``` ## Charges Retrieve and manage charge records (use PaymentIntents for new integrations). ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Retrieve a charge $charge = $stripe->charges->retrieve('ch_ABC123xyz'); echo "Charge amount: $" . ($charge->amount / 100) . "\n"; echo "Status: " . $charge->status . "\n"; echo "Payment method: " . $charge->payment_method . "\n"; // List charges $charges = $stripe->charges->all([ 'customer' => 'cus_ABC123xyz', 'limit' => 10, ]); // Search charges $results = $stripe->charges->search([ 'query' => "amount>5000 AND status:'succeeded'", ]); // Update charge metadata $charge = $stripe->charges->update('ch_ABC123xyz', [ 'description' => 'Order #12345', 'metadata' => ['order_id' => '12345'], ]); // Capture an uncaptured charge $charge = $stripe->charges->capture('ch_ABC123xyz', [ 'amount' => 1500, // Capture less than authorized ]); ``` ## Webhook Event Handling Verify and process webhook events from Stripe for real-time updates. ```php <?php require_once 'vendor/autoload.php'; // Webhook endpoint handler $payload = @file_get_contents('php://input'); $sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE']; $webhookSecret = 'whsec_your_webhook_secret'; try { $event = \Stripe\Webhook::constructEvent( $payload, $sigHeader, $webhookSecret ); } 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; echo "Payment succeeded: " . $paymentIntent->id . "\n"; // Fulfill the order break; case 'payment_intent.payment_failed': $paymentIntent = $event->data->object; echo "Payment failed: " . $paymentIntent->last_payment_error->message . "\n"; // Notify customer break; case 'customer.subscription.created': $subscription = $event->data->object; echo "Subscription created: " . $subscription->id . "\n"; // Provision access break; case 'customer.subscription.updated': $subscription = $event->data->object; echo "Subscription updated: " . $subscription->status . "\n"; break; case 'customer.subscription.deleted': $subscription = $event->data->object; echo "Subscription canceled: " . $subscription->id . "\n"; // Revoke access break; case 'invoice.paid': $invoice = $event->data->object; echo "Invoice paid: " . $invoice->id . "\n"; break; case 'invoice.payment_failed': $invoice = $event->data->object; echo "Invoice payment failed for customer: " . $invoice->customer . "\n"; // Notify customer to update payment method break; case 'checkout.session.completed': $session = $event->data->object; echo "Checkout completed: " . $session->id . "\n"; // Fulfill order or provision subscription break; default: echo "Unhandled event type: " . $event->type . "\n"; } http_response_code(200); ``` ## Error Handling Handle API errors gracefully with Stripe's exception classes. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); try { $charge = $stripe->charges->create([ 'amount' => 2000, 'currency' => 'usd', 'source' => 'tok_invalid', ]); } catch (\Stripe\Exception\CardException $e) { // Card was declined echo "Card error: " . $e->getError()->message . "\n"; echo "Decline code: " . $e->getDeclineCode() . "\n"; echo "Error code: " . $e->getStripeCode() . "\n"; } catch (\Stripe\Exception\RateLimitException $e) { // Too many requests echo "Rate limit exceeded. Retry after: " . $e->getHttpHeaders()['Retry-After'] . "\n"; } catch (\Stripe\Exception\InvalidRequestException $e) { // Invalid parameters echo "Invalid request: " . $e->getMessage() . "\n"; } catch (\Stripe\Exception\AuthenticationException $e) { // Invalid API key echo "Authentication failed: " . $e->getMessage() . "\n"; } catch (\Stripe\Exception\ApiConnectionException $e) { // Network error echo "Network error: " . $e->getMessage() . "\n"; } catch (\Stripe\Exception\ApiErrorException $e) { // Generic Stripe error echo "Stripe error: " . $e->getMessage() . "\n"; echo "HTTP status: " . $e->getHttpStatus() . "\n"; } ``` ## OAuth Connect Implement Stripe Connect OAuth flow for platform integrations. ```php <?php $stripe = new \Stripe\StripeClient('sk_test_your_secret_key'); // Generate OAuth authorization URL $clientId = 'ca_ABC123xyz'; $authorizeUrl = 'https://connect.stripe.com/oauth/authorize?' . http_build_query([ 'response_type' => 'code', 'client_id' => $clientId, 'scope' => 'read_write', 'redirect_uri' => 'https://example.com/oauth/callback', 'state' => bin2hex(random_bytes(16)), // CSRF protection ]); echo "Redirect user to: " . $authorizeUrl . "\n"; // Handle OAuth callback - exchange code for access token $code = $_GET['code']; $response = $stripe->oauth->token([ 'grant_type' => 'authorization_code', 'code' => $code, ]); $connectedAccountId = $response->stripe_user_id; $accessToken = $response->access_token; $refreshToken = $response->refresh_token; echo "Connected account: " . $connectedAccountId . "\n"; // Deauthorize a connected account $stripe->oauth->deauthorize([ 'client_id' => $clientId, 'stripe_user_id' => $connectedAccountId, ]); ``` ## Summary The Stripe PHP SDK enables comprehensive payment integration supporting one-time payments via PaymentIntents, recurring billing through Subscriptions, hosted checkout flows with Checkout Sessions, and invoice management. The library handles customer management, payment method storage, refund processing, and Connect platform features. All API resources follow consistent patterns with create, retrieve, update, delete, and list operations, making it straightforward to implement any payment workflow. Common integration patterns include: using PaymentIntents with Stripe.js for secure card collection, implementing SetupIntents to save cards for future use, creating Checkout Sessions for hosted payment pages, building subscription billing with automatic invoicing, processing webhooks for real-time event handling, and connecting third-party accounts via OAuth for marketplace platforms. The SDK's robust error handling, automatic retries, and idempotency support make it suitable for production payment processing at any scale.