首頁 > web前端 > js教程 > 主體

如何將 Stripe 加入 Astro

Susan Sarandon
發布: 2024-10-17 20:44:02
原創
1004 人瀏覽過

How to add Stripe to Astro

將 Stripe 與 Astro 整合:逐步指南

在本教學課程中,我將向您展示如何在 Astro 專案中設定 Stripe,從建立新專案到處理 Webhooks 和建立結帳工作階段。

第 1 步:建立一個新的 Astro 項目

首先,我們需要使用以下指令建立一個新的 Astro 專案:

npm create astro@latest
登入後複製

正在使用的Astro版本是4.16.5

步驟2:安裝Stripe

接下來,安裝 Stripe 軟體包。

npm i stripe
登入後複製

正在使用的Stripe版本是17.2.0

步驟3:配置Stripe

建立一個名為 src/lib/stripe.ts 的檔案來初始化 Stripe 並處理其配置:

import Stripe from 'stripe';

if (!import.meta.env.STRIPE_SECRET_KEY) {
    throw new Error('Missing Stripe secret key');
}

export const stripe = new Stripe(import.meta.env.STRIPE_SECRET_KEY, {
    apiVersion: '2024-09-30.acacia',
});
登入後複製

這裡沒什麼特別的,只是 apiVersion 基於 stripe 版本(17.2.0 是 2024-09-30.acacia )

之後在 src/lib/get-prices.ts 中建立一個新檔案並新增以下內容:

export async function getPrices() {
    const data = [
        {
            id: 1,
            amount: 1000,
            title: 'One time Price 1',
        },
        {
            id: 2,
            amount: 1000,
            title: 'One time Price 2',
        },
        {
            id: 3,
            amount: 1500,
            credits: 10,
            title: '10 credits',
        },
        {
            id: 4,
            amount: 3000,
            credits: 25,
            title: '25 credits',
        },
    ];
    return data;
}
登入後複製

在這裡,我們將配置價格。

步驟 4:為 Webhooks 設定 Stripe CLI

Webhooks 允許 Stripe 向您的伺服器通知事件(例如付款完成)。要在本地收聽這些事件,我們需要以下內容:

"stripe:listen": "stripe listen --forward-to http://localhost:4321/api/webhooks/stripe"
登入後複製

您還需要安裝 Stripe CLI,它允許您的本機伺服器接收 Stripe 事件。有關如何安裝 Stripe CLI 的更多詳細信息,請訪問 https://docs.stripe.com/stripe-cli。

之後,運行:

npm run stripe:listen
登入後複製

它可能會要求您登錄,之後您應該會看到類似的訊息:

Ready! You are using Stripe API Version. Your webhook signing secret is whsec_something
登入後複製

步驟5:配置環境變數

在專案的根目錄中,建立一個包含以下內容的 .env 檔案:

STRIPE_SECRET_KEY=your_secret_key_from_stripe
STRIPE_SIGNING_SECRET=signing_key_from_stripe_cli
登入後複製

第 6 步:新增 Tailwind CSS 和 Node.js

對於基本樣式和處理後端請求,請將 Tailwind CSS 和 Node.js 整合加入到您的專案中:

npx astro add tailwind
npx astro add node
登入後複製

第 7 步:建立 Stripe Checkout 操作

您可以在 https://docs.astro.build/en/guides/actions/ 閱讀有關 Astro 中操作的更多資訊。

我們現在將建立一個操作來處理結帳流程。使用以下程式碼在 src/actions/index.ts 建立一個檔案:

import { ActionError, defineAction } from "astro:actions";
import { z } from "astro:schema";
import { getPrices } from "../lib/get-prices";
import { stripe } from "../lib/stripe";

export const server = {
  createCheckout: defineAction({
    input: z.object({
      priceId: z.number(),
    }),
    accept: "form",
    handler: async (input) => {
      const prices = await getPrices();
      const price = prices.find((p) => p.id === input.priceId);

      if (!price) {
        throw new ActionError({
          code: "NOT_FOUND",
          message: "Price not found.",
        });
      }

      const baseUrl = 'http://localhost:4321'; // replace with your production URL

      const stripeSession = await stripe.checkout.sessions.create({
        mode: "payment",
        payment_method_types: ["card"],
        line_items: [
          {
            quantity: 1,
            price_data: {
              unit_amount: price.amount,
              currency: "usd",
              product_data: {
                name: price.title,
                description: `Buy ${price.title} product`,
              },
            },
          },
        ],
        metadata: {
          priceId: price.id,
        },
        success_url: `${baseUrl}/?stripe=success`,
        cancel_url: `${baseUrl}/?stripe=cancel`,
      });

      if (!stripeSession.url) {
        throw new ActionError({
          code: "NOT_FOUND",
          message: "Could not create Stripe session",
        });
      }

      return {
        url: stripeSession.url,
      };
    },
  }),
};
登入後複製

在這裡,我們只是從前端獲取priceId,在我們的價格清單中找到它。如果找到它,我們將建立一個 stripe checkout 會話並將 url 傳送到前端。對於 stripe 會話,我們需要指定成功/取消 url,用戶應在付款後重定向到該 URL。此外,我們還可以將我們將收到的額外元資料添加到我們的 webhook 中。這裡通常會添加priceId和userId。

第 8 步:渲染結帳表單

現在,讓我們顯示定價卡並整合結帳按鈕。將以下程式碼加入 src/pages/index.astro:

---
import Layout from '../layouts/Layout.astro';
import { getPrices } from '../lib/get-prices';
import { actions } from 'astro:actions';

const prices = await getPrices();

const result = Astro.getActionResult(actions.createCheckout);
if (result && !result.error) {
    return Astro.redirect(result.data.url)
}
---

<Layout title="Welcome to Astro.">
    <h1 class="text-center text-5xl font-bold text-gray-200">Pricing</h1>
    <ul class="mt-12 grid grid-cols-1 gap-10 md:grid-cols-2 lg:grid-cols-3 p-4">
        {
            prices.map((price) => (
                <li class="mx-auto w-full max-w-5xl space-y-4 rounded-lg bg-gray-900 p-8 text-white">
                    <h2 class="text-2xl font-bold">{price.title}</h2>
                    <p class="mt-4 text-3xl font-bold">${price.amount / 100}</p>
                    <form method="POST" action={actions.createCheckout}>
                        <input type="hidden" name="priceId" value={price.id} />
                        <button class="bg-blue-500 text-white hover:bg-blue-600 p-4">
                            Buy
                        </button>
                    </form>
                </li>
            ))
        }
    </ul>
</Layout>
登入後複製

在這裡,我們在伺服器上獲取價格,並為每個價格創建卡片。然後,對於每個價格,我們都有一個呼叫先前定義的操作的表單,以便接收條帶結帳會話。之後,我們將使用者重新導向到條紋頁面。

第 9 步:為 Stripe 建立 Webhook

最後,處理 Stripe webhook 事件。使用以下程式碼建立檔案 src/pages/api/webhooks/stripe.ts:

import type { APIRoute } from 'astro';
import type Stripe from 'stripe';
import { stripe } from '../../../lib/stripe';

type Metadata = {
    priceId: string;
};

export const POST: APIRoute = async ({ request }) => {
    const signature = request.headers.get('stripe-signature');
    if (!signature) {
        return new Response(JSON.stringify({ error: 'Invalid signature' }), {
            status: 400,
            headers: {
                'Content-Type': 'application/json',
            },
        });
    }

    const stripeSigningSecret = import.meta.env.STRIPE_SIGNING_SECRET as string;
    try {
        const event = stripe.webhooks.constructEvent(
            await request.text(),
            signature,
            stripeSigningSecret,
        );

        const completedEvent = event.data.object as Stripe.Checkout.Session & {
            metadata: Metadata;
        };

        if (event.type === 'checkout.session.completed') {
            console.log('Paid', completedEvent.amount_total);
            console.log('Metadata', completedEvent.metadata);

            // Update your database or user status here
        }
        return new Response(JSON.stringify({ success: true, error: null }), {
            status: 200,
            headers: {
                'Content-Type': 'application/json',
            },
        });
    } catch (err) {
        return new Response(
            JSON.stringify({
                success: false,
                error: (err as { message: string }).message,
            }),
            {
                status: 500,
                headers: {
                    'Content-Type': 'application/json',
                },
            },
        );
    }
};

登入後複製

此 webhook 偵聽來自 Stripe 的 checkout.session.completed 事件。收到事件後,您可以更新資料庫、對使用者帳戶套用變更或觸發任何其他付款後操作。

結論

就是這樣!透過執行以下步驟,您可以成功地將 Stripe 整合到您的 Astro 專案中。很簡單吧?

以上是如何將 Stripe 加入 Astro的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!