Nuxt Nation カンファレンスが開催されます。11月12〜13日にご参加ください。

stripe-next
@unlok-co/nuxt-stripe

このNuxtモジュールは、クライアントサイドとサーバーサイドの両方で、NuxtアプリケーションにStripeを簡単に統合する方法を提供します。サーバーサイドでは公式のstripeパッケージを、クライアントサイドでは@stripe/stripe-jsを利用しています。

Stripe用Nuxtモジュール

npm versionnpm downloadsLicense

Stripeを使用するアプリケーション向けのNuxtモジュール。

機能

このNuxtモジュールは、クライアントサイドとサーバーサイドの両方で、NuxtアプリケーションにStripeを簡単に統合する方法を提供します。サーバーサイドでは公式のstripeパッケージを、クライアントサイドでは@stripe/stripe-jsを利用しています。

インストール

  1. プロジェクトに @unlok-co/nuxt-stripe 依存関係を追加します
npx nuxi@latest module add stripe-next
  1. nuxt.config.tsmodules セクションに @unlok-co/nuxt-stripe を追加します
export default defineNuxtConfig({
  modules: ["@unlok-co/nuxt-stripe"],
});

設定

利用可能なすべての serverConfig オプションについては、公式リポジトリのREADMEをご覧ください。 clientConfig オプションについては、公式ドキュメントをご覧ください。

オプションの使用

export default defineNuxtConfig({
  modules: ["@unlok-co/nuxt-stripe"],
  stripe: {
    // Server
    server: {
      key: process.env.STRIPE_SECRET_KEY,
      options: {
        // your api options override for stripe server side
        // https://github.com/stripe/stripe-node?tab=readme-ov-file#configuration
      },
      // CLIENT
    },
    client: {
      key: process.env.STRIPE_PUBLIC_KEY,
      // manualClientLoad: true, // if you want to have control where you are going to load the client
      // your api options override for stripe client side https://stripe.com/docs/js/initializing#init_stripe_js-options
      options: {},
    },
  },
});

または、
ランタイム設定を使用する

export default defineNuxtConfig({
  modules: ["@unlok-co/nuxt-stripe"],
  runtimeConfig: {
    // Server
    stripe: {
      key: process.env.STRIPE_SECRET_KEY,
      options: {},
    },
    // Client
    public: {
      stripe: {
        key: process.env.STRIPE_PUBLIC_KEY,
        options: {},
      },
    },
  },
});

使い方

サーバーサイド

このモジュールは、サーバーサイドでStripeインスタンスを作成するための useServerStripe 関数を提供します。このインスタンスを使用して、Stripe APIとやり取りできます。

最小限の例

import { defineEventHandler } from "h3";
import { useServerStripe } from "#stripe/server";

export default defineEventHandler(async (event) => {
  const stripe = await useServerStripe(event);
  console.info("Stripe instance:", stripe);

  return {
    version: stripe.VERSION,
  };
});

Stripe Elements用の支払いインテントを生成する

いつでも、サーバーサイドの完全なコードは playground/server/api/create-payment-intent.get.ts に、クライアントサイドの完全なコードは playground/components/OtherComponent.vue にあります。

サーバーサイドの例

export default defineEventHandler(async (event) => {
  const stripe = await useServerStripe(event);
  const orderAmount = 1400;
  let paymentIntent;

  try {
    paymentIntent = await stripe.paymentIntents.create({
      currency: "usd",
      amount: orderAmount,
      automatic_payment_methods: { enabled: true },
    });

    return {
      clientSecret: paymentIntent.client_secret,
      error: null,
    };
  } catch (e) {
    return {
      clientSecret: null,
      error: e,
    };
  }
});

クライアントサイドの例

const { stripe } = useClientStripe();

watch(
  stripe,
  async () => {
    if (stripe.value) {
      // https://github.com/stripe-samples/accept-a-payment/blob/main/payment-element/client/vue-cva/src/components/SrCheckoutForm.vue
      const { clientSecret, error } = await $fetch(
        "/api/create-payment-intent"
      );
      if (error) {
        console.error(error);
        return;
      }

      const elements = stripe.value.elements({
        clientSecret: clientSecret as string,
      });
      const linkAuthenticationElement = elements.create("linkAuthentication");
      linkAuthenticationElement.mount("#linkAuthenticationElement");
    }
  },
  {
    immediate: true,
  }
);

クライアントサイドでの使用

クライアントサイドでは、useClientStripe を使用できます。これにより、以下のオブジェクトが公開されます。

{
  stripe, // This composable is a wrap around the [`loadStripe`](https://github.com/stripe/stripe-js#loadstripe) and can be used in pages or plugins.
    isLoading, // You don't really need this in practice but we did expose it
    loadStipe; // you can also manually loadStripe if you have disabled auto load for stripe
}

実際のコードは、playground/app.vue ファイル内で確認できます。

Stripeクライアントサイドの自動ロード

<template>
  <h1>Nuxt Stripe instance</h1>
  <div>
    {{ stripe ? stripe : "Loading..." }}
  </div>
</template>

<script setup lang="ts">
import { watch } from "vue";

const { stripe, isLoading } = await useClientStripe();
</script>

クライアントサイドのStripeの手動ロード

nuxt.config.ts

stripe: {
    client: {
      // ...
      manualClientLoad: true, // this is the part you want
    },
      // ...
},

App.vue

import { useNuxtApp, useClientStripe } from "#imports";

const { loadStripe, stripe } = useClientStripe();
const nuxtApp = useNuxtApp();

// you can leave it empty if you already have defined the keys in the config or override like in this example
stripe.value = await loadStripe(nuxtApp.$config.public.stripe.key);

開発

最初のステップ:このリポジトリをクローンする

# Install dependencies
yarn install
npm install

# Generate type stubs
yarn dev:prepare
npm run dev:prepare

# Develop with the playground
yarn dev
npm run dev

# Build the playground
yarn dev:build
npm run dev:build

# Run ESLint
yarn lint
npm run lint

# Run Vitest
yarn test
yarn test:watch
npm run test
npm run test:watch

# Release new version
yarn release
npm run release