LoginSignup
57
91

More than 3 years have passed since last update.

Pay.jpをRailsで!【登録・削除・購入】

Posted at

はじめに

今回Pay.jpでクレジットカードの商品購入機能を実装したので
そのまとめを行います。
基本的には 「pay.jp rails」で検索をかけると少ないですが記事が出てくるので
そちらを読み込めば実装はできます。

ですので
pay.jpのgemの導入方法などはそちらを参考にしていただければと思います。

僕が調べて参考にした記事を貼っておくので以下の記事を見ればできるかなと思います。
・Payjpでクレジットカード登録と削除機能を実装する(Rails)
https://qiita.com/takachan_coding/items/f7e70794b9ca03b559dd
・Payjpに登録したクレジットカードで商品購入を実装する(Rails)
https://qiita.com/takachan_coding/items/d21c0d2621368c9b0d9b
・Rails で Payjp を使って決済システムを導入する
https://qiita.com/hirotakasasaki/items/794c920016ac7c33da74
・【Payjp】payjp.jsを使ってトークンを取得する方法
https://qiita.com/kubbo0211/items/0030c00cea8461b1a498

ではクレジットカード登録から削除、購入まで通して書いていきますね。

登録

登録する際にはjsとrailsを使い色々するので処理の流れを中心に解説できればと思います。

登録のviewはこちら

スクリーンショット 2019-06-19 21.28.44.png

まずはjs

payjp.js
var form = $("#card__form");
  Payjp.setPublicKey("pk_test_f7605539c63c593a5b5ebfed");
//まずはテスト鍵をセットする↑
  $("#submit_btn").on("click",function(e){
    e.preventDefault();
  //↑ここでrailsの処理を止めることでjsの処理を行う
    var card = {
      number: $("#card_number").val(),
      cvc: $("#card_cvc").val(),
      exp_month: $("#card_month").val(),
      exp_year: $("#card_year").val()
    };
   //↑Pay.jpに登録するデータを準備する
    Payjp.createToken(card,function(status,response){
   //↑先ほどのcard情報がトークンという暗号化したものとして返ってくる
      form.find("input[type=submit]").prop("disabled", true);
      if(status == 200){//←うまくいった場合200になるので
        $("#card_number").removeAttr("name");
        $("#card_cvc").removeAttr("name");
        $("#card_month").removeAttr("name");
        $("#card_year").removeAttr("name");
       //↑このremoveAttr("name")はデータを保持しないように消している
        var payjphtml = `<input type="hidden" name="payjpToken" value=${response.id}>`
        form.append(payjphtml);
        //↑これはdbにトークンを保存するのでjsで作ったトークンをセットしてる
        document.inputForm.submit();
       //↑そしてここでsubmit!!これでrailsのアクションにいく!もちろん上でトークンをセットしているのでparamsの中には{payjpToken="トークン"}という情報が入っている
      }else{
        alert("カード情報が正しくありません。");
      }
    });
  });


jsはトークンを作成するためのものなので
本番はここからです!

Railsいきます

cards_controller.rb
def pay #クレジットカード登録
    Payjp.api_key = "sk_test_0e2eb234eabf724bfaa4e676"
    # ここでテスト鍵をセットしてあげる(環境変数にしても良い)
    if params['payjpToken'].blank?
    # paramsの中にjsで作った'payjpTokenが存在するか確かめる
      redirect_to action: "new"
    else
      customer = Payjp::Customer.create(
      card: params['payjpToken'],
      metadata: {user_id: current_user.id}
      )
     # ↑ここでjay.jpに保存
      @card = CreditCard.new(user_id: current_user.id, customer_id: customer.id, card_id: customer.default_card)
     # ここでdbに保存
      if @card.save
        redirect_to action: "show"
        flash[:notice] = 'クレジットカードの登録が完了しました'
      else
        redirect_to action: "pay"
        flash[:alert] = 'クレジットカード登録に失敗しました'
      end
    end
 end

ここまででクレジットカードの登録ができます。

注意

クレジットカード情報を直接DBに保存するのはセキュリティー上よろしくないので
jsで暗号化してdbに保存したほうがいいです。

ちなみにテーブルにはこんな感じでデータが入ります。

スクリーンショット 2019-06-20 20.56.54.png

再度、下記の記事と併用して見ると捗ると思います
【参考記事】
・Payjpでクレジットカード登録と削除機能を実装する(Rails)
https://qiita.com/takachan_coding/items/f7e70794b9ca03b559dd
・Payjpに登録したクレジットカードで商品購入を実装する(Rails)
https://qiita.com/takachan_coding/items/d21c0d2621368c9b0d9b
・Rails で Payjp を使って決済システムを導入する
https://qiita.com/hirotakasasaki/items/794c920016ac7c33da74
・【Payjp】payjp.jsを使ってトークンを取得する方法
https://qiita.com/kubbo0211/items/0030c00cea8461b1a498

クレジットカードの詳細

この辺はそんな難しくないのでさらっと流します。

view画面のコード

show.html.haml
.user-card__content
   %h2 クレジットカード情報
   .customer-card__content
     %figure.form_space
     = image_tag"credit_cards/visa.svg",size: "50x30"
      .customer-card__content--number.form_space
        %h3
          = "**** **** **** " + @customer_card.last4
       .customer-card__content--expired.form_space
         - exp_month = @customer_card.exp_month.to_s
         - exp_year = @customer_card.exp_year.to_s.slice(2,3)
         %h3
           = exp_month + " / " + exp_year
        = link_to delete_cards_path ,method: :delete,class:"customer-card__content--btn" do
          %button{type: "submit",class: "btn-red"}
            削除する

Railsコード

cards_controller.rb
def show
    card = current_user.credit_card
    if card.blank?
      redirect_to action: "new" 
    else
      Payjp.api_key = "sk_test_0e2eb234eabf724bfaa4e676"
      customer = Payjp::Customer.retrieve(card.customer_id)
      @customer_card = customer.cards.retrieve(card.card_id)
    end
end

クレジットカードの購入

cards_controller.rb
def buy #クレジット購入

    if card.blank?
      redirect_to action: "new"
      flash[:alert] = '購入にはクレジットカード登録が必要です'
    else
      @product = Product.find(params[:product_id])
     # 購入した際の情報を元に引っ張ってくる
      card = current_user.credit_card
     # テーブル紐付けてるのでログインユーザーのクレジットカードを引っ張ってくる
      Payjp.api_key = "sk_test_0e2eb234eabf724bfaa4e676"
     # キーをセットする(環境変数においても良い)
      Payjp::Charge.create(
      amount: @product.price, #支払金額
      customer: card.customer_id, #顧客ID
      currency: 'jpy', #日本円
      )
     # ↑商品の金額をamountへ、cardの顧客idをcustomerへ、currencyをjpyへ入れる
      if @product.update(status: 1, buyer_id: current_user.id)
        flash[:notice] = '購入しました。'
        redirect_to controller: "products", action: 'show'
      else
        flash[:alert] = '購入に失敗しました。'
        redirect_to controller: "products", action: 'show'
      end
     #↑この辺はこちら側のテーブル設計どうりに色々しています
    end
  end

購入が完了すると・・・

スクリーンショット 2019-06-20 20.41.55.png
こんな感じで金額が追加されます。

ここまでで購入機能が完成です。

再度、下記の記事と併用して見ると捗ると思います
【参考記事】
・Payjpでクレジットカード登録と削除機能を実装する(Rails)
https://qiita.com/takachan_coding/items/f7e70794b9ca03b559dd
・Payjpに登録したクレジットカードで商品購入を実装する(Rails)
https://qiita.com/takachan_coding/items/d21c0d2621368c9b0d9b
・Rails で Payjp を使って決済システムを導入する
https://qiita.com/hirotakasasaki/items/794c920016ac7c33da74
・【Payjp】payjp.jsを使ってトークンを取得する方法
https://qiita.com/kubbo0211/items/0030c00cea8461b1a498

削除機能

これも簡単です

cards_controller.rb
def delete
    card = current_user.credit_card
    if card.blank?
      redirect_to action: "new"
    else
      Payjp.api_key = 'sk_test_0e2eb234eabf724bfaa4e676'
      customer = Payjp::Customer.retrieve(card.customer_id)
      customer.delete
     #ここでpay.jpの方を消している
      card.delete
     #ここでテーブルにあるcardデータを消している
    end  
end

以上でクレジットカードの削除は終わりです。

最後にできてしまえば簡単だなと感じますが
導入時は何がどうなってるのかわからなくて
一連の処理を乗せてくれる記事がなくて苦労したので
この記事が参考になれば幸いです。。

では最後まで読んでいただきありがとうございました!!!

57
91
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
91