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?

Stripe サンプル「Checkout を使用した構築済みのサブスクリプション」

Posted at

image.png

はじめに

カード決済系で Stripe サービスを知りました。
まずは慣れるために Youtube で勉強です。

Stripe とは?

Stripe(ストライプ)はオンライン決済サービスです。説明はいろいろなサイトがあるので省略。

開発環境

  • OS : Windows 11 Pro
  • Node : 20.16.0
  • npm : 10.8.1
  • Cursor(IDE) : 0.42.3

サンプル作成

Stripe Checkout を使用した構築済みのサブスクリプションページ

パッケージ作成

> npm init -y

Stripe アカウント作成

  • 公開可能キー:XXX1
  • シークレットキー:XXX2

package.json

{
  "name": "node_stripe_subscription",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "latest",
    "nodemon": "latest",
    "stripe": "latest"
  }
}

server.js

// express でローカルサーバーを起動
const express = require("express");
const app = express();
const PORT = 3000;

// This is your test secret API key.
const stripe = require("stripe")(
  "XXX2"
);

// ドメイン。成功時の戻り先
const YOUR_DOMAIN = "http://localhost:3000";

// 静的ページのディレクトリ index.htmlがデフォルトで読み込まれる
app.use(express.static("public"));

// 「申し込みはこちら」ボタンの処理
app.post("/create-checkout-session", async (req, res) => {
  try {
    // 登録した商品のプライスリストを取得
    const prices = await stripe.prices.list();
    // console.log(prices);
    const session = await stripe.checkout.sessions.create({
      line_items: [
        {
          price: prices.data[0].id,
          quantity: 1,
        },
      ],
      mode: "subscription",
      success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${YOUR_DOMAIN}/cancel.html`,
    });
    // HTTPステータス303で、リダイレクト
    res.redirect(303, session.url);
  } catch (err) {
    console.log("[ERROR] " + err);
  }
});

app.listen(PORT, console.log("サーバー起動!"));

Stripe API

おわりに

今回は単純なサブスクリプション(継続支払い)の登録だけだったので、とても簡単に作成することができました。
実際には Webhookイベント をいろいろと処理するみたいなので、もっと複雑になると思われます。

作成した Stripe アカウントを削除したいんですが、アカウント削除にたどり着けない。。。


参考(感謝) 

0
0
0

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?