Stripe Webhook on Rails

倾然丶 夕夏残阳落幕 提交于 2019-11-28 16:05:31

问题


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.


回答1:


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.




回答2:


It is much easier now using the stripe_event gem:

https://github.com/integrallis/stripe_event




回答3:


This is a less than ideal testing situation…

Stripe needs a way to "force" webhooks for testing purposes. Currently, the shortest subscription you can make is for 1 week (in test mode); it would be much more helpful if you could set it for 1 minute, 1 hour, or even simply cause the callback to occur in realtime, so you can test your API response system.

Local tests are great, but nothing replaces the real-world, live, over the internet, webhooks/callbacks. Having to wait a week (!) seriously slows down projects.



来源:https://stackoverflow.com/questions/9627580/stripe-webhook-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!