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. @unlok-co/nuxt-stripe 添加到 nuxt.config.tsmodules 部分
export default defineNuxtConfig({
  modules: ["@unlok-co/nuxt-stripe"],
});

配置

有关所有可用的 serverConfig 选项,请查看 官方仓库自述文件。而对于 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: {},
      },
    },
  },
});

用法

服务器端

该模块提供了一个 useServerStripe 函数,用于在服务器端创建 Stripe 实例。此实例可用于与 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 元素生成支付意图

您随时可以在 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