Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

djave_co's avatar

How / When to initialize Stripe

I have a class like this:

class ServiceStripePlan{

    public static function delete(Service $service){

        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        $plan = Stripe\Plan::retrieve($service->id);
        return $plan->delete();

    }

    public static function create(Service $service){

        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        $plan = Stripe\Plan::create([
            "amount" => $service->rate * 100,
            "name" => $service->name,
            "id" => $service->id,
            "interval" => $service->interval,
            "currency" => "gbp",
        ]);

        return $plan;

    }

}

It seems a bit weird to initialize Stripe with the Stripe\Stripe::setApiKey(env('STRIPE_SECRET')); in two different places. Am I doing something wrong / is there a nicer way of doing this? As this class gets bigger then I'll need this in every single function.

Thanks D

0 likes
2 replies
tkjaergaard's avatar

I would definitely put Stripe\Stripe::setApiKey(env('STRIPE_SECRET')); into a ServiceProvider. Either make a StripeServiceProvider or just simply use the AppServiceProvider.

This way Stripe is ready to use everywhere in your application and so much easier to maintain.

https://laravel.com/docs/5.2/providers

1 like
kahriman's avatar
Level 30

I would put stripe key in config/services.php


return [
'stripe' => [
        'model'  =>'',
        'key' => '',
        'secret' => '',
    ]
]

the problem working with static methods. Try not to use it.


class ServiceStripePlan {

private $stripe;
private $stripePlan;

public function __construct(Stripe\Stripe $stripe, Stripe\Plan $stripePlan)
{
    $key = config('stripe.key');
    $this->stripe::setApiKey($key);
    $this->stripePlan = $stripePlan;
}


public function delete(Service $service)
{
    return $this->stripePlan::retrieve($service->id)->delete();
}

public function create(Service $service)
{
    return $this->stripePlan::create([
        "amount" => $service->rate * 100,
        "name" => $service->name,
        "id" => $service->id,
        "interval" => $service->interval,
        "currency" => "gbp",
    ]);
}

}

Please or to participate in this conversation.