LoginSignup
5
5

More than 1 year has passed since last update.

Next.jsとStripeで決済機能を作ってみる。【Let's ハンズオン!】

Last updated at Posted at 2021-12-12

エンジニアたるもの、ものを作るだけではなく、作ったもので儲けることこそ真の技術者やで。

そんなみんなの為にNext.jsとStripeを使って決済機能を実装したやで。

ほな、いくやで。

Next.js環境構築

まずはなにがともあれNext.jsのプロジェクトを立ち上げてみる。

npx create-next-app next-stripe-app --typescript

プロジェクトの作成が完了したら、とりあえず動かしてみるやで。

cd next-stripe-app
npm run dev

この画面になったかな?

スクリーンショット 2021-12-12 11.16.59.png

プロジェクトの概要

pages/api以下にcheckout_sessions.tsというファイルを作成してください。そうすると、プロジェクトの構成はこんな感じ。
やはりしんぷるいずべすと。

スクリーンショット 2021-12-12 11.22.04.png

Stripeインストール

標準の雛形にpages/api/checkout_sessions.tsを追加しただけやで。

次は、stripeを使うからインストール。

npm install --save stripe @stripe/stripe-js

Let's ハンズオン!

ほな、実装にうつるやで。
pages/api/checkout_sessions.tsに以下をコーディング。

pages/api/checkout_sessions.ts
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req: any, res: any) {
  if (req.method === 'POST') {
    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        line_items: [
          {
            // Provide the exact Price ID (for example, pr_1234) of the product you want to sell
            price: process.env.NEXT_PUBLIC_STRIPE_PRODUCT_KEY,
            quantity: 1,
          },
        ],
        mode: 'payment',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err: any) {
      res.status(500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

pages/index.tsxのreturnの中に、以下のコーディングを追加しておくれ。

pages/index.tsx
<form action="/api/checkout_sessions" method="POST">
        <section>
          <button type="submit" role="link">
            Checkout
          </button>
        </section>
</form>

そして、.env.localファイルを作成して、以下を書いておくれ。

NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
NEXT_PUBLIC_STRIPE_PRODUCT_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
STRIPE_SECRET_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

アカウントの設定やら、商品の登録はこちらのサイトが分かりやすかったので、掲載。
https://concrete5.co.jp/blog/stripe-subsctiption

そして、アプリの画面からbuttonをクリックすると、こんな画面がでてくればOK

スクリーンショット 2021-12-12 11.05.20.png

最後に

これでこれからバシバシ商売ができるようになるやで

みんなが大金持ちになることを祈って終わりにします。

fin

5
5
1

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