[Java] Rails Payjp.js V2 credit card registration function implementation flea app

6 minute read

Overview

I used payjp.js and there was no article of customizable v2 implementation. I think I shared. There were many implementation articles in v1, but…

###payjp.js v2 provided by β Regarding payjp.js, which provides the tokenization function for card information, we have recently provided β for payjp.js >v2 that complies with the latest PCI-DSS.

What is ###payjp.js v2 payjp.js v2 is a card information input form >generation library that is compliant with the latest PCI-DSS in addition to the conventional tokenization function for card information.

See References and Guides for features and details. We also have multiple demos available.

Request for migration

With regard to the current payjp.js v1, we will deprecate new use of v2 at the same time as this release of v2 (scheduled for the beginning of April).

Members who are already using v1 are sorry to trouble you, but please migrate to payjp.js v2.

For the migration procedure from v1, we will publish an article on this blog again. Please note that we will inform you separately> of the detailed transition schedule.

Thank you for your continued support of PAY.JP. Reference: PAY.JP Blog

Since it is said that this will be recommended from now on, so even a little I would like to write it down because I was able to implement it in the hope of helping everyone. PAY.JP API Usage Guide | PAY.JP I think that it is quite easy to understand if you implement it after seeing.

↑ Since I am a fledgling engineer, I will correct any mistakes Please let us know what you think: point_up:

version information

  • ruby 2.6.5
  • Rails 6.0.3.2

table of contents

  1. Create a Payjp account
  2. Check API
  3. Install Payjp and dotenv Gem
  4. Make payjp.js readable
  5. Create a table to save
  6. Create controller
  7. Create card registration screen 8.Create a javascript file
  8. Create a route
  9. Register card

1. Create a Payjp account

Create an account on the Payjp site.

2. Check API

After logging in, check using the API on the dashboard. Since this time we are implementing in test mode, we will use test private key and test public key. b36.png

3. Install Payjp and dotenv Gem

install payjp gem

Gemfile


gem'payjp'
gem'dotenv'

Install in Gemfile.

terminal


$ bundle install

Create .env with touch command

terminal


$ cd created app directory
$ touch .env

If you can create the API of .env description If you write 'pk_test_000000000000000000000000' here, it may not work in the production environment,

PAYJP_PRIVATE_KEY=pk_test_000000000000000000000000
PAYJP_SECRET_KEY=sk_test_000000000000000000000000

If you’re using Git, write the following to avoid pushing to remote repositories!

.gitnore


.env

4. Make payjp.js readable

★ Described in Haml, here is how to introduce haml↓ Introducing haml with Rails! | Qiita

Add %script{src: "https://js.pay.jp/", type: "text/javascript"} as follows.

ruby:app/views/layouts/application.html.haml


%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title hogehoge
    %script{src: "https://js.pay.jp/v2/pay.js"} #Enter this script
    = csp_meta_tag
    = csrf_meta_tag
    = stylesheet_link_tag'application', media:'all','data-turbolinks-track':'reload'
    = javascript_include_tag'application','data-turbolinks-track':'reload'
  %body
    = yield

5. Create a table to save

Create a database table to store payjp data with the following command

terminal


$ rails g model Card user_id:integer customer_id:string card_id:string

When you command, a migration file is created in db, so check the contents

class CreateCards <ActiveRecord::Migration[6.0]
  def change
    create_table :cards do |t|
      t.integer :user_id, null: false
      t.string :customer_id, null: false
      t.string :card_id, null: false
      t.timestamps
    end
  end
end

Migrate.

terminal


$ rails db:migrate

It is prohibited to save the card information itself in the database, so Information can be obtained by calling the information stored in payjp with the customer ID or card ID.

Revised Installment Sales Law

Request for card information non-passing support

6. Create controller

Create a controller with the following command

terminal


$ rails g controller card

pp/controllers/card_controller.rb


class CardsController <ApplicationController

  require'payjp' # Now you can use the pajp methods

  def new
    card = Card.where(user_id: current_user.id)
    redirect_to action: "show" if card.exists?
  end

  def pay #payjp and Card database creation
    Payjp.api_key = ENV["PAYJP_SECRET_KEY"]
    if params['payjp_token'].blank?
      redirect_to action: "new"
    else
      customer = Payjp::Customer.create(
      description:'Registration test', # no need
      email: current_user.email, # OK without
      card: params['payjp_token'],
      metadata: {user_id: current_user.id}
      ) # Just in case you didn't put user_id in metadata
      @card = Card.new( # Create card table data
        user_id: current_user.id, # There is current_user.id here, so let's sign in in advance
        customer_id: customer.id, # customer is defined above
        card_id: customer.default_card # .default_card is used to pull the card information associated with the customer definition. If this is null, the above customer's card: params['payjp_token'] cannot be read in many cases.
      )
      if @card.save
        redirect_to action: "show"
      else
        redirect_to action: "pay"
      end
    end
  end



  def delete #Payjp and Card Delete database
    card = Card.find_by(user_id: current_user.id)
    if card.blank?
    else
      Payjp.api_key = ENV["PAYJP_SECRET_KEY"]
      customer = Payjp::Customer.retrieve(card.customer_id)
      customer.delete
      card.delete
    end
      redirect_to action: "new"
  end

  def show #Card data Payjp retrieves informationcard = Card.find_by(user_id: current_user.id)
    if card.blank?
      redirect_to action: "new"
    else
      Payjp.api_key = ENV["PAYJP_SECRET_KEY"]
      customer = Payjp::Customer.retrieve(card.customer_id)
      @default_card_information = customer.cards.retrieve(card.card_id)
    end
  end

end

7. Create card registration screen

**From here on, v2 is slightly different from v1! !! !! !! **

haml:new_credit.html.haml


      .form-group
        %p#number-form.payjs-outer
        %p#expiry-form.payjs-outer
        %p#cvc-form.payjs-outer
      .form-group
        = form_with url: pay_cards_path, method: :post,id: "card_form" do |f|
      #card_token
          = f.submit "register", class:"btn", id: "info_submit"

With this alone, if you write pay.js in javascript, the following elements will appear in asynchronous communication! Screenshot 2020-08-26 11.25.16.png

8. Create a javascript file

Rails can use jQuery (Before writing js payjp.js v2 Guideandpayjp.jsv2ReferenceIt’seasiertounderstandafterreadingandthenenteringthefollowing:point_up:)

app/assets/javascripts/pay.js


$(window).bind("load", function(){
  if (document.URL.match(/cards/)){
  // Only fire when ↑URl has /crads/

    var payjp = Payjp('pk_test_*************0')
     //↑ Register the public key and get the starting object

    var elements = payjp.elements();
Get //↑elements.

    var numberElement = elements.create('cardNumber');
    var expiryElement = elements.create('cardExpiry');
    var cvcElement = elements.create('cardCvc');
//Creates ↑element

    numberElement.mount('#number-form');
    expiryElement.mount('#expiry-form');
    cvcElement.mount('#cvc-form');
//Arrange ↑element on the DOM

    var submit_btn = $("#info_submit");
    submit_btn.click(function (e) {
      e.preventDefault();
      payjp.createToken(numberElement).then(function (response) {
// ↑↑ Create a token here // Pass an arbitrary Element to the argument of createToken

        if (response.error) {//when communication fails
          alert(response.error.message)
          regist_card.prop('disabled', false)
        } else {
          alert("Registration is complete");
          $("#card_token").append(
            `<input type="hidden" name="payjp_token" value=${response.id}>
            <input type="hidden" name="card_token" value=${response.card.id}>`
          );
          $('#card_form')[0].submit();
        //↑↑ Here, type='hidden' is set and the token is added to the submit.

          $("#card_number").removeAttr("name");
          $("#cvc-from").removeAttr("name");
          $("#exp_month").removeAttr("name");
        $("#exp_year").removeAttr("name");
 ↑↑ The description is deleted here with removeAttr
        };
      });
    });
  }
});

8. Create confirmation and deletion screen

After registration, the card#show action will work with redirect. Prepare a confirmation and deletion screen.

haml:app/cards/show.html.haml



.creditShow
  %label Registered credit card information
  %br
  = "**** **** **** "+ @default_card_information.last4
  %br
  -exp_month = @default_card_information.exp_month.to_s
  -exp_year = @default_card_information.exp_year.to_s.slice(2,3)
  = exp_month + "/" + exp_year
  = form_tag(delete_cards_path, method: :post, id:'charge-form', name: "inputForm") do
    %input{ type: "hidden", name: "card_id", value: ""}
    %button delete

![Screenshot 2020-08-26 11.56.28.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/664372/4e2657e2-0306-24b2-494c-(ee4252de2622.png)

9. Create a route

It depends on the specifications of the application, but we will share the description once it has been implemented, so please arrange it.

config/routes.rb


resources :cards, only: [:new, :show,] do
    collection do
      post'show', to:'cards#show'
      post'pay', to:'cards#pay'
      post'delete', to:'cards#delete'
    end
  end

Now that the description of route and MVC is complete, I think you can register it.

10. Register Card

To register in test mode, Payjp test card See here

  • Card number: 4242424242424242
  • Expiration date: 12/20
  • CVC: 123
  • Card name: YUI ARAGAKI

Then try registering at http://localhost:3000/cards/new/: relaxed: If you can register, click here →Dashboard customers Will be reflected in!

Reference article

PAY.JP API Implement credit card registration and deletion function with Payjp (Rails)|Qiita How to use jQuery with Rails|Qiita Implement the purchase function using Payjp with Rails|Qiita [Rails] I briefly summarized the implementation procedure of the payment function using PAYJP