Ask A Question

Notifications

You’re not receiving notifications from this thread.

Braintree cancel subscription

Darren Booker asked in Rails

Hi,

So, I implemented the braintree payment processing and everything works perfect. Now the only issue I am having is if I user cancels their subscription through my web application everything works fine, but if I cancel the subscription or braintree cancels their subscription through my braintree dashboard it does not update my users cancellation through my web application. I figure this is a problem because if a user does not pay their monthly bill be default braintree cancels their subscription due to failure of payment and users will continue to use my service for free.

class SubscriptionsController < ApplicationController
    before_action :authenticate_user!, except: [:new]
    before_action :redirect_to_signup, only: [:new]

  def show

  end

  def new

  end

  def create
    if current_user.braintree_id?
      customer = Braintree::Customer.find(current_user.braintree_id)
    else
      result = Braintree::Customer.create(
        email: current_user.email,
        payment_method_nonce: params[:payment_method_nonce]
      )
      customer = result.customer
      current_user.update(braintree_id: customer.id)
    end

    result = Braintree::Subscription.create(
      payment_method_token: customer.payment_methods.find{ |pm| pm.default? }.token,
      plan_id: '25pm'
    )
    current_user.update(braintree_subscription_id: result.subscription.id)

    redirect_to root_path, notice: "You have been subscribed"
  end

  def destroy
    customer = Braintree::Customer.find(current_user.braintree_id)
    Braintree::Subscription.cancel(current_user.braintree_subscription_id)
    current_user.update(braintree_subscription_id: nil)

    redirect_to root_path, notice: "Your Subscription has been canceled"
  end

  private

  def redirect_to_signup
    if !user_signed_in?
        session["user_return_to"] = new_subscription_path
        redirect_to new_user_registration_path
    end
  end

end
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 76,990+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.