Stripe API for Subscription

Ritesh Sharma February 10, 2020

Stripe API for Subscription

There are many payment gateways that provide subscription APIs for membership plans. One of them is Stripe, which is very easy to understand and implement. The APIs for plan creation, subscription and cancellation code in Stripe are as follows:

Create a Plan

Admin can create the plans with the name of a plan, interval and amount that returns the Plan ID on submitting data through Stripe API.


Controller

public function createPlan(){
  // Takes raw data from the request
  //$json = '{"name":"Bronze Membership","interval":"month","amount":"500"}';
  $json = file_get_contents('php://input');
  if(empty($json)){
    echo json_encode(array("response"=>"-1","message"=>"Server error.")); die;
  }
  // Converts it into a PHP object
  $data = json_decode($json);
  $response = $this->apimodel->createPlan($data);
  echo $response; 
}

Model

function createPlan($data){
  $plan = $this->stripe_lib->create_plan($data); 
  if($plan['id']){
    $this->db->insert("plans",array("name"=>$data->name,"plan_id"=>$plan['id'],"amount"=>$data->amount/100,"time_interval"=>$data->interval));
    return json_encode(array("response"=>"1","message"=>"Plan added successfully."));
  }
}

Subscribe Plan

Plan id is provided while creating plan on stripe. Customer id and plan id are required for subscription to a plan.  This service provides a subscription id which can be further used to cancel/update the subscription of a user.

Controller

public function subscribeplan(){
  // Takes raw data from the request
  //$json = '{"plan_id":"plan_GQeaLzjDWeK5BL","user_id":"2"}';
  $json = file_get_contents('php://input');
  if(empty($json)){
    echo json_encode(array("response"=>"-1","message"=>"Server error.")); die;
  }
  // Converts it into a PHP object
  $data = json_decode($json);
  $response = $this->apimodel->subscribeplan($data);
  echo $response; 
}

Model

function subscribeplan($data){
  $data->customer_id = "cus_GPtoFlO7qzJO6E";
  $plan = $this->stripe_lib->subscribe($data); 
  if($plan){
    $this->db->insert("orders",array("user_id"=>$data->user_id,"plan_id"=>$data->plan_id,"sub_id"=>$plan['id']));
    return json_encode(array("response"=>"1","message"=>"Plan subscribed successfully."));
  }
}

Cancel Subscription

Cancel subscription api requires subscription id saved at time of subscription.

Controller

public function cancelSubscription(){
  // Takes raw data from the request
  //$json = '{"subscription_id":"sub_GR3gIr9Zjy4UIg"}';
  $json = file_get_contents('php://input');
  if(empty($json)){
    echo json_encode(array("response"=>"-1","message"=>"Server error.")); die;
  }
  // Converts it into a PHP object
  $data = json_decode($json);
  $response = $this->apimodel->cancelSubscription($data);
  echo $response; 
}

Model

function cancelSubscription($data){
  $plan = $this->stripe_lib->cancelSubscription($data); 
  $this->db->where("sub_id",$data->subscription_id);
  $this->db->update("orders",array("order_status"=>"1","updated_on"=>date("Y-m-d H:i:s")));
  return json_encode(array("response"=>"1","message"=>"Subscription cancelled successfully."));
}

The following code contains the methods called from the functions in model file.

function create_plan($data){
  $currency = $this->CI->config->item('stripe_currency');
  try { 
    $response = \Stripe\Plan::create([
      'amount' => $data->amount,
      'currency' => $currency,
      'interval' => $data->interval,
      'product' => ['name' => $data->name],
    ]);
    // Retrieve plan details 
    $Json = $response->jsonSerialize(); 
    return $Json; 
  }catch(Exception $e) { 
    $this->api_error = $e->getMessage(); 
    return json_encode(array("response"=>"-1","message"=>$this->api_error)); die;
  } 
}

function subscribe($data){
  try { 
    $response = \Stripe\Subscription::create([
      'customer' => $data->customer_id,
      'items' => [['plan' => $data->plan_id]],
    ]);
    // Retrieve plan details 
    $Json = $response->jsonSerialize(); 
    return $Json; 
  }catch(Exception $e) { 
    $this->api_error = $e->getMessage(); 
    return json_encode(array("response"=>"-1","message"=>$this->api_error)); die;
  } 
}

function cancelSubscription($data){
  $subscription = \Stripe\Subscription::retrieve(
    $data->subscription_id
  );
  $subscription->delete();
}

Hope these APIs work well for you. Any feedback or suggestions are most welcome.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you take your API development to the next level!

Lets’s Talk

About your ideas and concept