Manu
Manu

Reputation: 119

How to Cancel the Braintree Subscription by Braintree_id or subscription_id using Laravel Cashier

We are using Laravel Cashier (Braintree) with Laravel version 5.8. We have a case where a user is subscribed to same plan with same name multiple times for different orders. We want to give the ability to user to cancel their subscription. we tried below statement to cancel the subscription with subscription name as suggested by manual here https://laravel.com/docs/5.8/braintree#cancelling-subscriptions.

$user->subscription('main')->cancel();

$user->subscription('main')->cancelNow();

We are passing the subscription name. It works fine as expected and also updating the date in "ends_at" column of subscription table.

The problem here is that as we have same name for the subscriptions where user is subscribed to. So in our case it returns the last subscribed order here and cancel that. It's fine as what it is suppose to do.

But we want to cancel the subscription based on braintree_id stored in subscriptions table. Can we do that ? As of now we tried it like below:-

use Braintree\Subscription;

$subcriptionObj = Subscription::find($subscription); //where $subscription is braintree_id from subscriptions table.
if ($subcriptionObj->status == 'Canceled')
    abort(400, 'Subscription Not Active');

Subscription::cancel($subscription);

This however cancel the subscription at Braintree but not updating the column "ends_at" in subscriptions table.

Can anyone suggests a workaround for this ? Any help would be appreciated.

Upvotes: 0

Views: 691

Answers (1)

Manu
Manu

Reputation: 119

Since the Laravel Braintree Cashier module is internally using Braintree Subscription library. So I thought to use the same directly into my controller.

I used namespace into my controller for subscription to call the Braintree subscription class directly. the below is the code to cancel the subscription by subscription ID.

use Braintree\Subscription;

public function cancelsubscription(User $user, $subscriptionId)
{
    $subcriptionObj = Subscription::find($subscriptionId); 
    if(is_null($subcriptionObj)){
        abort(400, 'Subscription is not found.');
    }

    if ($subcriptionObj->status == 'Canceled')
        abort(400, 'Subscription is not Active.');

    // In below line we are finding the Subscription DB Obj using cashier module here to update the ends_at date column
    $subsDbObj = $user->subscriptions->filter(function($sub) use ($user,$subscriptionId){
        return $sub->braintree_id == $subscriptionId && $sub->user_id == $user->id;})->values(); 

    Subscription::cancel($subscriptionId);

    if(! is_null($subsDbObj[0])){
        //Internally cashier module doing the same to update the subscription table
        $subsDbObj[0]->ends_at = Carbon::now();
        $subsDbObj[0]->save();
    }

    return 'Cancelled';
}

Upvotes: 0

Related Questions