SAWO와 Stripe를 이용한 유료 회원제 사이트 구축

Stripe와 Sawo로 유료 멤버십 사이트 구축



Stripe: 인터넷 비즈니스를 위한 온라인 결제 처리. Stripe는 모든 규모의 온라인 비즈니스를 위한 상거래를 지원하는 결제 API 제품군입니다.

요구 사항



  • Node.js 15.5+ 이상
  • MacOS, Windows(WSL 포함) 및 Linux가 지원됨
  • npm(node.js와 함께 제공됨) 또는 yarn

  • 단계



    1. SAWO API 키 생성


  • SAWO 대시보드로 이동하거나 새 계정here을 만들고 로그인합니다.
  • SAWO 대시보드에서 왼쪽 하단에 있는 프로젝트 만들기 버튼을 클릭하여 새 프로젝트를 만듭니다.
  • 반응 프레임워크로 작업 중이고 사용자 정의 코드를 직접 작성할 것이므로 웹을 선택한 다음 코드를 선택합니다.



  • 계속을 클릭합니다. 아래와 같은 유사한 프롬프트가 표시됩니다.

  • 적절한 이름으로 프로젝트 이름을 지정하십시오.
    2.1 로컬 머신에서 개발하려면 호스트 이름을 'localhost'로 설정해야 합니다.

  • If using "localhost" as hostname is not working for you, try "127.0.0.1"



    2.2 프로덕션의 경우 호스트 이름을 도메인으로 설정해야 합니다.

    If you are adding your domain do not add 'https://', ''http://', 'www' or even trailing backslash. Example: https://dev.sawolabs.com/ should be kept as dev.sawolabs.com



    만들기 버튼을 클릭하면 API 키 생성 프롬프트와 다운로드된 SAWO 키 csv 파일을 성공적으로 볼 수 있습니다.

    2. Stripe API 키 생성 및 가격으로 제품 생성


  • Stripe 대시보드로 이동하거나 새 계정here을 만들고 로그인합니다.
  • Stripe 대시보드에서 개발자 옵션을 클릭합니다.
  • 개발자 섹션에서 API 키로 이동하면 비밀 키와 게시 가능한 키를 찾을 수 있습니다.
  • 가격이 포함된 제품을 생성하려면 제품 옵션으로 이동하십시오.
  • 제품을 생성한 후 가격 정보 앞에 가격 ID가 표시됩니다.

  • 3. 종속성 설치



    터미널에 다음 명령을 입력하여 Next.js 앱을 생성합니다.

    npm i stripe, express
    


    4. index.js 파일에 끝점을 만들고 HTML 파일을 제공합니다.


  • 이제 익스프레스 및 경로 인스턴스를 생성합니다.

  •   const express = require("express");
      const app = express();
      const path = require("path");
    


  • html 파일 제공

  •   app.use(express.static(path.join(__dirname, "public")));
      app.get("/", (req, res) => {
      res.sendFile(__dirname + "/index.html");
      });
      app.get("/login", (req, res) => {
      res.sendFile(__dirname + "/public/login.html");
      });
      app.get("/success", (req, res) => {
      res.sendFile(__dirname + "/public/success.html");
      });
      app.listen("3000", console.log("Listening on port 3000."));
    


  • 다음으로 스트라이프 인스턴스를 생성해 보겠습니다.

  •   const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY');
    


  • 위에서 생성된 가격 ID를 가져옵니다.

  •   const priceId = 'YOUR_PRICE_ID';
    


  • Stripe에 대한 체크아웃 세션 생성

  •   const session = await stripe.checkout.sessions.create({
        billing_address_collection: 'auto',
        line_items: [
          {
            price: prices.data[0].id,
            // For metered billing, do not pass quantity
            quantity: 1,
    
          },
        ],
        mode: 'subscription',
        success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${YOUR_DOMAIN}/cancel.html`,
      });
    
      res.redirect(303, session.url);
      });
    


  • 조회 키에서 가격 가져오기

  •   const prices = await stripe.prices.list({
        lookup_keys: [req.body.lookup_key],
        expand: ['data.product'],
      });
    


  • 라인 항목을 정의합니다.

  •   line_items: [
          {
            price: prices.data[0].id,
            // For metered billing, do not pass quantity
            quantity: 1,
    
          },
        ],
    


  • 성공 및 취소 URL을 정의합니다.

  •     success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${YOUR_DOMAIN}/cancel.html`,
    


  • 고객 포털 세션을 만듭니다.

  •   const returnUrl = YOUR_DOMAIN;
    
      const portalSession = await stripe.billingPortal.sessions.create({
        customer: checkoutSession.customer,
        return_url: returnUrl,
      });
    


  • 프로비저닝 액세스:

  •   app.post(
      '/webhook',
      express.raw({ type: 'application/json' }),
      (request, response) => {
        const event = request.body;
        // Replace this endpoint secret with your endpoint's unique secret
        // If you are testing with the CLI, find the secret by running 'stripe listen'
        // If you are using an endpoint defined with the API or dashboard, look in your webhook settings
        // at https://dashboard.stripe.com/webhooks
        const endpointSecret = 'whsec_12345';
        // Only verify the event if you have an endpoint secret defined.
        // Otherwise use the basic event deserialized with JSON.parse
        if (endpointSecret) {
          // Get the signature sent by Stripe
          const signature = request.headers['stripe-signature'];
          try {
            event = stripe.webhooks.constructEvent(
              request.body,
              signature,
              endpointSecret
            );
          } catch (err) {
            console.log(`⚠️  Webhook signature verification failed.`, err.message);
            return response.sendStatus(400);
          }
        }
        let subscription;
        let status;
        // Handle the event
        switch (event.type) {
          case 'customer.subscription.trial_will_end':
            subscription = event.data.object;
            status = subscription.status;
            console.log(`Subscription status is ${status}.`);
            // Then define and call a method to handle the subscription trial ending.
            // handleSubscriptionTrialEnding(subscription);
            break;
          case 'customer.subscription.deleted':
            subscription = event.data.object;
            status = subscription.status;
            console.log(`Subscription status is ${status}.`);
            // Then define and call a method to handle the subscription deleted.
            // handleSubscriptionDeleted(subscriptionDeleted);
            break;
          case 'customer.subscription.created':
            subscription = event.data.object;
            status = subscription.status;
            console.log(`Subscription status is ${status}.`);
            // Then define and call a method to handle the subscription created.
            // handleSubscriptionCreated(subscription);
            break;
          case 'customer.subscription.updated':
            subscription = event.data.object;
            status = subscription.status;
            console.log(`Subscription status is ${status}.`);
            // Then define and call a method to handle the subscription update.
            // handleSubscriptionUpdated(subscription);
            break;
          default:
            // Unexpected event type
            console.log(`Unhandled event type ${event.type}.`);
        }
        // Return a 200 response to acknowledge receipt of the event
        response.send();
      }
      );
    


  • 튜토리얼을 잘 따라오셨다면 홈페이지에서 멤버십 구매 버튼으로 이동했을 때 아래와 유사한 체크아웃 양식이 표시됩니다.





  • 결론



    축하합니다! 끝까지 하셨고 SAWO에서 인증을 구현하는 방법과 유료 멤버십을 위한 Stripe API를 통합하는 방법을 배웠습니다. 어려움에 직면한 경우 방금 살펴본 자습서working demo를 참조하십시오. 동일한 소스 코드here를 찾으십시오.

    무엇 향후 계획?



    이제 Stripe 및 Sawo를 사용하여 유료 멤버십 사이트를 구축하는 방법을 배웠으므로 자유롭게 SAWO documentation을 살펴보고 저장소에서 포크하여 이 데모 애플리케이션에 몇 가지 새로운 기능을 통합하십시오.

    좋은 웹페이지 즐겨찾기