Loading...

Stripe API validate a subscription plan exists

David Carr

1 min read - 26th Aug, 2017

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

 

0 comments
Add a comment