简体   繁体   中英

Rails Stripe: How do I cancel subscription?

I'm using devise and in devise/edit I had put a "cancel my subscription" button but I'm not 100% how to get it to work.

How do I allow users to unsubscribe from stripe? Here is the error I got, any help is appreciated

在此处输入图片说明

edit.html.erb

<%= button_to "Cancel my Subscription", canceled_path, :data => { :confirm => "Are you sure?" }, :method => :delete, class: "btn btn-default btn-xs" %>

Migration to User Model

class AddExtraDetailsToUser < ActiveRecord::Migration
  def change
      add_column :users, :subscribed, :boolean, :default => false
      add_column :users, :stripeid, :string
  end
end

Routes.rb

Rails.application.routes.draw do

    resources :subscribe

    get '/cancel_plan' => 'subscribes#cancel_plan'

    devise_for :users do
        resources :posts 
        resources :products
    end

    get 'users/:id' => 'users#show', as: :user

end

SubscribesController.rb

class SubscribesController < ApplicationController
    before_action :authenticate_user!


    def new
    end

    def update
        token = params[:stripeToken]
        customer = Stripe::Customer.create(
            :card => token,
            :plan => 2,
            :email => current_user.email               
        )

        current_user.subscribed = true
        current_user.stripeid = customer.id
        current_user.save

        redirect_to user_path, :notice => "Your subscription was setup!"
    end

def cancel_plan
    @user = current_user
    if @user.cancel_user_plan(params[:customer_id])
      @user.update_attributes(customer_id: nil, plan_id: 1)
      flash[:notice] = "Canceled subscription."
      redirect_to root_path
    else
      flash[:error] = "There was an error canceling your subscription. Please notify us."
      redirect_to edit_user_registration_path
    end
  end

end

Your button has the :method => :delete while your routes defines a get for /cancel_plan . Change

get '/cancel_plan' => 'subscribes#cancel_plan'

to

delete '/cancel_plan' => 'subscribes#cancel_plan'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM