Using PAY.JP API with Rails ~ Implementation Preparation ~ (payjp.js v2)

Overview

This is a memorandum of implementation of the card registration / change / deletion function using the PAY.JP API. This time, as a preparation for implementation, we will summarize the procedure up to token acquisition.

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

procedure

Register with PAY.JP

Select ʻAPIon the screen after registration / login. <img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/672627/3864b610-2de8-fb05-8ece-2da908454971.png " width=75%> Atest key and a production keyare available, but thetest key` will be used.

Install the required gems

Gemfile


gem 'payjp'
gem 'dotenv-rails'

dotenv-rails is a gem that manages environment variables, so it's not required, but let's take the form of not writing the private key directly in the code. Don't forget to write bundle install as well.

Define environment variables

Create a .env file in the application directory and write as follows.

.env


PAYJP_SECRET_KEY = 'Test private key confirmed earlier'
PAYJP_PUBLIC_KEY = 'The test public key confirmed earlier'

By doing this, you can make the key variable, for example, you can express the test key by writing ʻENV [PAYJP_SECRET_KEY] . You can check the operation with rails console`.

terminal


[1] pry(main)> require 'dotenv-rails'
=> true
[2] pry(main)> ENV['PAYJP_SECRET_KEY']
=> "sk_test_hogehoge"

By the way, if the file name is .env.development, the development environment, and if it is .env.production, the code can be used as it is, and variables can be used for each environment. See the official github (https://github.com/bkeepers/dotenv) for more details.

* Do not push .env files to github. Let's set it to .gitignore. </ font>

Create a model

Create a Card model.

terminal


$ rails g model card

What you need to save as the data received from PAY.JP is the column to save the customer ID and card ID. With these two, you can bring in most of the data. The code below also links with the ʻUser model`.

migrationfile


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

Don't forget to migrate.

terminal


$ rails db:migrate

Write JS file

This is almost a complete copy of the official guide (https://pay.jp/docs/payjs-guidance). Officially I use onclick to fire the token generation, but in my case it didn't work so I used AddEventListener. For the time being, display the token and check the operation.

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_token.addEventListener("click", function() {
    payjp.createToken(numberElement).then(function(r) {
      document.querySelector('#token').innerText = r.error ? r.error.message : r.id
    })
  });
})

Write a view file

For the time being, I will make a minimum description to display the form. Let's rewrite it later as you like.

haml:_card_form.html.haml


:css
  .Payjs__outer {
    border: solid 1px;
  }

-#Actually application.html.It is better to write it in the header part such as haml.
= javascript_include_tag 'https://js.pay.jp/v2/pay.js'

.Payjs
  .Payjs__outer{id: "number-form"}
  .Payjs__outer{id: "expiry-form"}
  .Payjs__outer{id: "cvc-form"}
  %button{id: "create_token"}
Token creation
  %span#token
token:

Operation check

You can create a form like this, so enter your favorite card number from the test card (https://pay.jp/docs/testcard) and check the operation. I was able to confirm the token generation.

So far this time, next time I would like to summarize the implementation of the card registration function.

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 ~ Implementation Preparation ~ (payjp.js v2)
Using PAY.JP API with Rails ~ Card Registration ~ (payjp.js v2)
Credit card registration function implementation with Payjp.js V2 on Rails Flea market app
[Rails] Implementation of multi-layer category function using ancestry "Preparation"
Try using view_component with rails
Japaneseize using i18n with Rails
API creation with Rails + GraphQL
Preparation for developing with Rails
Login function implementation with rails
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)
[Rails] Implementation of coupon function (with automatic deletion function using batch processing)
Using Java with AWS Lambda-Eclipse Preparation
I implemented Rails API with TDD by RSpec. part3-Action implementation with authentication-
# 8 seed implementation to build bulletin board API with authentication authorization in Rails 6
Signature verification implementation (Rails) for detecting tampering with request parameters using JWT
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
# 6 show, create implementation to build bulletin board API with authentication authorization in Rails 6
Rails API
Build a bulletin board API with authentication authorization in Rails 6 # 5 controller, routes implementation
[Rails] Set validation for the search function using Rakuten API (from the implementation of Rakuten API)
# 7 update, destroy implementation to build bulletin board API with authentication authorization in Rails 6
[Rails 6] Implementation of inquiry function using Action Mailer
Interact with LINE Message API using Lambda (Java)
[Rails] Error resolution when generating tokens with PAYJP
[Rails] Implementation of image enlargement function using lightbox2
Rails6 [API mode] + MySQL5.7 environment construction with Docker
[Rails] Schedule management using Full Calendar Yesterday's implementation
[Nuxt / Rails] POST implementation using axios and devise_token_auth
[Rails] Implementation of batch processing using whenever (gem)
Translator using Microsoft Translator Text API on Android ~ Implementation ~
How to build API with GraphQL and Rails
[Rails] Implementation of PV number ranking using impressionist
[Rails] Implementation of image slide show using Bootstrap 3