translator

Pay.jp定期課金更新及びcheckout Token使用

controller

class WebhockController< ApplicationController
  protect_from_forgery except: :create
  def create
    Payjp.api_key = 'あなたのキー'
    event = Payjp::Event.retrieve(params[:id])

    case event.type
      when 'subscription.updated'
        subscription = event.data
        user = User.find_by(subscription_id: subscription.id)
        user.update_subscription(subscription)
      when 'subscription.created'
        subscription = event.data
        user = User.find_by(subscription_id: subscription.id)
        user.test
      when 'subscription.deleted'
        subscription = event.data
        user = User.find_by(subscription_id: subscription.id)
        user.test
    end

    head :ok
  end
end

controller 解説

eventをwebhockで受け取って、subscription.updatedの時にsubscription_idを元にユーザーを割り出し、subscriptionupdate簡単に実装できます

modelで課金が有効かチェック&課金をupdate

def update_subscription(subscription)
    update(expires_at: Time.zone.at(subscription.current_period_end))
  end

expries_atに期限をいれています.

課金が有効かチェック

def member?
    expires_at && (expires_at > Time.now)
end

現在の時刻と比較

pay.jp checkout

預かりたくないクレジットの情報をpay.jpに丸投げしてくれるJavaScriptベースのデザインされた入力フォームを使います。

def create
    if current_user.customer_id==nil
      token=params['payjp-token']
      current_user.making_customer(current_user,token)
    end
    current_user.subscription(current_user)
    redirect_to :back
  end

超クール!

  def making_customer(current_user,token)
    Payjp.api_key = ''
    customer=Payjp::Customer.create(
        email:current_user.email,#任意
        description: 'test',#任意
        card:token #ないと定期課金実装できない
    )
    update(customer_id:customer.id)
  end

終わり

pay.jpドキュメントわかりやすいけどparams['payjp-token']なんてのは、乗っているのがドキュメントじゃないとこで探すのに苦労した。 情報がないと導入に躊躇するけど実際は驚くほど簡単 みなさんぜひ使いましょう!!

コメント

このブログの人気の投稿