Rails 上的 Stripe Webhook [英] Stripe Webhook on Rails

查看:43
本文介绍了Rails 上的 Stripe Webhook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有另一个问题与这个问题类似,但我认为没有很好地提出/回答.

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

基本上,我有一个可运行的 rails 应用程序,用户可以在其中注册我的订阅、输入信用卡信息等.这一切正常.但是我需要处理在此定期订阅期间用户卡在某个时间点被拒绝的情况.

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.

他们发送的事件类型在这里:https://stripe.com/docs/api?lang=ruby#event_types.

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

我无法访问我的应用中的 charge.failed 对象.

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

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

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

推荐答案

您需要创建一个控制器来基本上接受和处理请求.它非常简单,虽然最初并没有那么直接.这是我的 hooks_controller.rb 的示例:

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

def 接收器是您必须将 webhooks 指向条带接口的视图.视图接收 json,如果付款失败或成功,我将使用它来更新用户的个人资料.

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.

这篇关于Rails 上的 Stripe Webhook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆