Skip to content

Commit

Permalink
feat: Controllers Stripe_Webhook Account_Manager
Browse files Browse the repository at this point in the history
  • Loading branch information
OmarMWarraich committed Jul 23, 2024
1 parent 5e54a63 commit 3e1e0be
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 4 deletions.
14 changes: 14 additions & 0 deletions app/controllers/account_manager_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class AccountManagerController < ApplicationController
before_action :authenticate_user!

def index; end

def create_portal_session
session = Stripe::BillingPortal::Session.create({
customer: current_user.stripe_customer_ref,
return_url: account_manager_url
})

redirect_to session.url, status: 303, allow_other_host: true
end
end
51 changes: 51 additions & 0 deletions app/controllers/stripe_webhooks_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class StripeWebhooksController < ApplicationController
skip_before_action :verify_authenticity_token, only: :webhook

def webhook
payload = request.body.read
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil

begin
event = Stripe::Webhook.construct_event(
payload, sig_header, ENV.fetch('STRIPE_WEBHOOK_SECRET')
)
rescue JSON::ParserError => e
# Invalid payload
Rails.logger.error "⚠️ Webhook JSON parse error: #{e.message}"
rescue Stripe::SignatureVerificationError => e
# Invalid signature
Rails.logger.error "⚠️ Webhook signature verification error: #{e.message}"
end

# Handle the event
case event.type
when 'checkout.session.completed'
session = event.data.object

if session.client_reference_id.present?
subscription = Subscription.find(session.client_reference_id)
subscription.user.update(stripe_customer_ref: session.customer)
subscription.update!(stripe_customer_ref: session.customer, stripe_subscription_ref: session.subscription)
end
when 'customer.subscription.created'
stripe_subscription = event.data.object

subscription = Subscription.find_by(stripe_subscription_ref: stripe_subscription.id)
subscription.update!(status: stripe_subscription.status,
paid_until: Time.at(stripe_subscription.current_period_end))
when 'customer.subscription.deleted'
stripe_subscription = event.data.object
subscription = Subscription.find_by(stripe_subscription_ref: stripe_subscription.id)
subscription.update!(status: 'canceled', paid_until: nil)
when 'customer.subscription.updated'
stripe_subscription = event.data.object
subscription = Subscription.find_by(stripe_subscription_ref: stripe_subscription.id)
subscription.update!(status: stripe_subscription.status,
paid_until: Time.at(stripe_subscription.current_period_end))
# ... handle other event types
else
puts "Unhandled event type: #{event.type}"
end
end
end
2 changes: 1 addition & 1 deletion app/controllers/subscriptions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def create_checkout_session
quantity: 1,
price: prices.data[0].id
}],
success_url: "http://localhost:3000" + '/success.html?session_id={CHECKOUT_SESSION_ID}',
success_url: "https://#{ENV.fetch("DOMAIN")}/success.html?session_id={CHECKOUT_SESSION_ID}",
cancel_url: root_url,
})

Expand Down
2 changes: 2 additions & 0 deletions app/helpers/account_manager_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
module AccountManagerHelper
end
2 changes: 2 additions & 0 deletions app/helpers/stripe_webhooks_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
module StripeWebhooksHelper
end
2 changes: 2 additions & 0 deletions app/models/subscription.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@
#
class Subscription < ApplicationRecord
belongs_to :user

scope :active, -> { where(status: "active") }
end
14 changes: 14 additions & 0 deletions app/views/account_manager/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<div class="vh-100 d-flex justify-content-center align-items-center">
<div class='text-center'>
<div class='card mb-2'>
<div class='card-body'>
<h5 class='card-title'>Your Subscription</h5>
<p class='card-text'>You are currently subscribed and your account will renew on:</p>
<p class='card-text'><%= current_user.subscriptions.active.first.paid_until.strftime('%B %d, %Y') %></p>
</div>
</div>
<section>
<%= button_to 'Manage Account', create_portal_session_path, data: {turbo: false}, class: 'btn btn-primary' %>
</section>
</div>
</div>
2 changes: 1 addition & 1 deletion app/views/layouts/_navbar.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
<ul class="navbar-nav mb-2 mb-lg-0">
<li class="nav-item dropdown">
<% if user_signed_in? %>
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<a class="nav-link dropdown-toggle" href="/account" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<%= current_user.email.gsub(/@.*/, '') %>
</a>
<ul class="dropdown-menu dropdown-menu-end">
Expand Down
2 changes: 2 additions & 0 deletions app/views/stripe_webhooks/webhook.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1>StripeWebhooks#webhook</h1>
<p>Find me in app/views/stripe_webhooks/webhook.html.erb</p>
9 changes: 7 additions & 2 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
Rails.application.routes.draw do
get "account" => "account_manager#index", as: :account_manager
post '/create_portal_session' => 'account_manager#create_portal_session', as: :create_portal_session

post "stripe_webhook" => "stripe_webhooks#webhook"

get "pricing" => "subscriptions#index"
post "/create_checkout_session" => "subscriptions#create_checkout_session", as: :create_checkout_session
post "create_checkout_session" => "subscriptions#create_checkout_session", as: :create_checkout_session
get "success" => "subscriptions#success"


mount Sidekiq::Web => "/sidekiq"
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

resource :session # where login and logout routes are defined
Expand Down
8 changes: 8 additions & 0 deletions test/controllers/account_manager_controller_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
require "test_helper"

class AccountManagerControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get account_manager_index_url
assert_response :success
end
end
8 changes: 8 additions & 0 deletions test/controllers/stripe_webhooks_controller_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
require "test_helper"

class StripeWebhooksControllerTest < ActionDispatch::IntegrationTest
test "should get webhook" do
get stripe_webhooks_webhook_url
assert_response :success
end
end

0 comments on commit 3e1e0be

Please sign in to comment.