In my latest article I showed you how to integrate Stripe on Ruby on Rails. Today I'm writing a quick tutorial about how to get Slack notification every time someone makes a purchase on your site. It's very easy and simple. I chose Slack notification because as for me this platform is the best to share short messages instantly with your collaborators.
For the first part the Slack tutorial is quite explicite, so I suggest you to read it and do what they say. Firstly you need to create a Slack app, then activate Incoming Webhooks and choose a channel to post your notifications. After doing the Slack tutorial, navigate to the page of your app => Features => Incoming Webhooks and you should see something like this:
Now, go to your Ruby on Rails application and in the terminal open the nano editor to add the Webhook URL in encrypted rails credentials:
$ EDITOR=nano rails credentials:edit
In the editor, add:
slack:
token: 'https://hooks.slack.com/services/your/webhook/url'
Use Ctrl+X to exit editor.
Now in our Gemfile add a new gem:
gem 'slack-notifier'
Then, run the command 'bundle install' in the terminal to install it. Now, in config/initializers create slack_notifier.rb:
module SlackNotifier
CLIENT = Slack::Notifier.new Rails.application.credentials.slack[:token]
end
Finally, the last step is to send the notification. I want that every time someone pays I get a notification on slack. So we need to add this message in the action that subscribes the user to a plan. If you followed my previous tutorial it will be in the action subscribe inย the view views/controllers/billing_controller.rb:
def subscribe
#code which you can see in my previous tutorial
subscription.save
SlackNotifier::CLIENT.ping "๐ธ Boom! New purchase for #{subscription.items.data[0].plan.amount / 100}โฌ from #{current_user.email}! ๐ธ"
end
Now I also want to have a notification when a user registers. In order to do it we go to app/models/user.rb:
after_create :notify_slack
def notify_slack
SlackNotifier::CLIENT.ping "๐ New user: #{email} ๐"
end
Now we are going to test if everything works well. So we are going on our application, create a new user and subscribe him to one of the plans. You should get 2 notifications which look something like this:
That's it! I hope you will see this notifications very often!
Top comments (2)
I reviewed the code of this gem and it's a bit old. Last main update was 3 years ago. What do you think ?
possibly you would like to use slack-ruby-client gem instead: github.com/slack-ruby/slack-ruby-c...