Skip to content

Migration to StripeClient and services in 7.33.0

remi-stripe edited this page Sep 15, 2021 · 6 revisions

Starting with 7.33.0 of the library, we released a new StripeClient class which lets you interact with the API without using static methods or having to retrieve a resource before deleting it for example.

Table of Contents

Legacy approach

In the past, your code would look like this

<?php
// Initialize the API key
\Stripe\Stripe::setApiKey('sk_test_xxx');

// Retrieve the customer and then delete it
$customer = \Stripe\Customer::retrieve('cus_xxx');
$customer->delete();

// Create a Coupon
$coupon = \Stripe\Coupon::create([
  'percent_off' => 25,
  'duration' => 'repeating',
  'duration_in_months' => 3,
]);

// Retrieve and confirm a PaymentIntent
$paymentIntent = \Stripe\PaymentIntent::retrieve('pi_123');
$paymentIntent->confirm([
  'payment_method' => 'pm_card_visa'
];

// Create a Checkout Session
$checkoutSession = \Stripe\Checkout\Session::create([
  'success_url' => 'https://www.example.com/success',
  'cancel_url' => 'https://www.example.com/failure',
  'payment_method_types' => ['card'],
  'line_items' => [
    [
      'price' => 'price_ABCDE',
      'quantity' => 2,
    ],
  ],
]);

// Retrieve a Checkout Session and expand line_items
// Note the first array having the id as a key which was hard to figure out
$checkoutSession = \Stripe\Checkout\Session::retrieve([
  'id' => 'cs_test_123',
  'expand' => ['line_items'],
]);

Client and Services

Instead, with the new client/services infrastructure, you can do this:

<?php
// Initialize the API key
$stripe = new \Stripe\StripeClient('sk_test_xxxx');

// Create a coupon
$coupon = $stripe->coupons->create([
  'percent_off' => 25,
  'duration' => 'repeating',
  'duration_in_months' => 3,
]);

// Confirm a PaymentIntent
$paymentIntent = $stripe->paymentIntents->confirm(
  'pi_1DeQ7b2eZvKYlo2C5FUypnEA',
  ['payment_method' => 'pm_card_visa']
);

// Create a Checkout Session
$checkoutSession = $stripe->checkout->sessions->create([
  'success_url' => 'https://example.com/success',
  'cancel_url' => 'https://example.com/cancel',
  'payment_method_types' => ['card'],
  'line_items' => [
    [
      'price' => 'price_ABCDE',
      'quantity' => 2,
    ],
  ],
]);

// Retrieve a Checkout Session and expand line_items
$checkoutSession = $stripe->checkout->sessions->retrieve(
  'cs_test_123',
  [
    'expand' => ['line_items'],
  ]
);