0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

15分でPAY.JP入門

Posted at

みなさんは、オンライン決済サービスPAY.JPを使ったことがあるでしょうか。
自分は使用したことがなく、15分で簡単なフォームから売上のリクエストを送るチュートリアルを行いたい。

まず、PAY.JPとは?

日本国内市場をターゲットとしたビジネスには非常に適した決済プラットフォームです。

PAY.JPのプラン:https://pay.jp/plan
2024/12月現在では、金額ごとに3つのタイプがあるそうです。

image.png

他類似サービスが3.6%前後なのに対して、PAY.JPは非常に手数料が安いようです。

さて、本題のPAY.JPのテスト環境にリクエストを送ってみましょう。

0.概要

  • 環境
- サーバーサイド:
使用技術: Node.js (Express)
- フロントエンド:
使用技術: HTML + JavaScript
- 環境変数管理:
.envファイルを利用し、PAY.JP開発環境の公開鍵・秘密鍵
  • アプリケーションのディレクトリ構造
payjp-sample-app/
├── public/
│   └── index.html       # 決済フォーム
├── server.js            # バックエンドサーバー
├── .env                 # APIキーなどの環境変数
└── package.json         # Node.js設定ファイル
  • PAY.JPでアカウントを作成する
    https://pay.jp/d/login
    こちらのサイトにて、アカウントを作成してください。
    開発用の公開鍵と秘密鍵を使用する際に必要です。

1.環境構築

さて、環境構築です。

  • プロジェクトディレクトリ作成
mkdir payjp-sample-app
cd payjp-sample-app
  • Node.jsプロジェクトの初期化
npm init -y
  • 必要なパッケージのインストール
npm install express body-parser payjp dotenv
  • 開発用ツールのインストール
npm install nodemon --save-dev

2.実装

  • payjp-sample-app/public/index.html
<!DOCTYPE html>
<html>
<head>
  <title>PAY.JP サンプル決済</title>
  <script src="https://js.pay.jp/"></script>
</head>
<body>
  <h1>商品購入ページ</h1>
  <form id="payment-form">
    <div id="card-element"></div>
    <button type="submit">購入する</button>
  </form>

  <script>
    async function initializePayjp() {
      try {
        const response = await fetch('/public-key');
        const data = await response.json();
        const publicKey = data.publicKey;

        // PAY.JPの初期化
        const payjp = Payjp(publicKey);
        const elements = payjp.elements();
        const card = elements.create('card'); // PAY.JPのCard要素を作成
        card.mount('#card-element'); // カード要素をDOMにマウント

        // フォーム送信時の処理
        document.getElementById('payment-form').addEventListener('submit', async (event) => {
          event.preventDefault();

          const result = await payjp.createToken(card); // トークンを生成

          if (result.error) {
            alert('エラー: ' + result.error.message);
          } else {
            const token = result.id;

            const response = await fetch('/charge', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ token: token, amount: 1000 }),
            });

            const resultData = await response.json();
            if (resultData.success) {
              alert('決済成功');
            } else {
              alert('決済失敗: ' + resultData.error);
            }
          }
        });
      } catch (err) {
        console.error('公開鍵の取得に失敗しました:', err);
      }
    }

    initializePayjp();
  </script>
</body>
</html>
  • payjp-sample-app/server.js
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const payjp = require('payjp')(process.env.PAYJP_SECRET_KEY);

const app = express();
const PORT = 3000;

// Middleware
app.use(bodyParser.json());
app.use(express.static('public'));

// Public Key Endpoint
app.get('/public-key', (req, res) => {
  res.json({ publicKey: process.env.PAYJP_PUBLIC_KEY });
});

// Charge Endpoint
app.post('/charge', async (req, res) => {
  const { token, amount } = req.body;
  try {
    const charge = await payjp.charges.create({
      amount: amount,
      currency: 'jpy',
      card: token,
    });
    res.json({ success: true, charge });
  } catch (err) {
    console.error(err);
    res.status(500).json({ success: false, error: err.message });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
  • payjp-sample-app/.env

https://pay.jp/d/settings
より「テスト秘密鍵」を PAYJP_SECRET_KEY「テスト公開鍵」を PAYJP_PUBLIC_KEY にコピーしてください。

image.png

PAYJP_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxx
PAYJP_PUBLIC_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxxxxx

3.動作確認

  • 開発環境の画面
    image.png

商品購入ページにて「カード番号」「年/月」「CVC」を入力する

入力後、「購入する」ボタンを押下してください。
成功すると、トーストが表示されます。

image.png

  • ダッシュボードを確認します。
    image.png

売上金額に1000円追加されました。🎉

いったんここまで!
あくまで、チュートリアルとしての実装です。
15分で動作確認までできたでしょうか。
日本国内向けのサービスであれば、導入を検討して良いと思いました!


参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?