Stripe API | Nova Framework | Tutorials

David Carr

Stripe API validate a subscription plan exists

Before using a plan it's a good idea to make sure it exists in Stripe, this post will cover how to do just that.

I’m using Nova Framework not setup with Nova? please read Getting Stripe API setup with Nova Framework

I’m going to make a protected method called getPlan so other methods can easily get a plan.

protected function getPlan($plan_id)
{
    try {
        return Plan::retrieve($plan_id);
    } catch (Exception $e) {
        dd('Stripe Plan not found! error: '.$e->getMessage());
    }
}

The plan will be returned containing an array as long as it exists, if not then an exception is thrown. Use a try and catch to deal with both cases.

Another use case.

Return a plan a user is subscribed to. In this case, check the user is logged in and use their plan_id from the database to return the plan.

protected function getPlan()
{
    //if not logged in return
    if (!Auth::check()) {
        return null;
    }

    //assign stripe customer from db
    $plan_id = Auth::user()->plan_id;

    //no customer id
    if ($plan_id == null) {
        return null;
    }

    //get customer record from stripe
    try {
        return Plan::retrieve($plan_id);
    } catch (Exception $e) {
        dd('Stripe Plan not found! error: '.$e->getMessage());
    }
}

 

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2020 DC Blog. All code MIT license. All rights reserved.