Stripe API, Tutorials, Nova Framework

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());
    }
}

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.