Using PAY.JP API with Rails ~ Card Registration ~ (payjp.js v2)

Overview

This is a memorandum of implementation of the card registration / change / deletion function using the PAY.JP API. This time, we will summarize the procedure from the acquired token to the registration of card information.

If you have any mistakes, we would appreciate it if you could request an edit.

By the way, payjp.js has many articles about v1, but it should be noted that there are many parts that are different from the current v2.

environment

# OS Version
ProductName:	Mac OS X
ProductVersion:	10.15.7
BuildVersion:	19H2

# Ruby Version
ruby:           2.6.5p114
Rails:          6.0.3.3

Prerequisites

We have even acquired token information using the PAY.JP API. See the article Last time.

procedure

Edit view

Add an error message or hidden form in JS.

haml:_card_form.html.haml


.CardForm
card number
  .CardForm__outer{id: "number-form"}
expiration date
  .CardForm__outer{id: "expiry-form"}
security code
  .CardForm__outer{id: "cvc-form"}
  #message    -#I get an error message here
  = form_with model: @card, id: "card_form", local: true do |form|
    #card_token   -#A hidden form will be added here
    = form.submit "Register your card", class:"CardForm__button", id: "create_card"

Edit controller

Use the token to create customer information from the PAY.JP API and store it in the Card table.

card_controller.rb


class CardController < ApplicationController
  require 'payjp'
  
  def new
  end
  
  def create
    Payjp.api_key = ENV['PAYJP_SECRET_KEY']  #Initialize API
    customer = Payjp::Customer.create(card: params['payjp_token'])  #Create customer data from customer ID
    @card = Card.new(
      user_id: current_user.id,          #Link with user ID
      customer_id: customer.id,          #Save customer ID
      card_id: customer.default_card     #Save customer card information
    )
    @card.save
  end
end

Edit JS file

When you press the send card information button, the token will be used to create and send a hidden form containing your customer ID and card ID.

card_form.js


//Execute when DOM loading is completed
document.addEventListener('DOMContentLoaded', () => {
  //Register the public key and get the starting object
  var payjp = Payjp('pk_test_hogehoge')

  //Gets the elements. If you prepare multiple forms on the page, please get multiple
  var elements = payjp.elements()

  // element(Input form unit)To generate
  var numberElement = elements.create('cardNumber', {style: style})
  var expiryElement = elements.create('cardExpiry', {style: style})
  var cvcElement = elements.create('cardCvc', {style: style})
 
 //Place element on DOM
  numberElement.mount('#number-form')
  expiryElement.mount('#expiry-form')
  cvcElement.mount('#cvc-form')

  //Prepare a function to generate a token when the button is pressed
  create_card.addEventListener("click", function(e) {
    e.preventDefault();
    payjp.createToken(numberElement).then(function(r) {
      if (r.error) {  //Registration failure
        document.querySelector('#message').innerText = r.error.message
        regist_card.prop('disabled', false)
      } else {
        $("#card_token").append(  // #card_Add hidden form to token part
          `<input type="hidden" name="payjp_token" value=${r.id}>
          <input type="hidden" name="card_token" value=${r.card.id}>`
        );
        $("#card_form")[0].submit();  //Submit form
      }
    })
  });
});

reference

After all, the official API and guide are the strongest. However, if you are not accustomed to reading it, you can get a feel for it while looking at the actual implementation procedure on Qiita etc.

PAY.JP API Reference https://pay.jp/docs/api/

PAY.JP API User's Guide | PAY.JP https://pay.jp/docs/started
The official blog is also helpful, but be aware that the information is often old and v1 compliant.

Very basic usage of PAY.JP (Ruby edition) --PAY.JP Engineering Blog https://payjp.hatenablog.com/entry/2017/11/21/191916
Other articles that I referred to

Credit card registration function implementation with Payjp.js V2 on Rails Flea market app --Qiita https://qiita.com/ta9301/items/6b736390c49c3f40edb6

[HowTo] From product purchase function implementation using Pay.jp to setting after product purchase https://qiita.com/Tatsu88/items/eb420e372077939a4627

Recommended Posts

Using PAY.JP API with Rails ~ Card Registration ~ (payjp.js v2)
Using PAY.JP API with Rails ~ Implementation Preparation ~ (payjp.js v2)
[Rails] I will write the mechanism and method of using payjp (API) very carefully (Credit card registration)
[Rails] Implement credit card registration / deletion function in PAY.JP
Try using view_component with rails
Japaneseize using i18n with Rails
API creation with Rails + GraphQL
How to set environment variables when using Payjp with Rails
[Rails] Book search (asynchronous communication) with Amazon PA API v5.0
[Rails 6] API development using GraphQL (Query)
Try using the Rails API (zip code)
Rails API server environment construction using docker-compose
Notes on using FCM with Ruby on Rails
[Rails] Book search with Amazon PA API
Using Material Design for Bootstrap with Rails 5.2
Rails API
[Rails] Error resolution when generating tokens with PAYJP
Rails6 [API mode] + MySQL5.7 environment construction with Docker
How to build API with GraphQL and Rails
[Rails] Introducing pay.jp (from view customization to registration)