Stripe Webhook on Rails

Zac*_*ach 19 ruby-on-rails webhooks stripe-payments

我知道还有另一个类似于这个问题的问题,但我不认为它得到了很好的回答.

基本上我有一个工作轨道应用程序,用户可以注册我的订阅,输入信用卡信息等.这一切都工作.但我需要处理在此定期订阅期间某个时候用户卡被拒绝的情况.

他们发送的事件类型如下:https://stripe.com/docs/api?lang = ruby​​ #event_types.

我在访问应用中的charge.failed对象时遇到问题.

关于webhooks的文档也在这里:https://stripe.com/docs/webhooks ,任何帮助将不胜感激.

小智 39

您需要创建一个控制器来基本上接受和处理请求.这是非常直接的,虽然不是最初直接包装你的想法.这是我的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
Run Code Online (Sandbox Code Playgroud)

def接收器是您必须将webhook指向条带接口的视图.该视图接收json,我正在使用它来更新用户的配置文件,如果付款失败或成功.

  • 为了最好的[安全]练习,使用事件id(`data_json ['id']`)来检索Stripe :: Event对象,然后从中获取数据,因为它肯定是合法的. - 如[Stripe的webhooks参考页面](https://stripe.com/docs/webhooks)所述. (10认同)
  • 很有帮助!仅供参考,JSON解析的结果不是无关紧要的散列,因此您可能希望改为执行event_json = JSON :: parse(request.body.read).with_indifferent_access. (2认同)

Ric*_*ega 10

现在使用stripe_eventgem 更容易:

https://github.com/integrallis/stripe_event