Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripe Webhook on Rails

Tags:

I know there is another question that exists similar to this one but I don't think it was asked/answered very well.

Basically I have a working rails app where users can sign up for my subscription, enter credit card information, etc. That's all working. But I need to handle the situation where a user's card is declined at some point during this recurring subscription.

The types of events they send are here: https://stripe.com/docs/api?lang=ruby#event_types.

I'm having trouble accessing the charge.failed object in my app.

The docs on webhooks are also here: https://stripe.com/docs/webhooks, and any help would be much appreciated.

like image 485
Zach Avatar asked Mar 09 '12 01:03

Zach


2 Answers

You need to create a controller to basically accept and handle the requests. It's pretty straight forward, although not as straight forward to wrap your mind around initially. Here is an example of my hooks_controller.rb:

class HooksController < ApplicationController
  require 'json'

  Stripe.api_key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

  def receiver

    data_json = JSON.parse request.body.read

    p data_json['data']['object']['customer']

    if data_json[:type] == "invoice.payment_succeeded"
      make_active(data_event)
    end

    if data_json[:type] == "invoice.payment_failed"
      make_inactive(data_event)
    end
  end

  def make_active(data_event)
    @profile = Profile.find(User.find_by_stripe_customer_token(data['data']['object']['customer']).profile)
    if @profile.payment_received == false
      @profile.payment_received = true
      @profile.save!
    end
  end

  def make_inactive(data_event)
    @profile = Profile.find(User.find_by_stripe_customer_token(data['data']['object']['customer']).profile)
    if @profile.payment_received == true
      @profile.payment_received = false
      @profile.save!
    end
  end
end

The def receiver is the view that you have to point the webhooks to on the stripe interface. The view receives the json, and I'm using it to update the user's profile in the event that a payment fails or succeeds.

like image 101
rubyplusplus Avatar answered Sep 22 '22 18:09

rubyplusplus


It is much easier now using the stripe_event gem:

https://github.com/integrallis/stripe_event

like image 44
Richard Ortega Avatar answered Sep 19 '22 18:09

Richard Ortega