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


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.


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

# Ruby Version
ruby:           2.6.5p114


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


Edit view

Add an error message or hidden form in JS.


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.


class CardController < ApplicationController
  require 'payjp'
  def new
  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 =
      user_id:,          #Link with user ID
      customer_id:,          #Save customer ID
      card_id: customer.default_card     #Save customer card information

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.


//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

  //Prepare a function to generate a token when the button is pressed
  create_card.addEventListener("click", function(e) {
    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=${}>
          <input type="hidden" name="card_token" value=${}>`
        $("#card_form")[0].submit();  //Submit form


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

PAY.JP API User's Guide | PAY.JP
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
Other articles that I referred to

Credit card registration function implementation with Payjp.js V2 on Rails Flea market app --Qiita

[HowTo] From product purchase function implementation using to setting after product purchase

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 (from view customization to registration)