Fatal error: Class 'Stripe\Stripe_Charge' not found in

6.1k views Asked by At

This is the code I'm using.

    <?php

        require_once('init.php');

if ($_POST) {
  \Stripe\Stripe::setApiKey("xxxxxxxxxxxxx");
  $error = '';
  $success = '';
  try {
    if (!isset($_POST['stripeToken']))
      throw new Exception("The Stripe Token was not generated correctly");
    $charge = \Stripe\Stripe_Charge::create(array("amount" => 100, //995
                                "currency" => "eur",
                                "card" => $_POST['stripeToken']));
    $success = 'Your payment was successful.';
  }
  catch (Exception $e) {
    $error = $e->getMessage();
  }
}

?>

Why am I getting the error

"Fatal error: Class 'Stripe\Stripe_Charge' not found in"

2

There are 2 answers

0
discry On

I discovered that neither UsageRecord.php nor UsageRecordSummary.php were available in my stripe-php/lib directory and likewise not initiated in my stripe-php/init.php. I went and grabbed them from https://github.com/stripe/stripe-php/blob/master/lib/

Using Composer to install. adam-paterson/oauth2-stripe. Not sure if this is missing there.

0
kojow7 On

I was pulling my hair out on this one as well, but finally found the solution.

From what I found out older versions of PHP (<5.3) did not use namespaces. To get around this PSR-0* converted underscores to directory names. This created a messy interface for Composer. Now with PHP 5.3 and higher namespaces have been added. Composer now uses PSR-4 which supports namespaces but does not convert underscores to directories. Therefore, if you are using the newer preferred PSR-4, you need to use the new method. Therefore, your line:

$charge = \Stripe\Stripe_Charge::create(...);

needs to become:

$charge = \Stripe\Charge::create(...);

You can double check to see what version of PSR your Stripe module is using by opening the /vendor/stripe/stripe-php/composer.json file. Mine shows:

"autoload": {
  "psr-4": { "Stripe\\" : "lib/" }
},

which clearly states that I am using PSR-4.

Here is some good reading on the subject: https://mattstauffer.co/blog/a-brief-introduction-to-php-namespacing

*PSR stands for PHP Standards Recommendation