>  기사  >  웹 프론트엔드  >  Astro에 Stripe을 추가하는 방법

Astro에 Stripe을 추가하는 방법

Susan Sarandon
Susan Sarandon원래의
2024-10-17 20:44:021007검색

How to add Stripe to Astro

Astro와 Stripe 통합: 단계별 가이드

이 튜토리얼에서는 새 프로젝트 생성부터 웹훅 처리 및 체크아웃 세션 생성까지 Astro 프로젝트에서 Stripe를 설정하는 방법을 보여 드리겠습니다.

1단계: 새로운 Astro 프로젝트 만들기

시작하려면 다음 명령을 사용하여 새 Astro 프로젝트를 생성해야 합니다.

npm create astro@latest

사용중인 Astro 버전은 4.16.5

2단계: 스트라이프 설치

다음으로 Stripe 패키지를 설치하세요.

npm i stripe

사용중인 Stripe 버전은 17.2.0입니다

3단계: 스트라이프 구성

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이 스트라이프 버전(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단계: 웹후크용 Stripe CLI 설정

웹후크를 사용하면 Stripe가 서버에 이벤트(예: 결제 완료)를 알릴 수 있습니다. 현지에서 이러한 이벤트를 들으려면 다음이 필요합니다.

"stripe:listen": "stripe listen --forward-to http://localhost:4321/api/webhooks/stripe"

로컬 서버가 Stripe 이벤트를 수신할 수 있도록 하려면 Stripe CLI도 설치해야 합니다. 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단계: 스트라이프 체크아웃 작업 생성

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,
      };
    },
  }),
};

여기서는 프런트엔드에서 가격 ID를 가져와 가격 목록에서 찾아봅니다. 이를 찾으면 스트라이프 체크아웃 세션을 생성하고 해당 URL을 프런트엔드로 보냅니다. 스트라이프 세션의 경우 결제 후 사용자가 리디렉션되어야 하는 성공/취소 URL을 지정해야 합니다. 또한 웹훅에 수신할 추가 메타데이터를 추가할 수도 있습니다. 여기에는 일반적으로 가격 ID와 사용자 ID를 추가합니다.

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용 웹훅 생성

마지막으로 Stripe 웹훅 이벤트를 처리합니다. 다음 코드를 사용하여 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',
                },
            },
        );
    }
};

이 웹훅은 Stripe의 checkout.session.completed 이벤트를 수신합니다. 이벤트를 수신하면 데이터베이스를 업데이트하거나, 사용자 계정에 변경 사항을 적용하거나, 기타 결제 후 작업을 실행할 수 있습니다.

결론

그렇습니다! 다음 단계를 수행하면 Stripe을 Astro 프로젝트에 성공적으로 통합할 수 있습니다. 꽤 쉽죠?

위 내용은 Astro에 Stripe을 추가하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.